Awesome!
Completion rate improved to 3.85SectionΒ 2. ChapterΒ 6
single
Grouped Bar Charts
Swipe to show menu
Another common option is a grouped bar chart, where bars for each category are placed side by side instead of stacking them.
This is useful when you want to compare categories across groups (like economic sectors in different countries), rather than within one total.
Steps to Create a Grouped Bar Chart
- Set a bar width and create an array for x-axis positions using
np.arange(); - Combine your category data into a 2D array;
- Use a
forloop to draw each group of bars with thebar()function, shifting their positions horizontally; - Customize the x-axis tick positions and labels using
plt.xticks().
12345678910111213141516171819202122232425import matplotlib.pyplot as plt import numpy as np # Labels and data countries = ['USA', 'China', 'Japan'] positions = np.arange(len(countries)) primary = np.array([1.4, 4.8, 0.4]) secondary = np.array([11.3, 6.2, 0.8]) tertiary = np.array([14.2, 8.4, 3.2]) # Group the data sectors = np.array([primary, secondary, tertiary]) # Width of each bar width = 0.25 # Plot each group of bars for i in range(len(sectors)): plt.bar(positions + width * i, sectors[i], width) # Center the group of bars and label the ticks plt.xticks(positions + width, countries) plt.show()
How xticks() Works
- The first argument shifts the tick marks to the center of each group of bars;
- The second argument sets the labels using the
countrieslist.
Note
This approach works for any number of categories β just adjust the width to make sure the bars don't overlap.
Task
Swipe to start coding
- Pass the array of all answer groups to the
len()function. - Call the function to create a bar chart.
- Calculate the x-position offset based on the current loop iteration.
- Select the specific dataset from
answersfor the current step. - Pass the variable that defines the bar width.
Solution
Everything was clear?
Thanks for your feedback!
SectionΒ 2. ChapterΒ 6
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat