WeirdGeek

Data Science | Machine Learning | Automation

  • Data Analytics
  • Python
  • Data Science
  • Google Apps Script
  • Machine Learning
  • Artificial Intelligence
  • SQL Server

23/11/2018 By WeirdGeek 4 Comments

Plotting multiple bar graph using Python’s Matplotlib library

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()

multiple bar graph using Python's Matplotlib library

 

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.

 

Plotting multiple bar charts using Matplotlib library in Python

 

Hope you like our post. To learn more about Matplotlib package, you can go through the official documentation here.

 

Related posts:

  1. Plot multiple bar graph using Python’s Plotly library
  2. Plotting stacked bar graph using Python’s Matplotlib library
  3. Plotting multiple histograms with different length using Python’s Matplotlib library
  4. Plotting stacked histogram using Python’s Matplotlib library

Filed Under: Data Analytics, Python Tagged With: Matplotlib, Pandas, Python

Comments

  1. john says

    06/11/2019 at 5:16 pm

    how to write values of each bar on the top of the bar in above example.

    Reply
    • WeirdGeek says

      06/11/2019 at 10:29 am

      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

      Reply
  2. Fang says

    20/03/2020 at 5:11 pm

    Thank you for this great article! It solved the working issue for me!!

    Reply
  3. ravi says

    22/11/2020 at 6:00 am

    if the categorical data can be plotted like this?

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Subscribe to my Blog !!

Enter your email below to subscribe my blog and get the latest post right in your inbox.

  • Home
  • Terms
  • Privacy
  • Contact Us

Copyright © 2025 · WeirdGeek · All trademarks mentioned are the property of their respective owners.