Create a stacked bar plot in Matplotlib
×


Create a stacked bar plot in Matplotlib

2143

Creating Stacked Bar Plots with Matplotlib

Matplotlib is a versatile Python library for generating a wide range of static, animated, and interactive plots. One of its powerful features is the ability to create stacked bar plots, which are particularly useful for visualizing the composition of different groups across categories. In this guide, we'll explore how to create stacked bar plots using Matplotlib, including examples with multiple datasets and customization options.

Understanding Stacked Bar Plots

A stacked bar plot displays multiple datasets stacked on top of each other, allowing you to compare the total size and the individual components across different categories. This type of plot is ideal for showing how parts contribute to a whole over time or across different categories.

Creating a Basic Stacked Bar Plot

To create a basic stacked bar plot, we can use Matplotlib's bar() function with the bottom parameter to stack the bars. Here's an example:

import matplotlib.pyplot as plt
import numpy as np

# Data
categories = ['A', 'B', 'C', 'D']
y1 = np.array([10, 20, 10, 30])
y2 = np.array([20, 25, 15, 25])

# Create stacked bar plot
plt.bar(categories, y1, color='r')
plt.bar(categories, y2, bottom=y1, color='b')

# Add labels and title
plt.xlabel('Category')
plt.ylabel('Value')
plt.title('Stacked Bar Plot Example')

# Show plot
plt.show()

In this example, y1 and y2 represent two datasets that are stacked on top of each other for each category. The bottom parameter in the second bar() call ensures that y2 is stacked on top of y1.

Stacking Multiple Datasets

When dealing with more than two datasets, you can continue stacking by adding the previous datasets together using the bottom parameter. Here's how you can stack four datasets:

# Additional data
y3 = np.array([12, 15, 19, 6])
y4 = np.array([10, 29, 13, 19])

# Create stacked bar plot
plt.bar(categories, y1, color='r')
plt.bar(categories, y2, bottom=y1, color='b')
plt.bar(categories, y3, bottom=y1+y2, color='y')
plt.bar(categories, y4, bottom=y1+y2+y3, color='g')

# Add labels and title
plt.xlabel('Category')
plt.ylabel('Value')
plt.title('Stacked Bar Plot with Multiple Datasets')

# Show plot
plt.show()

By adding the previous datasets together for each category, we can stack multiple datasets to visualize their cumulative effect.

Using Pandas DataFrames for Stacked Bar Plots

Matplotlib integrates seamlessly with Pandas, allowing you to create stacked bar plots directly from DataFrames. Here's an example using a DataFrame:

import pandas as pd

# Create DataFrame
data = {'Category': ['A', 'B', 'C', 'D'],
        'Dataset 1': [10, 20, 10, 30],
        'Dataset 2': [20, 25, 15, 25],
        'Dataset 3': [12, 15, 19, 6],
        'Dataset 4': [10, 29, 13, 19]}

df = pd.DataFrame(data)

# Set category as index
df.set_index('Category', inplace=True)

# Create stacked bar plot
df.plot(kind='bar', stacked=True, color=['r', 'b', 'y', 'g'])

# Add labels and title
plt.xlabel('Category')
plt.ylabel('Value')
plt.title('Stacked Bar Plot from DataFrame')

# Show plot
plt.show()

Using Pandas' plot() function with kind='bar' and stacked=True creates a stacked bar plot directly from the DataFrame.

Customizing the Stacked Bar Plot

Matplotlib offers various customization options to enhance the appearance of your stacked bar plots:

  • Colors: Specify colors for each dataset using the color parameter in the bar() or plot() function.
  • Legends: Add legends to differentiate between datasets using the legend() function.
  • Gridlines: Enable gridlines for better readability using the grid() function.
  • Annotations: Annotate bars with values using the text() function to display exact values on the plot.

Here's an example with some customizations:

# Create stacked bar plot with customizations
ax = df.plot(kind='bar', stacked=True, color=['r', 'b', 'y', 'g'])

# Add labels and title
ax.set_xlabel('Category')
ax.set_ylabel('Value')
ax.set_title('Customized Stacked Bar Plot')

# Add gridlines
ax.grid(True, axis='y', linestyle='--', alpha=0.7)

# Add legend
ax.legend(title='Datasets')

# Show plot
plt.show()

These customizations improve the readability and presentation of your stacked bar plots.

Conclusion

Stacked bar plots are an effective way to visualize the composition of different groups across categories. Matplotlib provides powerful tools to create and customize these plots, allowing you to present your data in a clear and informative manner. By leveraging the examples and techniques discussed in this guide, you can create compelling visualizations that enhance your data analysis and storytelling.


If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat