How to draw and nest doughnut charts with Python Visualization

파이썬 시각화 중첩 도넛 차트

Python Visualizations allow you to present complex data in beautiful, easy-to-understand charts. In particular, donut charts are a great tool for visualizing ratios. But don't settle for just representing ratios! Nested doughnut charts allow you to create trendy and in-depth visualizations.

In this article, we'll use the The Python visualization library matplotlibHow to draw a doughnut chart step by step usingin this tutorial. We'll cover everything from basic donut charts to more advanced techniques for drawing nested donut charts, so follow along!

What is a donut chart?

A doughnut chart is a A variation of the pie chart with a hollow centerThis empty space adds to the cleanliness of the chart and is a great place to include additional information.

Key Features

  • Data ratein an intuitive way.
  • Overlaying multiple pieces of data enables multidimensional visualizations.
  • The clean, modern design is perfect for trendy data visualizations.

Drawing basic charts with Python visualizations

파이썬 시각화 도넛 차트

First, let's take a look at how to draw a basic chart like the one above, where we'll use the matplotlibto utilize the

Python Code Example - Basic Donut Chart

Importing the # library
import matplotlib.pyplot as plt

Set up the # data
labels = ['Country A', 'Country B', 'Country C', 'Country D']
sizes = [30, 20, 35, 15]
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']

Create a # donut chart
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, colors=colors, wedgeprops=dict(width=0.3), autopct='%1.1f%%')

Add a # center circle (make it donut-shaped)
centre_circle = plt.Circle((0, 0), 0.70, fc='white')
fig.gca().add_artist(centre_circle)

Set the # chart title
plt.title('Basic Donut Chart')
plt.show()

Drawing a nested chart

A nested chart shows the Two tierssimultaneously, with each layer providing a richer view of the data.

Python code example - Nested doughnut chart

import matplotlib.pyplot as plt

Set up the # outer donut data
outer_labels = ['Germany', 'France', 'China', 'UK', 'Italy']
outer_sizes = [30, 23, 16, 18, 13]

# inner donut data settings
inner_labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
inner_sizes = [15, 15, 12, 11, 8, 8, 8, 9, 9, 9, 7, 6]

# color settings
outer_colors = plt.cm.Blues([0.6, 0.7, 0.8, 0.9, 1.0])
inner_colors = plt.cm.RdYlBu_r([0.6, 0.6, 0.7, 0.7, 0.8, 0.8, 0.8, 0.9, 0.9, 1.0, 1.0])

Create a # nested doughnut chart
fig, ax = plt.subplots()

# outer donut layer
ax.pie(outer_sizes, labels=outer_labels, radius=1.3, colors=outer_colors,
       wedgeprops=dict(width=0.3), labeldistance=1.1, autopct='%1.1f%%', pctdistance=0.85)

# inner donut layer
ax.pie(inner_sizes, labels=inner_labels, radius=1.0, colors=inner_colors,
       wedgeprops=dict(width=0.3), labeldistance=0.7, autopct='%1.1f%%', pctdistance=0.6)

Hollow out the center of # (completing the donut shape)
centre_circle = plt.Circle((0, 0), 0.6, fc='white')
fig.gca().add_artist(centre_circle)

Set up the # title (adjust spacing with the pad option)
plt.title('Improved Nested Donut Chart with Adjusted Labels', pad=30)

Set the # layout
plt.tight_layout()
plt.show()

Common mistakes

  • When you have too much data: Too many items clutter the chart. Include only key data.
  • Color confusion: Using similar colors can make it difficult to distinguish between items. Use a color palette.
  • Ratio and label mismatches: autopctto ensure that the correct percentage is displayed.

Frequently asked questions (FAQ)

Q1. When should I use this chart?
This chart shows the ratio
Great for situations where you need comparisons but want a clean, modern design.

Q2. What is the purpose of a nested doughnut chart?
It is effective when comparing and analyzing two layers of data simultaneously.

Q3. How is it different from a pie chart?
Donut charts are hollow in the center to display additional information or are more aesthetically pleasing.

Finalize

Donut charts are a popular technique in Python visualization that breaks up the monotony of pie charts. Once you've followed along from basic charts to nested charts, it's time to try your hand at creating some cool doughnut charts with real data! You'll be one step closer to falling in love with data visualization.

As a side note, there are a lot of people in Python visualization who do time series analysis. Python Data Analysis Example: Analyze S&P 500 Stock Data Time Series and Predict Future Prices Check out this post to learn how!

# Explanation of the code

Draw a basic chart

Importing the # library
import matplotlib.pyplot as plt  
  1. Importing libraries
  • matplotlib.pyplot: The matplotlibwhich is a submodule of
  • This module uses the Graphs, charts and more.
Set up # data
labels = ['Country A', 'Country B', 'Country C', 'Country D']
sizes = [30, 20, 35, 15]
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']  
  1. Data settings
  • labels: The name of each fragment (section). For example: 'Country A', 'Country B', etc.
  • sizes: Sets the proportion of each piece. Examples: 30%, 20%, 35%, 15%.
  • colors: The color code to use for each section.
    • '#ff9999': light pink
    • '#66b3ff': light blue
    • '#99ff99': light green
    • '#ffcc99': orange color
Create a # Donut Chart
fig, ax = plt.subplots()  
  1. Create a chart
  • fig, ax: figure(canvas) and axes(the area where the graph will be plotted).
  • plt.subplots(): Prepare the space for drawing a new chart.
