0
0
Matplotlibdata~30 mins

Bar width and positioning in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Bar width and positioning
📖 Scenario: You are helping a small shop owner visualize the sales of three products over a week. They want to see the sales side by side for easy comparison.
🎯 Goal: Create a bar chart using matplotlib that shows sales of three products with custom bar widths and positions so the bars do not overlap.
📋 What You'll Learn
Create a list called days with the days: 'Mon', 'Tue', 'Wed', 'Thu', 'Fri'
Create three lists called sales_A, sales_B, and sales_C with exact sales numbers
Create a variable called bar_width and set it to 0.2
Use matplotlib.pyplot.bar to plot three sets of bars with correct positions using bar_width
Add a legend with labels 'Product A', 'Product B', and 'Product C'
Print the plot using plt.show()
💡 Why This Matters
🌍 Real World
Bar charts are used in business to compare sales, expenses, or other data across categories or time periods.
💼 Career
Data analysts and scientists often create bar charts to visualize and communicate data insights clearly.
Progress0 / 4 steps
1
Create sales data lists
Create a list called days with these exact values: 'Mon', 'Tue', 'Wed', 'Thu', 'Fri'. Then create three lists called sales_A, sales_B, and sales_C with these exact values respectively: [5, 7, 3, 8, 6], [6, 9, 4, 7, 5], and [4, 6, 5, 6, 7].
Matplotlib
Need a hint?

Use square brackets to create lists. Separate items with commas.

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

Just assign 0.2 to the variable bar_width.

3
Plot the bars with correct positions
Import matplotlib.pyplot as plt. Create a list called positions using range(len(days)). Use plt.bar to plot three sets of bars for sales_A, sales_B, and sales_C. Position the bars so they do not overlap by adding bar_width offsets: positions for sales_A, [p + bar_width for p in positions] for sales_B, and [p + 2 * bar_width for p in positions] for sales_C. Use bar_width as the width for all bars. Add labels 'Product A', 'Product B', and 'Product C' respectively.
Matplotlib
Need a hint?

Use range(len(days)) to get positions. Add bar_width to shift bars right.

4
Add legend, labels, and show the plot
Set the x-axis ticks to the middle of the grouped bars using plt.xticks with positions shifted by bar_width. Use days as labels. Add a legend using plt.legend(). Finally, display the plot using plt.show().
Matplotlib
Need a hint?

Use plt.xticks() to set the ticks in the middle of grouped bars. Use plt.legend() to show labels. Use plt.show() to display the chart.