Matplotlib multiple bar chart

In this Matplotlib tutorial, we will discuss Matplotlib multiple bar chart in python. Here we will cover different examples related to the multiple bar chart using matplotlib. And we will also cover the following topics:

  • Matplotlib multi bar chart
  • Matplotlib multiple bar chart example
  • Matplotlib multiple bar charts side by side
  • Matplotlib multiple horizontal bar chart
  • Matplotlib mutiple bar chart pandas
  • Matplotlib bar chart multiple columns
  • Matplotlib bar chart multiple colors
  • Matplotlib overlay two bar chart
  • Matplotlib multiple stacked bar chart
  • Matplotlib bar chart multiple groups
  • Matplotlib multiple bar chart labels
  • Matplotlib multiple bar chart title

Matplotlib multi bar chart

In this section, we learn about how to plot multi bar charts in matplotlib in Python. Before starting the topic, firstly we have to understand what does multi bar chart means:

Multi bar Chart means Multiple Bar Chart. It is also known as Grouped Bar Chart.

A multiple bar graph is used to portray the relationship between various data variables. And column in the graph represents each data value. Basically, multiple bar charts are used for comparing different entities.

The following steps used to plot multi bar chart graphs are outlined below:

  • Defining Libraries: Import the libraries which is required to plot multi bar chart graphs and data visualization pyplot and also import other libraries which are required for data creation and manipulation numpy and pandas.
  • Define Data: Define the data coordinates values of the x-axis and y-axis used for plotting.
  • Plot Multi Bar Chart: By using the bar() method of the matplotlib library we can draw multiple bar charts.
  • Visualize a Plot: By using the show() method users can generate a plot on their screen.

The syntax for multiple bar chart graph plotting is given below:

matplotlib.pyplot.bar(x, height, width=None, bottom=None, align='center', data=None, **kwargs)

The parameters are defined below:

  • x: specify the x-coordinates of the bars.
  • height: y-coordinates specify the height of the bars.
  • width: specify the width of the bars.
  • bottom: specify the y coordinates of the bases of the bars.
  • align: alignment of the bars.

Matplotlib multiple bar chart example

Let’s see different examples to understand the concept more clearly:

Example #1

# Import Library

import numpy as np 
import matplotlib.pyplot as plt 

# Define Data

team = ['Team 1','Team 2','Team 3','Team 4','Team 5']
female = [5, 10, 15, 20, 25]
male = [15, 20, 30, 16, 13]

x_axis = np.arange(len(team))

# Multi bar Chart

plt.bar(x_axis -0.2, female, width=0.4, label = 'Female')
plt.bar(x_axis +0.2, male, width=0.4, label = 'Male')

# Xticks

plt.xticks(x_axis, team)

# Add legend

plt.legend()

# Display

plt.show()
  • In the above example, we import libraries such as numpy and matplotlib.pyplot.
  • After this, we define data for plotting.
  • np.arange() method is used to create a range of values.
  • Then plt.bar() function is used to plot multiple bar charts.
  • Then we shift bars -0.2 and 0.2 units from the x-axis to avoid overlapping.
  • Then we set the width of the bars to 0.4.
matplotlib mutiple bar chart example
plt.bar()

Example #2

# Import Library

import numpy as np 
import matplotlib.pyplot as plt 

# Define Data

team = ['Team 1','Team 2','Team 3']
Python = [5, 10, 15]
Java = [15, 20, 30]
Php = [ 5, 9, 12]

x_axis = np.arange(len(team))

# Multi bar Chart

plt.bar(x_axis +0.20, Python, width=0.2, label = 'Python')
plt.bar(x_axis +0.20*2, Java, width=0.2, label = 'Java')
plt.bar(x_axis +0.20*3, Php, width=0.2, label = 'Php')

# Xticks

plt.xticks(x_axis,team)

# Add legend

plt.legend()

# Display

plt.show()
  • In the above example, we import required libraries such as numpy, pyplot.
  • Then we define data for plotting.
  • After this, we use arange() method of numpy to get the length of the x-axis.
  • plt.bar() method is used to plot multiple bar chart graphs.
  • plt.xticks() function defines x ticks and plt.legend() method is used to add legend.
matplotlib multiple bar chart with example
” Multiple Bar Chart ”

Read: Matplotlib scatter plot legend

READ:  How to Print Duplicate Elements in Array in Python

Matplotlib multiple bar charts side by side

Here we are going to plot multiple bar charts side by side. For plotting side by side, we have to draw subplots.

Let’s see an example of multiple bar charts side by side:

# Import Library

import numpy as np 
import matplotlib.pyplot as plt 

# Define Data

x1 = [2.5, 3.5, 4.5, 5.5, 6.5, 7.5]
y1 = [3, 6, 9, 12, 15, 18]

x2 = [5, 10, 15, 20, 25, 30]
y2 = [2.6, 9.5, 14, 12, 8.3, 12]

r = np.arange(6)
width = 0.4

# Draw first subplot

plt.subplot(1, 2, 1)
plt.bar(r, x1, width=width)
plt.bar(r + width, y1, width=width)

# Draw second subplot

plt.subplot(1, 2, 2)
plt.bar(r, x2, width=width)
plt.bar(r + width, y2, width=width)

# Display

plt.show()
  • In the above example, we import numpy and matplotlib.pyplot library.
  • After this, we define data that is used for plotting.
  • Then we use the np.arange() function to create a range of values.
  • By using plt.subplot() method we create two subplots side by side.
  • plt.bar() method is used to create multiple bar chart graphs.
matplotlib multiple bar charts side by side
“Multiple Bar Graphs Side By Side”

Read: Matplotlib title font size

Matplotlib multiple horizontal bar chart

Here we are going to learn how we can plot grouped bar charts or we can say that multiple bar charts in the horizontal direction.

Firstly, we have to know the syntax to create a horizontal bar chart:

matplotlib.pyplot.barh(y, width, height=0.8, left=none, align='center', **kwargs)

The parameters used are described below:

  • y: specify coordinates of the y bars.
  • width: specify the width of the bars.
  • height: specify the height of the bars.
  • left: specify the x coordinates of the left sides of the bars.
  • align: alignment of the base to the y coordinates.

Let’s have a look at an example where we plot multiple horizontal bar charts:

# Import Library

import matplotlib.pyplot as plt
import pandas as pd

# Define Data

data = {'Girls': [15, 20, 25, 30, 35],
        'Boys': [25, 30, 28, 19, 40] }
df = pd.DataFrame(data,columns=['Girls','Boys'], index = ['Team-1','Team-2','Team-3','Team-4','Team-5'])

# Multiple horizontal bar chart

df.plot.barh()

# Display

plt.show()
  • In the above example, we define data by using Pandas DataFrame.
  • Then we use a plot.barh() method to draw multiple horizontal bar charts.
  • plt.show() method is used to visualize the plot on the user’s screen.
matplotlib mutiple horizontal bar chart
” Horizontal Multiple Bar Chart “

Read: Matplotlib default figure size

Matplotlib multiple bar chart pandas

Here we are going to learn how to plot multiple bar charts by using pandas DataFrame.

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt
import pandas as pd

# Define Data

data = {'Girls': [15, 20, 25, 30, 35],
        'Boys': [25, 30, 28, 19, 40] }
df = pd.DataFrame(data,columns=['Girls','Boys'], index = ['MCA','BCA','MCOM','BCOM','BA'])

# Multiple bar chart

df.plot.bar()

# Display

plt.show()
  • In the above example, we import important libraries such as pandas and pyplot.
  • Next, we define data using Pandas DataFrame.
  • plot.bar() method is used to create multiple bar charts.
matplotlib multiple bar chart pandas
” Multiple Bar Chart Using Pandas “

Read: Matplotlib savefig blank image

Matplotlib bar chart multiple columns

Here we are doing to learn how can we plot a bar chart having multiple columns. We use the plot() method to draw a bar chart and to define multiple columns, we use the DataFrame object.

Example:

Here we are going to create multiple bar charts by using the DataFrame object of Pandas. We create a bar chart having 5 multiple columns.

# Import Library

import pandas as pd 
import matplotlib.pyplot as plt 

# Define Data

data=[["A",40, 36, 38, 35, 40],
      ["B",39, 37, 33, 38, 32],
      ["C",28, 30, 33, 39, 24],
      ["D",40, 40, 35, 29, 35],
      ["E", 28, 25, 16, 27, 30]
     ]
# Plot multiple columns bar chart

df=pd.DataFrame(data,columns=["Name","English","Hindi","Maths", "Science", "Computer"])

df.plot(x="Name", y=["English","Hindi","Maths", "Science", "Computer"], kind="bar",figsize=(9,8))

# Show

plt.show()
  • In the above example, we import pandas and pyplot libraries.
  • After this, we define data and create DataFrame.
  • Then we use the plot() function to draw bar a chart with 5 multiple columns. Here we pass kind as a parameter to mention plot is of bar type.
