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, data[0], label='Group 1'), data[1], bottom=data[0], label='Group 2'), data[2], bottom=[i+j for i,j in zip(data[0],data[1])], label='Group 3')

// Add labels to the chart
ax.set_xticklabels(['A', 'B', 'C'])

// Add legend

// Show the chart

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