Pie and Donut Chart

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, we will create a pie and a donut chart using Python's Matplotlib library. We will learn how to label them with a legend as well as with annotations.

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/PlotCustomizationGroup(["`Plot Customization`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/SpecializedPlotsGroup(["`Specialized Plots`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlotCustomizationGroup -.-> matplotlib/line_styles_colors("`Customizing Line Styles and Colors`") matplotlib/PlotCustomizationGroup -.-> matplotlib/legend_config("`Legend Configuration`") matplotlib/PlotCustomizationGroup -.-> matplotlib/text_annotations("`Text Annotations`") matplotlib/SpecializedPlotsGroup -.-> matplotlib/pie_charts("`Pie Charts`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") 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-48866{{"`Pie and Donut Chart`"}} matplotlib/figures_axes -.-> lab-48866{{"`Pie and Donut Chart`"}} matplotlib/line_styles_colors -.-> lab-48866{{"`Pie and Donut Chart`"}} matplotlib/legend_config -.-> lab-48866{{"`Pie and Donut Chart`"}} matplotlib/text_annotations -.-> lab-48866{{"`Pie and Donut Chart`"}} matplotlib/pie_charts -.-> lab-48866{{"`Pie and Donut Chart`"}} python/variables_data_types -.-> lab-48866{{"`Pie and Donut Chart`"}} python/numeric_types -.-> lab-48866{{"`Pie and Donut Chart`"}} python/type_conversion -.-> lab-48866{{"`Pie and Donut Chart`"}} python/for_loops -.-> lab-48866{{"`Pie and Donut Chart`"}} python/list_comprehensions -.-> lab-48866{{"`Pie and Donut Chart`"}} python/lists -.-> lab-48866{{"`Pie and Donut Chart`"}} python/tuples -.-> lab-48866{{"`Pie and Donut Chart`"}} python/dictionaries -.-> lab-48866{{"`Pie and Donut Chart`"}} python/function_definition -.-> lab-48866{{"`Pie and Donut Chart`"}} python/lambda_functions -.-> lab-48866{{"`Pie and Donut Chart`"}} python/importing_modules -.-> lab-48866{{"`Pie and Donut Chart`"}} python/data_collections -.-> lab-48866{{"`Pie and Donut Chart`"}} python/numerical_computing -.-> lab-48866{{"`Pie and Donut Chart`"}} python/data_visualization -.-> lab-48866{{"`Pie and Donut Chart`"}} python/build_in_functions -.-> lab-48866{{"`Pie and Donut Chart`"}} end

Import necessary libraries and create a figure with subplots

We start by importing the necessary libraries and creating a figure with subplots.

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))

Create a Pie Chart

We will now create a pie chart for a recipe that has four ingredients: flour, sugar, butter, and berries.

recipe = ["375 g flour",
          "75 g sugar",
          "250 g butter",
          "300 g berries"]

data = [float(x.split()[0]) for x in recipe]
ingredients = [x.split()[-1] for x in recipe]

def func(pct, allvals):
    absolute = int(np.round(pct/100.*np.sum(allvals)))
    return f"{pct:.1f}%\n({absolute:d} g)"

wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
                                  textprops=dict(color="w"))

ax.legend(wedges, ingredients,
          title="Ingredients",
          loc="center left",
          bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=8, weight="bold")

ax.set_title("Matplotlib bakery: A pie")

plt.show()

Create a Donut Chart

We will now create a donut chart for a recipe that has six ingredients: flour, sugar, egg, butter, milk, and yeast.

recipe = ["225 g flour",
          "90 g sugar",
          "1 egg",
          "60 g butter",
          "100 ml milk",
          "1/2 package of yeast"]

data = [225, 90, 50, 60, 100, 5]

wedges, texts = ax.pie(data, wedgeprops=dict(width=0.5), startangle=-40)

bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(arrowprops=dict(arrowstyle="-"),
          bbox=bbox_props, zorder=0, va="center")

for i, p in enumerate(wedges):
    ang = (p.theta2 - p.theta1)/2. + p.theta1
    y = np.sin(np.deg2rad(ang))
    x = np.cos(np.deg2rad(ang))
    horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
    connectionstyle = f"angle,angleA=0,angleB={ang}"
    kw["arrowprops"].update({"connectionstyle": connectionstyle})
    ax.annotate(recipe[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
                horizontalalignment=horizontalalignment, **kw)

ax.set_title("Matplotlib bakery: A donut")

plt.show()

Conclusion

We have learned how to create a pie and a donut chart using Matplotlib, and how to label them with a legend and annotations.

Summary

In this lab, we learned how to create a pie and a donut chart using Python's Matplotlib library. We also learned how to label them with a legend and annotations.

Other Python Tutorials you may like