Here in this post, we will see how to plot a two bar graph on a different axis and multiple bar graph using Python’s Matplotlib library on a single axis. Let’s first understand what is a bar graph. We can use a bar graph to compare numeric values or data of different groups or we can say that A bar chart is a type of a chart or graph that can visualize categorical data with rectangular bars and can be easily plotted on a vertical or horizontal axis.
Let’s see both in action:
First of all, to create any type of bar graph whether it’s a single bar graph or a multiple bar graph, we need to import libraries that will help us to implement our task.
- Pandas library in this task will help us to import our ‘countries.csv’ file.
- From NumPy library, we will use np.arange() which will work similar to a range(10) = [0,1,2,3,4,5,6,7,8,9]
- And the final and most important library which helps us to visualize our data is Matplotlib. It will help us to plot multiple bar graph.
With the below lines of code, we can import all three libraries with their standard alias.
import pandas as pd import matplotlib.pyplot as plt import numpy as np
Second, we have to import the file which we need to visualize. If you want to download and use the CSV file, you can download it from here. We can use pandas .read_csv() function as shown below:
data = pd.read_csv('countries.csv') data.head()
Now the question comes that we want to visualize is – The GDP and Population of the top 10 countries for the year 2007.
From the below code we have extracted the data only for the year 2007 and then sorted it according to the population. Also, we have taken top 10 values and stored it in the variable named datasort.
data_2007 = data[data.year == 2007] datasort = data_2007.sort_values('population', ascending = False) datasort = datasort.head(10)
Now lets plot two bar graph or bar chart plots using the below code.
x = range(10) #The below code will create two plots. The parameters that .subplot take are (row, column, no. of plots). plt.subplot(2,1,1) #This will create the bar graph for poulation pop = plt.bar(x, datasort['population']/10**6) plt.ylabel('Population in Millions') plt.xticks([],[]) #The below code will create the second plot. plt.subplot(2,1,2) #This will create the bar graph for gdp i.e gdppercapita divided by population. gdp =plt.bar(x, datasort['gdpPerCapita'] * datasort['population'] / 10 ** 9) plt.ylabel('GDP in Billions') plt.xticks(x, datasort['country'], rotation='vertical') plt.show()
Plotting multiple bar graph using Python’s Matplotlib library:
The below code will create the multiple bar graph using Python’s Matplotlib library. Have a look at the below code:
x = np.arange(10) ax1 = plt.subplot(1,1,1) w = 0.3 #plt.xticks(), will label the bars on x axis with the respective country names. plt.xticks(x + w /2, datasort['country'], rotation='vertical') pop =ax1.bar(x, datasort['population']/ 10 ** 6, width=w, color='b', align='center') #The trick is to use two different axes that share the same x axis, we have used ax1.twinx() method. ax2 = ax1.twinx() #We have calculated GDP by dividing gdpPerCapita to population. gdp =ax2.bar(x + w, datasort['gdpPerCapita'] * datasort.population / 10**9, width=w,color='g',align='center') #Set the Y axis label as GDP. plt.ylabel('GDP') #To set the legend on the plot we have used plt.legend() plt.legend([pop, gdp],['Population in Millions', 'GDP in Billions']) #To show the plot finally we have used plt.show(). plt.show()
Below you can see the multiple bar graph i.e for population and GDP on the same plot with two different x-axes on both the sides.
Hope you like our post. To learn more about Matplotlib package, you can go through the official documentation here.
john says
how to write values of each bar on the top of the bar in above example.
WeirdGeek says
In the second code, you can use ax1.text or ax2.text().
Follow the below link to get more information –
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.text.html
Fang says
Thank you for this great article! It solved the working issue for me!!
ravi says
if the categorical data can be plotted like this?