How to add colors to a bar in Matplotlib

Overview

A bar chart is a diagram in which the numerical values of variables are represented by the height or length of lines or rectangles of equal width. In simpler terms, we use bar charts to present categorical data using rectangular bars.

Bars used in this case could be both horizontal or vertical. With the pyplot module in the Matplot library, matplotlib, we are able to plot or draw the bar charts.

To plot a vertical bar chart, we use the following command:

pyplot.bar(x, y) 

To plot a horizontal bar chart, we use the following command:

pyplot.barh(x,y)

In both cases, x and y parameter values represent the values in the x and y (horizontal and vertical) axes of the plot. The only difference in both syntaxes is the h after the bar.

How to create a bar chart

Now let’s create a vertical bar chart.

# importing the necessary libraries and modules
import matplotlib.pyplot as plt
import numpy as np
# creating the data values for the vertical y and horisontal x axis
x = np.array(["Oranges", "Apples", "Mangoes", "Berries"])
y = np.array([3, 8, 1, 10])
# using the pyplot.bar funtion
plt.bar(x,y)
# to show our graph
plt.show()

Explanation

As seen in the code above,

  • In lines 2-3, we import the libraries (matplotlib) and modules (pyplot and numpy) needed to plot a bar chart.
  • In lines 6-7, with numpy.array(), we create an array of values for the x and y axes.
  • In line 11, using the pyplot.bar(x, y) function, we create a vertical bar chart with a horizontal and vertical value.
  • In line 14, we use the pyplot.show() function to tell Python to show our graph.

How to add color to a bar chart

It is worth noting that pyplot.bar() and pyplot.barh() functions do not take only the x and y variables as their parameter values. They also take many other parameters, of which color is one.

Adding a color to a vertical bar chart, we simply use the command or syntax below.

Syntax

pyplot.bar(x, y, color)

Parameters

  • x and y are the data values for the horizontal and vertical axes of the plot respectively.

  • color is simply the color we wish to add to the bars.

Example

# importing the necessary libraries and modules
import matplotlib.pyplot as plt
import numpy as np
# creating the data values for the vertical y and horisontal x axis
x = np.array(["Oranges", "Apples", "Mangoes", "Berries"])
y = np.array([3, 8, 1, 10])
# using the pyplot.bar funtion and assigning the color red as the color value
plt.bar(x,y, color = 'red')
# to show our graph
plt.show()

Explanation

The code above is just like the previous code. The only difference here is that the pyplot.bar() contains the color parameter to which we assigned red.