0
0
Matplotlibdata~30 mins

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

Choose your learning style9 modes available
Grouped Bar Charts
📖 Scenario: You work in a small store that sells two types of fruits: apples and oranges. You want to compare the sales of these fruits over three months to see which fruit sold better each month.
🎯 Goal: Create a grouped bar chart to visually compare the monthly sales of apples and oranges side by side.
📋 What You'll Learn
Create a dictionary called sales with keys as months and values as another dictionary with keys 'apples' and 'oranges' and their sales numbers.
Create a list called months containing the months in order.
Create a variable called bar_width to set the width of each bar.
Use matplotlib.pyplot to plot grouped bars for apples and oranges for each month.
Add labels for the x-axis, y-axis, and a title for the chart.
Add a legend to distinguish apples and oranges.
💡 Why This Matters
🌍 Real World
Grouped bar charts help compare multiple categories across different groups, like sales of different products over months.
💼 Career
Data analysts and scientists use grouped bar charts to visualize and communicate comparisons clearly to stakeholders.
Progress0 / 4 steps
1
Create the sales data dictionary
Create a dictionary called sales with these exact entries: 'January': {'apples': 30, 'oranges': 25}, 'February': {'apples': 40, 'oranges': 35}, and 'March': {'apples': 35, 'oranges': 30}.
Matplotlib
Need a hint?

Use a dictionary with months as keys and another dictionary for fruit sales as values.

2
Set up months list and bar width
Create a list called months with the values 'January', 'February', and 'March'. Then create a variable called bar_width and set it to 0.35.
Matplotlib
Need a hint?

Use a list for months and a float for bar_width.

3
Plot the grouped bar chart
Import matplotlib.pyplot as plt. Create two lists called apples_sales and oranges_sales that contain the sales numbers for apples and oranges for each month in order. Create a list called positions using range(len(months)). Plot grouped bars for apples and oranges using plt.bar with positions and positions + bar_width for x positions. Add x-axis labels using plt.xticks at the middle of the grouped bars with the month names. Add labels for x-axis as 'Months', y-axis as 'Sales', and a title 'Monthly Fruit Sales'. Add a legend for apples and oranges.
Matplotlib
Need a hint?

Use list comprehensions to get sales lists. Use plt.bar twice with shifted positions for grouped bars.

4
Display the grouped bar chart
Add a line to display the plot using plt.show().
Matplotlib
Need a hint?

Use plt.show() to display the chart.