matplotlib bar chart multiple columns
” Bar Chart with 5 multiple columns “

Read: Matplotlib save as png

READ:  Pandas iterrows update value in Python [4 Ways]

Matplotlib bar chart multiple colors

Here we are going to create grouped bar chart with different colors of bars.

To change the colors of the bar we have to pass color as a parameter and pass the list of different colors as values.

The syntax to change color is given below:

matplotlib.pyplot.bar(x, height, color=None ...)

Here color parameter is used to set the colors of bars according to our choice.

Let’s see some examples:

Example:

# Import Library

import pandas as pd 
import matplotlib.pyplot as plt 

# Define Data

data=[["Team A",10, 5, 3],
      ["Team B",6, 3, 8],
      ["Team C",4, 12, 5],
      ["Team D",8, 9, 5]
     ]

# Colors 

my_color =['yellow', 'cyan','m','blue']

# Plot multiple bar chart with color of your choice

df=pd.DataFrame(data,columns=["Team","Web Development", "Andriod", "IoT"])

df.plot(x="Team", y=["Web Development", "Andriod", "IoT"], 
        kind="bar",figsize=(8,4), color=my_color)

# Show

plt.show()

In the above example, we create a list of colors and pass it to the color parameter of the plot() method, so that we can set the colors of the bars according to our choice.

matplotlib bar chart multiple colors
plot(kind=bar, color=my_color)

Example:

# Import Library

import numpy as np 
import matplotlib.pyplot as plt 

# Define Data

team = ['Team 1','Team 2','Team 3','Team 4','Team 5']
female = [5, 10, 15, 20, 25]
male = [15, 20, 30, 16, 13]

x_axis = np.arange(len(team))

# Multiple colors of bars

plt.bar(x_axis -0.2, female, width=0.4, 
        label = 'Female', color='k')

plt.bar(x_axis +0.2, male, width=0.4, 
        label = 'Male', color='g')

# Xticks

plt.xticks(x_axis, team)

# Add legend

plt.legend()

# Display

plt.show()

In the above example, we use two plt.bar() method to create multiple bars and to each function, we pass a color parameter to set the value of bars according to our choice.

matplotlib bar chart having multiple colors
plt.bar(color=None)

Read: Matplotlib bar chart labels

Matplotlib overlay two bar chart

Here we are going to learn how we can overlay one bar inside another bar of the bar chart.

Let’s see an example of overlay two bar chart:

# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Define Data

x = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 12.5, 14.5]

y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

ind = np.arange(14)

# Create figure

fig = plt.figure()
ax = fig.add_subplot(111)

# Multiple bar chart

ax.bar(x=ind, height=x, width=0.55,align='center')
ax.bar(x=ind, height=y, width=0.55/3,  align='center')

# Define x-ticks

plt.xticks(ind, x)

# Layout and Display

plt.tight_layout()
plt.show()
  • In the above example, we import numpy and matplotlib libraries.
  • After this, we define data used for plotting multiple bar charts.
  • Then we create a figure and also use the add_figure() method to create subplots.
  • ax.bar() method is used to create multiple bar charts in which one bar overlays another bar. Here we divide the width of the bar which resides inside another bar.
matplotlib overlay two bar chart
” Overlay two bar chart “

Read: Matplotlib plot error bars

Matplotlib multiple stacked bar chart

Here we are going to learn how we can create grouped stacked bar charts. Firstly, we have understood what does stacked bar chart means:

Stacked Bar Chart is a graph that is used to compare parts of whole. When we have multiple sets of data in a single category we can drawbar for each set of data and place that bars one above the another. “

Let’s have a look at an example:

# Import Library

import matplotlib.pyplot as plt
import pandas as pd

# Define Data

df = pd.DataFrame(dict(
    x1=[3, 4, 5, 6],
    x2=[5, 9, 11.2, 14],
    x3=[1.6, 3, 4, 6.5],
    x4=[4.5, 5.5, 8.9, 12]))

# Stacked grouped bar chart

plt.bar([0, 1, 2, 3], df.x2, align='edge', width= 0.4,color='g')
plt.bar([0, 1, 2, 3], df.x1, align='edge', width= 0.4,color='c')
plt.bar([0, 1, 2, 3], df.x4, align='edge',width= -0.4, color='r')
plt.bar([0, 1, 2, 3], df.x3, align='edge',width= -0.4,color='y')

# Show

plt.show()
  • In the above example, we define data using DataFrame.
  • Then we draw a stacked multiple bar chart by mentioning data points in such a way that it creates stacked bars.
matplotlib multiple stacked bar chart
“Stacked Multiple Bar Chart”

Read: Matplotlib rotate tick labels

READ:  Python Tkinter panel

Matplotlib bar chart multiple groups

Here we are going to create a bar chart having multiple groups. Multiple groups and multiple columns mean the same.

Let’s see an example where we draw a bar chart with multiple groups.

Here we create a bar chart with 6 groups.

# Import Library

import pandas as pd 
import matplotlib.pyplot as plt 

# Define Data

data=[["Team A", 500, 100, 350, 250, 400, 600],
      ["Team B", 130, 536, 402, 500, 350, 250],
      ["Team C", 230, 330, 500, 450, 600, 298],
      ["Team D", 150, 398, 468, 444, 897, 300]
     ]

# Plot multiple groups

df=pd.DataFrame(data,columns=["Team","January", "March", "May", "July", "September", "November"])

df.plot(x="Team", y=["January", "March", "May", "July", "September", "November"], kind="bar",
 figsize=(8,4))

# Show

plt.show()
  • In the above example, we import pandas and matplotlib.pyplot libraries.
  • Next, we create DataFrame.
  • Then we plot a bar chart with 6 multiple groups by using plot() method.
matplotlib bar chart multiple groups
” Multiple Groups Bar Chart “

Read: Matplotlib scatter marker

Matplotlib multiple bar chart labels

Here we are going to learn how we can add labels to multiple bar charts.

The syntax to add labels:

# X-axis label
matplotlib.pyplot.xlabel()

# Y-axis label
matplotlib.pyplot.ylabel()

Example:

# Import Library

import numpy as np 
import matplotlib.pyplot as plt 

# Define Data

team = ['Team 1','Team 2','Team 3','Team 4','Team 5']
female = [5, 10, 15, 20, 25]
male = [15, 20, 30, 16, 13]

x_axis = np.arange(len(team))

# Multi bar Chart

plt.bar(x_axis -0.2, female, width=0.4, label = 'Female')
plt.bar(x_axis +0.2, male, width=0.4, label = 'Male')

# Xticks

plt.xticks(x_axis, team)

# Add labels

plt.xlabel("Team", fontsize=12, fontweight='bold')
plt.ylabel("No.of Persons", fontsize=12, fontweight='bold')

# Add legend

plt.legend()

# Display

plt.show()
  • In the above example, we define labels at the x-axis and y-axis by using plt.xlabel() and plt.ylabel() respectively.
  • To create multiple bar chart we use plt.bar() method.
matplotlib multiple bar cahrt labels
” Multiple Bar Chart with Labels “

Read: Matplotlib dashed line

Matplotlib multiple bar chart title

Here we are going to create multiple bar chart with a title. To add a title we use the title() function.

The syntax to add a title is given below:

matplotlib.pyplot.title()

Example:

# Import Library

import pandas as pd 
import matplotlib.pyplot as plt 

# Define Data

data=[["Team A",10, 5, 3],
      ["Team B",6, 3, 8],
      ["Team C",4, 12, 5],
      ["Team D",8, 9, 5]
     ]

# Colors 

my_color =['yellow', 'cyan','m','blue']

# Plot multiple bar chart 

df=pd.DataFrame(data,columns=["Team","Web Development", "Andriod", "IoT"])

df.plot(x="Team", y=["Web Development", "Andriod", "IoT"], kind="bar",
        figsize=(8,4), color=my_color)

# Add title

plt.title("Studenr vs Courses")

# Show

plt.show()

In the above example, we use plt.title() method to add a title to multiple bar charts.

matplotlib multiple bar chart title
Multiple Bar Chart with Title”

You may also like to read the following tutorials on Matplotlib.

In this Python tutorial, we have discussed the “Matplotlib multiple bar chart” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib multi bar chart
  • Matplotlib multiple bar chart example
  • Matplotlib multiple bar charts side by side
  • Matplotlib multiple horizontal bar chart
  • Matplotlib mutiple bar chart pandas
  • Matplotlib bar chart multiple columns
  • Matplotlib bar chart multiple colors
  • Matplotlib overlay two bar chart
  • Matplotlib multiple stacked bar chart
  • Matplotlib bar chart multiple groups
  • Matplotlib multiple bar chart labels
  • Matplotlib multiple bar chart title