In this Python tutorial, we will discuss Stacked bar chart matplotlib in python. Here we will cover different examples related to the stacked bar chart using matplotlib. And we will also cover the following topics:
- Stacked bar chart matplotlib
- Matplotlib how to plot stacked bar chart
- Stacked bar chart matplotlib example
- Stacked bar chart with labels matplotlib
- Stacked bar chart legend matplotlib
- Stacked bar chart matplotlib color
- Stacked bar chart pandas dataframe
- Stacked bar chart using for loop
- Matplotlib stacked bar chart with value
- Matplotlib stacked bar chart with negative value
- Matplotlib stacked bar chart error
- Horizontal stacked bar chart in matplotlib
Stacked bar chart matplotlib
In this section, we learn about how to plot stacked bar charts in matplotlib in Python. Before starting the topic, firstly we have to understand what is stacked bar chart is:
A stacked bar chart is also known as a stacked bar graph. It is a graph that is used to compare parts of a whole. In a stacked bar chart each bar represents the whole, and the segments or parts in the bar represent categories of that whole. Different colors are used to represent these categories.
Matplotlib how to plot stacked bar chart
When we have multiple sets of data in a single category we can drawbar for each set of data and pace that bars one above the another.
The height of the bar in the stacked bar chart depends on the resulting height of the combination of the results of the groups. Or we can say the sum of the height of each bar.
To plot the stacked bar graph in the bar function the bottom parameter is very important. As we have to drawbars one above the other, so the bottom of the next bar is equal to the value of the previous bar.
The following steps are used to plot the stacked bar chart in matplotlib is outlined below:
- Defining Libraries: Import the important libraries which are required (For data creation and manipulation: Numpy and Pandas, For data visualization: pyplot from matplotlib).
- Define X and Y: Define the data coordinated values used for the x-axis and y-axis or we can say that x-axis and height of the bar.
- Plot bar chart: By using bar() method we can bar chart.
- Set bottom: Set bottom of the next bar equalls to the values of the pervious bars.
- Generate a Plot: Use the show() method to visulaize the plot on the user’s windows.
Read How to install matplotlib python
Stacked bar chart matplotlib example
Here we plot a stacked bar chart between students in different classes. The student is divided into two stacks Girls and Boys.
Code:
# Import Library
import matplotlib.pyplot as plt
# Define Data
Class = ["First", "Second", "Third", "Fourth", "Fifth"]
Boys = [15, 20, 16, 18, 25]
Girls = [10, 12, 5, 9, 15]
# Define width of stacked chart
w = 0.6
# Plot stacked bar chart
plt.bar(Class, Boys, w)
plt.bar(Class, Girls, w, bottom=Boys)
# Display
plt.show()
- In the above example, we import matplotlib.pyplot library for data visualization.
- After this, we define data that were used for plotting and the width of the stacked bar chart.
- Then by using the plt.bar() method, we draw a bar chart and we define the bottom as a parameter so that bars draw one above the another.
- For visualization of the chart on the user’s screen, we use plt.show() method.
Stacked bar chart with labels matplotlib
In this section, we are going to learn how to create a stacked bar chart with labels in matplotlib.
To add labels on x-axis and y-axis we have to use plt.xlabel() and plt.ylabel() method respectively.
The of the method to add labels is given below:
# To add labels on x-axis
matplotlib.pyplot.xlabel(xlabel, fontdict=None,
labelpad=None, loc=None, **kwargs)
# To add labels on y-axis
matplotlib.pyplot.ylabel(ylabel, fontdict=None,
labelpad=None, loc=None, **kwargs)
The parameters used above are:
- xlabel and ylabel: specify the label text.
- labelpad: specify the spacing.
- loc: specify the location of the label.
- kwargs: More text properties.
Let’s see an example of a stacked bar chart with labels:
# Import Library
import matplotlib.pyplot as plt
# Define Data
Class = ["First", "Second", "Third", "Fourth", "Fifth"]
Pass = [30, 33, 20, 26, 15]
Fail = [1, 2, 3, 1, 4]
# Define width of stacked chart
w = 0.6
# Plot stacked bar chart
plt.bar(Class, Pass, w)
plt.bar(Class, Fail, w, bottom=Pass)
# Add labels
plt.xlabel("Classes")
plt.ylabel("No.of students")
# Display
plt.show()
- In the above we use plt.bar() method with bottom argument to plot a stacked bar chart.
- After this we use plt.xlabel() method to define x-axis label.
- plt.ylabel() method is used to define what does y-axis represent or we can say that y-axis label is defined.
Stacked bar chart legend matplotlib
In this section, we are going to learn how to create a stacked bar chart with a legend in matplotlib. To add a legend use plt.legend() method.
The syntax to add legend is given below:
matplotlib.pyplot.legend()
Let’s see an example:
# Import Library
import matplotlib.pyplot as plt
# Define Data
Class = ["First", "Second", "Third", "Fourth", "Fifth"]
Male = [15, 20, 16, 18, 25]
Female = [10, 12, 5, 9, 15]
# Define width of stacked chart
w = 0.6
# Plot stacked bar chart
plt.bar(Class, Male, w, label='Male')
plt.bar(Class, Female, w, bottom=Male, label='Female')
# Add labels
plt.xlabel("Classes")
plt.ylabel("Students")
# Add legend
plt.legend()
# Display
plt.show()
- In the above example, we plot a stacked bar chart between students and classes. Here student bar is stacked into two categories Male and Fale.
- Here we pass the label as an argument in a bar() method and set the text of the label to be printed.
- plt.legend() method is used to add a legend to the plot.
Stacked bar chart matplotlib color
Here we are going to learn how we can change the color of the stacked bars in the stacked bar chart in matplotlib. Bypassing the color to the bar() method we can easily change the color.
The syntax to change the color of the bars is as given below:
matplotlib.pyplot.bar(x, height, bottom, color)
The parameters used above are:
- x: specify the x-axis
- height: specify the y-axis.
- bottom: specify the value on which another bar is plotted.
- color: specify the color.
Let’s see an example where we change the color of the bars of the stacked bar chart:
# Import Library
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import figure
# Set figure size
figure(figsize=(9,6))
# Define Data
x = ['Class 1', 'Class 2', 'Class 3', 'Class 4', 'Class 5']
A = np.array([35, 30, 29, 28, 26])
B = np.array([10, 15, 16, 9, 11])
C = np.array([5, 6, 9, 10, 8])
D = np.array([2, 1, 3, 2, 1])
# Plot stacked bar chart
plt.bar(x, A, color='cyan', label='A')
plt.bar(x, B, bottom=A, color='green', label='B')
plt.bar(x, C, bottom=A+B, color='red', label='C')
plt.bar(x, D, bottom=A+B+C, color='yellow', label='D')
# Define labels
plt.xlabel("Classes")
plt.ylabel("Students")
# Add legend
plt.legend(loc=1)
# Display
plt.show()
- In the above example, we import matplotlib.plot, numpy, and figure library.
- Next, we set figsize by using figure() method and define data using array() method of numpy.
- Then by using plt.bar() method and by passing the bottom as a parameter we plot stacked bar chart.
- Here we also pass color as argument to plt.bar() method to change color of the stacks.
- plt.xlabel() and plt.ylabel() method is used to add x-axis label and y-axis label respectively.
- plt.legend() method is used to add legend to the plot.
- plt.show() method is used to visualize plot on the user’s screen.
Also read, Horizontal line matplotlib
Stacked bar chart pandas dataframe
Here we are going to learn how we can create a stacked bar chart using pandas dataframe. Firstly, you have to know how to create a dataframe in pandas.
Syntax to create dataframe in pandas:
class pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=None)
The parameters used above are:
- data: specify data.
- index: specify an index.
- columns: specify the columns for the resulting frame.
- dtype: specify a data type.
- copy: copy data from inputs.
Let’s see an example where we create a stacked bar chart using pandas dataframe:
# Import Library
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Create Dataframe
df = pd.DataFrame([['A', 10, 12, 2, 20],
['B', 10, 23, 12, 18],
['C', 12, 15, 19, 6],
['D', 10, 18, 11, 19]],
columns=['Team', 'C++', 'Java', 'Python', 'Php'])
# View Data
print(df)
# Plot stacked bar chart
df.plot(x='Team', kind='bar', stacked=True,
title='Stacked Bar Chart Pandas Dataframe',
figsize=(12,6))
# Rotate tick label
plt.xticks(rotation='horizontal')
# Show
plt.show()
- In the above example, we import matplotlib.pyplot, numpy, and pandas library.
- After this, we create data by using the DataFrame() method of the pandas.
- Then, print the DataFrame and plot the stacked bar chart by using the plot() method.
- plt.xticks() method is used to create tick labels and rotation argument is used to rotate tick label we set it to horizontal.
Read Draw vertical line matplotlib
Stacked bar chart using for loop
Here we learn to create a stacked bar chart using for loop in Python matplotlib.
Let’s see an example:
# Import Library
import numpy as np
import matplotlib.pyplot as plt
# Define Data
data = np.array([[5, 15, 12, 10, 7, 6],
[10, 19, 13, 9, 6, 9],
[4, 8, 6, 8, 3, 7],
[6, 9, 4, 3, 15, 19],
[9, 15, 19, 16, 8, 6]])
list = ['red','blue', 'yellow','pink','cyan','orange']
# For loop for creating stacked bar chart
X = np.arange(data.shape[1])
for i in range(data.shape[0]):
plt.bar(X, data[i],bottom = np.sum(data[:i],
axis =0),color = list[i % len(list)] )
# Display
plt.show()
- In the above example, we import matplotlib.pyplot, numpy library.
- Then we store data in the NumPy array.
- Next, we iterate each row of data. Here for the bottom parameter, the ith row receives the sum of all rows.
- plt.bar() method is used to create a stacked bar chart.
Matplotlib stacked bar chart with value
Here we are going to create a stacked bar chart with values using matplotlib.
Let’s see an example of a stacked bar chart with value:
# Import libraries
import matplotlib.pyplot as plt
import pandas as pd
# Define Data
df = pd.DataFrame({
'Male': [35, 20, 43, 12, 19],
'Female': [20, 11, 18, 6, 9]
})
Class = ["Fisrt","Second","Third","Fourth","Fifth"]
# Plot stacked bar chart
ax = df.plot(stacked=True, kind='bar')
for bar in ax.patches:
height = bar.get_height()
width = bar.get_width()
x = bar.get_x()
y = bar.get_y()
label_text = height
label_x = x + width / 2
label_y = y + height / 2
ax.text(label_x, label_y, label_text, ha='center',
va='center')
# Set Tick labels
ax.set_xticklabels(Class,rotation='horizontal')
# Display chart
plt.show()
- In the above example, we import matplotlib.pyplot, and pandas library.
- After this, we create DataFrame and define a list of Class.
- Then by using the plot() method plot stacked bar chart.
- Define for loop in patches and patches consist of everything inside the chart.
- By using get_height() and get_width() method we get height and width.
- At last, we use the text() method to define the height of each of the stacked bars or we can say that to add values to the bars.
Read Put legend outside plot matplotlib
Matplotlib stacked bar chart with negative value
Here we are going to plot a stacked bar chart having a negative value using Python matplotlib.
Let’s see an example:
# Import Library
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import figure
# Set figure size
figure(figsize=(9,6))
# Define Data
x = np.arange(3)
y1 = np.array([4, -6, -4])
y2 = np.array([2, -4, -2])
y3 = np.array([3, -3, -5])
y4 = np.array([4, -2, -3])
# Plot stacked bar chart
plt.bar(x, y1, color='cyan')
plt.bar(x, y2, bottom=y1, color='green')
plt.bar(x, y3, bottom=y1+y2, color='red')
plt.bar(x, y4, bottom=y1+y2+y3, color='yellow')
# Define labels
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# Display
plt.show()
- In the above example, we define data using the array() method of numpy, and data defined have negative values.
- plt.bar() method is used to plot the bar chart and we pass the bottom as a parameter to make it a stacked bar chart.
Matplotlib stacked bar chart error
In this section, we learn how to plot a stacked bar chart with errors.
Let’s see an example where we plot a stacked bar chart with error:
# Import Library
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = [5, 4, 9]
y = [2, 3, 3]
z = [7, 6, 8]
# Error bars
x_error = np.std(x)
y_error = np.std(y)
z_error = np.std(z)
ind = np.arange(len(bars))
bar_padding = np.add(x, y).tolist()
# Standard Bar Chart
plt.bar(ind, x, yerr=x_error)
plt.bar(ind, y, yerr=y_error, bottom=x)
plt.bar(ind, z, yerr=z_error, bottom=bar_padding)
# Display chart
plt.show()
- In the above example, we import matplotlib.pyplot and numpy library.
- Then we define data and errors.
- Next, by using plt.bar() method we plot the stacked bar chart and we pass the bottom as a parameter.
Read Matplotlib title font size
Horizontal stacked bar chart in matplotlib
To create a horizontal stacked bar chart in matplotlib we use the barh() method and instead of the bottom argument we pass left as an argument to the method.
The syntax to draw horizontal stacked 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 x-coordinates.
Let’s see an example:
# Import Library
import matplotlib.pyplot as plt
# Define Data
Class = ["First", "Second", "Third", "Fourth", "Fifth"]
Boys = [15, 20, 16, 18, 25]
Girls = [10, 12, 5, 9, 15]
# Define height of stacked chart
h = 0.6
# Plot stacked bar chart
plt.barh(Class, Boys, w)
plt.barh(Class, Girls, w, left=Boys)
# Display
plt.show()
- In the above example, we import matplotlib.pyplot library.
- After this, we define the data and height of the bars.
- Then by using the plt.barh() method we draw a bar chart and bypass left as a parameter we create it into the stacked chart.
You may also like the following Python Matplotlib tutorials:
- Matplotlib default figure size
- Matplotlib savefig blank image
- Matplotlib save as png
- Matplotlib set axis range
- Python plot multiple lines using Matplotlib
- Matplotlib bar chart labels
In this Python tutorial, we have discussed the “Stacked bar chart matplotlib” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.
- Stacked bar chart matplotlib
- Matplotlib how to plot stacked bar chart
- Stacked bar chart matplotlib example
- Stacked bar chart with labels matplotlib
- Stacked bar chart legend matplotlib
- Stacked bar chart matplotlib color
- Stacked bar chart pandas dataframe
- Stacked bar chart using for loop
- Matplotlib stacked bar chart with value
- Matplotlib stacked bar chart with negative value
- Matplotlib stacked bar chart error
- Horizontal stacked bar chart in matplotlib
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.