Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Grouped Bar Charts | Creating Commonly Used Plots
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Ultimate Visualization with Python
close
SectionΒ 2. ChapterΒ 6
single

single

bookGrouped 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

  1. Set a bar width and create an array for x-axis positions using np.arange();
  2. Combine your category data into a 2D array;
  3. Use a for loop to draw each group of bars with the bar() function, shifting their positions horizontally;
  4. Customize the x-axis tick positions and labels using plt.xticks().
12345678910111213141516171819202122232425
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()
copy

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.
Note
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

  1. Pass the array of all answer groups to the len() function.
  2. Call the function to create a bar chart.
  3. Calculate the x-position offset based on the current loop iteration.
  4. Select the specific dataset from answers for the current step.
  5. Pass the variable that defines the bar width.

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 6
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt