Grouped Bar Charts
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
for
loop to draw each group of bars with thebar()
function, shifting their positions horizontally;Customize the x-axis tick positions and labels using
plt.xticks()
.
import 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
countries
list.
This approach works for any number of categories β just adjust the width
to make sure the bars don't overlap.
Swipe to start coding
- Pass the correct array to the
len()
function. - Use the correct function to plot bars.
- Use the correct variable which should be multiplied by
i
. - Use the correct variable as an index for
answers
array. - Pass the correct variable as the rightmost arguments of the plotting function.
Solution
Thanks for your feedback!