0
0
Matplotlibdata~30 mins

Horizontal grouped bars in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Horizontal grouped bars
📖 Scenario: You are working for a small company that wants to compare sales of two products across three regions. They want a clear visual to see which product sells better in each region.
🎯 Goal: Create a horizontal grouped bar chart using matplotlib to compare sales of two products across three regions.
📋 What You'll Learn
Create a list called regions with the values 'North', 'South', and 'East'.
Create two lists called sales_product_a and sales_product_b with sales numbers for each region.
Create a variable called bar_width and set it to 0.4.
Use matplotlib.pyplot to create horizontal grouped bars for both products side by side for each region.
Add labels for the y-axis with region names and a legend for the products.
Display the plot.
💡 Why This Matters
🌍 Real World
Horizontal grouped bar charts are useful to compare multiple categories side by side across different groups, such as sales of different products in various regions.
💼 Career
Data analysts and scientists often create grouped bar charts to visualize and communicate comparisons clearly to stakeholders.
Progress0 / 4 steps
1
Create the sales data lists
Create a list called regions with the values 'North', 'South', and 'East'. Then create two lists called sales_product_a with values 120, 150, 100 and sales_product_b with values 90, 130, 110.
Matplotlib
Need a hint?

Use square brackets to create lists. Put the region names as strings in regions. Put the sales numbers as integers in sales_product_a and sales_product_b.

2
Set the bar width
Create a variable called bar_width and set it to 0.4.
Matplotlib
Need a hint?

Just assign the number 0.4 to the variable bar_width.

3
Create the horizontal grouped bars
Import matplotlib.pyplot as plt. Create a list called y_positions using range(len(regions)). Use plt.barh() to plot sales_product_a at y_positions with height bar_width. Then plot sales_product_b at [y + bar_width for y in y_positions] with height bar_width. Add y-axis ticks at the middle of the grouped bars with region names using plt.yticks(). Add a legend with labels 'Product A' and 'Product B'.
Matplotlib
Need a hint?

Use plt.barh() twice with adjusted y positions to create grouped bars. Use plt.yticks() to label the regions in the middle of the groups.

4
Display the plot
Use plt.show() to display the horizontal grouped bar chart.
Matplotlib
Need a hint?

Call plt.show() to display the chart window.