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, they present categorical data using rectangular bars. Bars used in this case could be horizontal or vertical. We can plot bar charts with the pyplot
module in the Matplot library, `matplotlib.
To plot a bar chart, we use the following command:
pyplot.bar(x, y)
Here the x
and y
parameter values represent the horizontal and vertical axis of the plot, respectively.
It is worth noting that the
pyplot.bar
function takes more parameter values other than just thex
andy
axis values. However, it is beyond the scope of this shot to look at the other parameters.
A vertical bar represents the data vertically. Hence, its bars are drawn vertically. In such a chart, the data categories are shown on the x-axis while the data values are shown on the y-axis.
# 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, we first import the libraries (matplotlib
) and the modules (pyplot
and numpy
) needed to plot a bar chart. With numpy.array()
, we create an array of values for the x
and y
axes. Then, using the pyplot.bar(x, y)
function, we create a vertical bar chart with horizontal and vertical values. Lastly, we use the pyplot.show()
function to display our graph.
A horizontal bar chart represents the data horizontally. Hence, its bars are drawn horizontally. The data categories are shown on the y-axis, while the data values are shown on the x-axis.
The unique thing about the syntax for the horizontal bar chart is the h
after the bar
pyplot.barh(x, y)
# 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.barh funtion for the horizontal barplt.barh(x,y)# to show our graphplt.show()
We can see that the only difference between the vertical and horizontal bar charts is their syntax. We use the pyplot.bar()
function for a vertical bar chart and the pyplot.barh()
function for a horizontal bar chart.