Grouped Bar Chart Withels Using Matplotlib

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to create a grouped bar chart and how to annotate bars with labels using Python Matplotlib. We will use data from the Palmer Penguins dataset to create a chart that displays penguin attributes by species.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/bar_charts("`Bar Charts`") matplotlib/PlotCustomizationGroup -.-> matplotlib/legend_config("`Legend Configuration`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48579{{"`Grouped Bar Chart Withels Using Matplotlib`"}} matplotlib/figures_axes -.-> lab-48579{{"`Grouped Bar Chart Withels Using Matplotlib`"}} matplotlib/bar_charts -.-> lab-48579{{"`Grouped Bar Chart Withels Using Matplotlib`"}} matplotlib/legend_config -.-> lab-48579{{"`Grouped Bar Chart Withels Using Matplotlib`"}} python/for_loops -.-> lab-48579{{"`Grouped Bar Chart Withels Using Matplotlib`"}} python/tuples -.-> lab-48579{{"`Grouped Bar Chart Withels Using Matplotlib`"}} python/dictionaries -.-> lab-48579{{"`Grouped Bar Chart Withels Using Matplotlib`"}} python/importing_modules -.-> lab-48579{{"`Grouped Bar Chart Withels Using Matplotlib`"}} python/numerical_computing -.-> lab-48579{{"`Grouped Bar Chart Withels Using Matplotlib`"}} python/data_visualization -.-> lab-48579{{"`Grouped Bar Chart Withels Using Matplotlib`"}} python/build_in_functions -.-> lab-48579{{"`Grouped Bar Chart Withels Using Matplotlib`"}} end

Import Required Libraries

We will begin by importing the necessary libraries to work with our data and create the chart.

import matplotlib.pyplot as plt
import numpy as np

Prepare Data

Next, we will prepare the data for our chart. We have three species of penguins and three attributes, so we will create a dictionary with the means for each attribute by species.

species = ("Adelie", "Chinstrap", "Gentoo")
penguin_means = {
    'Bill Depth': (18.35, 18.43, 14.98),
    'Bill Length': (38.79, 48.83, 47.50),
    'Flipper Length': (189.95, 195.82, 217.19),
}

Create a Grouped Bar Chart

Now, we can create our chart using the bar function from Matplotlib. We will create a loop that iterates through our attributes and creates a set of bars for each one. We will also adjust the width of the bars and the position of each set of bars.

x = np.arange(len(species))
width = 0.25
multiplier = 0

fig, ax = plt.subplots()

for attribute, measurement in penguin_means.items():
    offset = width * multiplier
    rects = ax.bar(x + offset, measurement, width, label=attribute)
    multiplier += 1

Add Labels to the Bars

We can add labels to the bars using the bar_label function from Matplotlib. This will add the value of each bar above it.

ax.bar_label(rects, padding=3)

Customize the Chart

We can customize the chart by adding labels, a title, and adjusting the x-axis tick labels and legend. We will also set the y-axis limit to ensure that all of our data is visible.

ax.set_ylabel('Length (mm)')
ax.set_title('Penguin attributes by species')
ax.set_xticks(x + width, species)
ax.legend(loc='upper left', ncols=3)
ax.set_ylim(0, 250)

Show the Chart

Finally, we can show the chart using the show function from Matplotlib.

plt.show()

Summary

In this lab, we learned how to create a grouped bar chart and how to annotate bars with labels using Python Matplotlib. We used data from the Palmer Penguins dataset to create a chart that displays penguin attributes by species. We also learned how to customize the chart by adding labels, a title, and adjusting the x-axis tick labels and legend.

Other Python Tutorials you may like