How to generate stacked BAR using Python

How to generate stacked BAR using Python

Creating a stacked bar chart in Python is a great way to display the distribution of different categories of data.

Here is an example of how you can create a stacked bar chart in Python using the popular library matplotlib:

import matplotlib.pyplot as plt
import numpy as np


// Create some data
data = [[20, 30, 50], [40, 10, 50], [35, 45, 20]]


// Create the chart
fig, ax = plt.subplots()


// Create the stacked bar chart
ax.bar(np.arange(3), data[0], label='Group 1')
ax.bar(np.arange(3), data[1], bottom=data[0], label='Group 2')
ax.bar(np.arange(3), data[2], bottom=[i+j for i,j in zip(data[0],data[1])], label='Group 3')


// Add labels to the chart
x.set_xticks(np.arange(3))
ax.set_xticklabels(['A', 'B', 'C'])
ax.set_ylabel('Values')


// Add legend
ax.legend()


// Show the chart
plt.show()

In this example, we first create some sample data. Then, we use the “bar” function of the matplotlib library to create the stacked bar chart. This function takes in three parameters: the x-coordinates of the bars, the heights of the bars, and the bottom positions of the bars. Here, we use the np.arange() function to create the x-coordinates of the bars, and for the heights we take data of each group one by one and for bottom positions, we take sum of previous group’s data. We can add labels to the chart using the set_xticks() and set_xticklabels() functions, and add a legend using the legend() function. Finally, we use the show() function to display the chart.

You can also use seaborn library in a similar way as matplotlib with more simplified functionalities and aesthetics.

In simple words, stacked bar chart is a chart in which multiple bars are stacked on top of each other, representing different categories of data. Python’s matplotlib library allows us to create stacked bar charts easily, by passing in the data and customizing the appearance of the chart as per our requirement.

In this Learn through Codes example, you will learn: How to generate stacked BAR using Python.



Essential Gigs