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
.
Now let’s create a vertical bar chart.
# importing the necessary libraries and modulesimport matplotlib.pyplot as pltimport numpy as np# creating the data values for the vertical y and horisontal x axisx = np.array(["Oranges", "Apples", "Mangoes", "Berries"])y = np.array([3, 8, 1, 10])# using the pyplot.bar funtionplt.bar(x,y)# to show our graphplt.show()
As seen in the code above,
matplotlib
) and modules (pyplot
and numpy
) needed to plot a bar chart.numpy.array()
, we create an array of values for the x and y axes.pyplot.bar(x, y)
function, we create a vertical bar chart with a horizontal and vertical value.pyplot.show()
function to tell Python to show our graph.It is worth noting that
pyplot.bar()
andpyplot.barh()
functions do not take only thex
andy
variables as their parameter values. They also take many other parameters, of whichcolor
is one.
Adding a color to a vertical bar chart, we simply use the command or syntax below.
pyplot.bar(x, y, color)
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.
# importing the necessary libraries and modulesimport matplotlib.pyplot as pltimport numpy as np# creating the data values for the vertical y and horisontal x axisx = 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 valueplt.bar(x,y, color = 'red')# to show our graphplt.show()
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
.