ax.pie(sizes, labels=labels, colors=colors, wedgeprops=dict(width=0.3), autopct='%1.1f%%')  
  1. Create a doughnut chart
  • sizes: Indicates the percentage of each section (piece).
  • labels=labelsSets the label (name) that will appear in the : section.
  • colors=colorsSets the color of the : section.
  • wedgeprops=dict(width=0.3): Donut shapeto adjust the width of the fragment.
    • width=0.3is a setting that empties the inner 70% of the full width of the circle.
  • autopct='%1.1f%%': Displays the ratio (%) for each piece.
    • %1.1f: Set to show up to the first decimal place.
Add a # center circle (make it donut-shaped)
centre_circle = plt.Circle((0, 0), 0.70, fc='white')
fig.gca().add_artist(centre_circle)  
  1. Add a center circle (to make it donut-shaped)
  • plt.Circle((0, 0), 0.70, fc='white'):
    • (0, 0): The coordinates of the center of the circle.
    • 0.70Sets the radius of the circle.
    • fc='white': Sets the color of the circle to white.
  • fig.gca().add_artist(centre_circle):
    • Add the white circle created above to the current axes (graph area).
  • This code allows us to create a centered empty Donut shapeis complete.
Setting the # chart title
plt.title('Basic Donut Chart')  
  1. Setting the chart title
  • plt.title(): Add a title to the top of the chart.
  • 'Basic Donut Chart': The title string for the chart.
plt.show()  
  1. Output the results
  • plt.show(): Displays the chart on the screen.
  • This command must be run before the chart is finally output.

Drawing a nested chart

import matplotlib.pyplot as plt  
  1. Importing libraries
  • Data Visualization matplotlibThe pyplot Import the module.
# outer donut data settings
outer_labels = ['Germany', 'France', 'China', 'UK', 'Italy']
outer_sizes = [30, 23, 16, 18, 13]  
  1. Setting up external donut data
  • outer_labels: The name of each piece that will appear on the outer donut.
  • outer_sizes: Represents the proportion of each piece of the outer donut (%).
Set up # inner donut data
inner_labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
inner_sizes = [15, 15, 12, 11, 8, 8, 8, 9, 9, 9, 7, 6]  
  1. Setting up internal donut data
  • inner_labels: The name of each piece that will appear in the inner donut.
  • inner_sizes: The proportion of each piece of the inner donut, divided by the proportion of the outer piece.
# color settings
outer_colors = plt.cm.Blues([0.6, 0.7, 0.8, 0.9, 1.0])
inner_colors = plt.cm.RdYlBu_r([0.6, 0.6, 0.7, 0.7, 0.8, 0.8, 0.8, 0.9, 0.9, 1.0, 1.0])  
  1. Color settings
  • plt.cm.Blues: Create a shade of blue as the color palette for the outer donut.
  • plt.cm.RdYlBu_r: Apply a red-yellow-blue combination as the color palette to use for the inner donut.
  • [] The number inside sets the darkness of the color (0 to 1).
Create a # Nested Donut Chart
fig, ax = plt.subplots()  
  1. Create a chart
  • fig, ax: Create new figure and axes objects.
  • plt.subplots(): Prepare a canvas to draw the chart on.
# Outer Donut Layer
ax.pie(outer_sizes, labels=outer_labels, radius=1.3, colors=outer_colors,
       wedgeprops=dict(width=0.3), labeldistance=1.1, autopct='%1.1f%%', pctdistance=0.85)  
  1. Create an outer donut
  • outer_sizes: Enter the percentage of the outer donut.
  • labels=outer_labels: Set the label (country name) that will be displayed on each fragment.
  • radius=1.3Sets the radius of the outer donut.
  • colors=outer_colorsSets the color of the outer donut.
  • wedgeprops=dict(width=0.3): Sets the width of each piece to create a donut shape.
  • labeldistance=1.1: Move the label (country name) a little further to the outside of the donut.
  • autopct='%1.1f%%': Displays the percentage of each piece to one decimal place.
  • pctdistance=0.85Position the : ratio text closer to the inside of the donut piece.
# Inner Donut Layer
ax.pie(inner_sizes, labels=inner_labels, radius=1.0, colors=inner_colors,
       wedgeprops=dict(width=0.3), labeldistance=0.7, autopct='%1.1f%%', pctdistance=0.6)  
  1. Create an inner donut
  • inner_sizes: Enter the percentage of the donut inside.
  • labels=inner_labelsSets the label that will be displayed on each fragment.
  • radius=1.0: Sets the radius of the inner donut.
  • colors=inner_colorsSets the color of the inner donut.
  • wedgeprops=dict(width=0.3): Create a donut shape.
  • labeldistance=0.7: Place the label (string) close to the inside of the fragment.
  • autopct='%1.1f%%': Displays the ratio to one decimal place.
  • pctdistance=0.6Moves the : ratio text further inward.
Hollow out the center of # (completing the donut shape)
centre_circle = plt.Circle((0, 0), 0.6, fc='white')
fig.gca().add_artist(centre_circle)  
  1. Center Hollow
  • plt.Circle((0, 0), 0.6, fc='white'): Add a white circle in the center to complete the donut shape.
  • add_artist(centre_circle): Adds a white circle to the chart.
  • (0, 0): The center coordinates.
  • 0.6: The radius of the white circle.
Setting up a # title (adjust spacing with the pad option)
plt.title('Improved Nested Donut Chart with Adjusted Labels', pad=30)  
  1. Setting titles and adjusting spacing
  • plt.title(): Add a title to the top of the chart.
  • pad=30: Adjust the spacing between the title and the chart to 30 pixels.
  • "Improved Nested Donut Chart with Adjusted Labels": The chart title.
# Layout Setup
plt.tight_layout()  
  1. Optimize layout
    • plt.tight_layout()Automatically adjust margins so that chart elements don't overlap each other.
plt.show()
  1. Output the results
    • Display the chart on the screen.

Similar Posts