0
0
Matplotlibdata~30 mins

Stacked bar charts in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Stacked Bar Charts
📖 Scenario: You work for a small company that sells three types of products: Books, Games, and Electronics. You want to show how many units of each product were sold in the first three months of the year.
🎯 Goal: Create a stacked bar chart using matplotlib to visualize the monthly sales of each product. Each bar will represent a month, and the segments in the bar will show sales of Books, Games, and Electronics stacked on top of each other.
📋 What You'll Learn
Create lists for months and sales of each product
Create a variable for the width of the bars
Use plt.bar to plot stacked bars for Books, Games, and Electronics
Display the final stacked bar chart with labels and legend
💡 Why This Matters
🌍 Real World
Stacked bar charts help businesses compare multiple categories over time or groups, making it easier to see total and individual contributions.
💼 Career
Data analysts and scientists use stacked bar charts to present sales, survey results, or any grouped data clearly to stakeholders.
Progress0 / 4 steps
1
Create sales data lists
Create a list called months with values 'Jan', 'Feb', 'Mar'. Create three lists called books_sales, games_sales, and electronics_sales with the values [120, 150, 170], [80, 90, 100], and [60, 70, 90] respectively.
Matplotlib
Need a hint?

Use square brackets [] to create lists with the exact values given.

2
Set bar width
Create a variable called bar_width and set it to 0.5. This will control the width of each bar in the chart.
Matplotlib
Need a hint?

Use a simple assignment to create bar_width with value 0.5.

3
Plot stacked bars
Import matplotlib.pyplot as plt. Create a list positions with values [0, 1, 2] for the x-axis positions. Use plt.bar to plot the books_sales bars at positions with width bar_width. Then plot games_sales bars stacked on top of books_sales by setting the bottom parameter to books_sales. Finally, plot electronics_sales bars stacked on top of the sum of books_sales and games_sales. Use plt.bar with bottom set to the sum of books_sales and games_sales. Use the variable names exactly as given.
Matplotlib
Need a hint?

Use zip to add books_sales and games_sales element-wise for the bottom parameter of the last bar.

4
Display the stacked bar chart
Add x-axis labels using plt.xticks with positions and months. Add a legend with plt.legend(). Finally, call plt.show() to display the chart.
Matplotlib
Need a hint?

Use plt.xticks(positions, months) to label the x-axis. Use plt.legend() to show the legend. Use plt.show() to display the chart window.