Creating a Bar of Pie Chart

PythonPythonBeginner
Practice Now

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

Introduction

In this tutorial, you will learn how to create a "Bar of Pie" chart using Python's Matplotlib library. A Bar of Pie chart is a combination of a Pie chart and a stacked bar chart, where the first slice of the pie is exploded into a bar chart with a further breakdown of its characteristics. This chart is useful when you want to show the distribution of a whole data set, while also highlighting specific categories.

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 python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/SpecializedPlotsGroup(["`Specialized Plots`"]) 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`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/bar_charts("`Bar Charts`") matplotlib/SpecializedPlotsGroup -.-> matplotlib/pie_charts("`Pie Charts`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") 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 python/comments -.-> lab-48574{{"`Creating a Bar of Pie Chart`"}} matplotlib/importing_matplotlib -.-> lab-48574{{"`Creating a Bar of Pie Chart`"}} matplotlib/figures_axes -.-> lab-48574{{"`Creating a Bar of Pie Chart`"}} matplotlib/bar_charts -.-> lab-48574{{"`Creating a Bar of Pie Chart`"}} matplotlib/pie_charts -.-> lab-48574{{"`Creating a Bar of Pie Chart`"}} python/for_loops -.-> lab-48574{{"`Creating a Bar of Pie Chart`"}} python/lists -.-> lab-48574{{"`Creating a Bar of Pie Chart`"}} python/tuples -.-> lab-48574{{"`Creating a Bar of Pie Chart`"}} python/dictionaries -.-> lab-48574{{"`Creating a Bar of Pie Chart`"}} python/importing_modules -.-> lab-48574{{"`Creating a Bar of Pie Chart`"}} python/numerical_computing -.-> lab-48574{{"`Creating a Bar of Pie Chart`"}} python/data_visualization -.-> lab-48574{{"`Creating a Bar of Pie Chart`"}} python/build_in_functions -.-> lab-48574{{"`Creating a Bar of Pie Chart`"}} end

Import necessary libraries

Before we start creating the chart, we need to import the necessary libraries. In this case, we will be using matplotlib.pyplot and numpy.

import matplotlib.pyplot as plt
import numpy as np

Define the data for the chart

Next, we need to define the data that we will be using to create the chart. In this case, we will be using the following data:

## pie chart parameters
overall_ratios = [.27, .56, .17]
labels = ['Approve', 'Disapprove', 'Undecided']
explode = [0.1, 0, 0]

## bar chart parameters
age_ratios = [.33, .54, .07, .06]
age_labels = ['Under 35', '35-49', '50-65', 'Over 65']

Create the pie chart

Now we can create the pie chart. We start by defining the figure and axis objects:

## make figure and assign axis objects
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 5))
fig.subplots_adjust(wspace=0)

Then we set the parameters for the pie chart and plot it:

## rotate so that first wedge is split by the x-axis
angle = -180 * overall_ratios[0]
wedges, *_ = ax1.pie(overall_ratios, autopct='%1.1f%%', startangle=angle,
                     labels=labels, explode=explode)

Create the bar chart

Next, we create the stacked bar chart. We start by defining the parameters for the chart:

## bar chart parameters
bottom = 1
width = .2

## Adding from the top matches the legend.
for j, (height, label) in enumerate(reversed([*zip(age_ratios, age_labels)])):
    bottom -= height
    bc = ax2.bar(0, height, width, bottom=bottom, color='C0', label=label,
                 alpha=0.1 + 0.25 * j)
    ax2.bar_label(bc, labels=[f"{height:.0%}"], label_type='center')

Connect the pie chart and bar chart

Finally, we connect the pie chart and bar chart using ConnectionPatch:

## use ConnectionPatch to draw lines between the two plots
theta1, theta2 = wedges[0].theta1, wedges[0].theta2
center, r = wedges[0].center, wedges[0].r
bar_height = sum(age_ratios)

## draw top connecting line
x = r * np.cos(np.pi / 180 * theta2) + center[0]
y = r * np.sin(np.pi / 180 * theta2) + center[1]
con = ConnectionPatch(xyA=(-width / 2, bar_height), coordsA=ax2.transData,
                      xyB=(x, y), coordsB=ax1.transData)
con.set_color([0, 0, 0])
con.set_linewidth(4)
ax2.add_artist(con)

## draw bottom connecting line
x = r * np.cos(np.pi / 180 * theta1) + center[0]
y = r * np.sin(np.pi / 180 * theta1) + center[1]
con = ConnectionPatch(xyA=(-width / 2, 0), coordsA=ax2.transData,
                      xyB=(x, y), coordsB=ax1.transData)
con.set_color([0, 0, 0])
ax2.add_artist(con)
con.set_linewidth(4)

Display the chart

Finally, we display the chart:

plt.show()

Summary

In this tutorial, you learned how to create a "Bar of Pie" chart using Python's Matplotlib library. A Bar of Pie chart is useful when you want to show the distribution of a whole data set, while also highlighting specific categories. You also learned how to use ConnectionPatch to connect the pie chart and bar chart.

Other Python Tutorials you may like