Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Creating and Customizing Pie Charts with Matplotlib

Notes May 13 2

Basic Pie Chart Construction

Pie charts provide an intuitive way to visualize proportional data. The pie() function in Matplotlib simplifies this process.

import matplotlib.pyplot as plt

plt.figure(figsize=(16, 9))

regions = ['China', 'Japan', 'Korea', 'USA', 'Russia']
tax_revenue = [60, 10, 20, 70, 50]
color_palette = ['red', '#FEDD62', 'blue', 'gray', 'green']
offsets = [0.1, 0, 0, 0, 0]  # Emphasize China's segment

plt.pie(tax_revenue,
        labels=regions,
        colors=color_palette,
        explode=offsets,
        startangle=90,
        shadow=True,
        autopct='%1.1f%%')

plt.legend(loc=2)
plt.show()

Real-World Tax Data Visualization

Using national tax data from 2006–2015 (source: National Bureau of Statistics of China), we compute and display the proporsion of each tax category for 2015.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

font_style = FontProperties(fname='/Library/Fonts/Songti.ttc', size=18)
year_col = '2015年'

tax_df = pd.read_csv('国家各项税收.csv',
                     index_col=0,
                     skiprows=2,
                     skipfooter=1,
                     engine='python')

# Derive 'Other Taxes' as residual
main_total = tax_df[year_col].iloc[0]
sum_of_categories = tax_df[year_col].iloc[1:].sum()
other_taxes = main_total - sum_of_categories

tax_series = tax_df[year_col].copy()
tax_series['其他税收'] = other_taxes

plt.figure(figsize=(16, 9))

# Highlight personal income tax
highlight = [0.2 if label == '个人所得税(亿元)' else 0 for label in tax_series.index]

pie_artists = plt.pie(tax_series.values,
                      labels=tax_series.index,
                      shadow=True,
                      autopct='%1.1f%%',
                      explode=highlight,
                      startangle=30)

# Apply Chinese font to labels
for label_text in pie_artists[1]:
    label_text.set_fontproperties(font_style)
    label_text.set_fontsize(14)

plt.show()

Multi-Plot Layouts with Subplots

A Figure can contain multiple Axes objects, arranged using subplot().

import matplotlib.pyplot as plt

plt.figure(figsize=(15, 9))

x_vals = [0, 1, 2, 5, 4, 5]
y_vals = [0, 2, 3, 4, 5, 6]

for i in range(1, 7):
    plt.subplot(2, 3, i)
    if i == 1:
        plt.plot(x_vals, y_vals, 'ro')
        plt.legend(['First plot'])
        plt.grid(True)
    else:
        plt.plot(x_vals, y_vals)
    plt.title(f'this is my picture{i}')

plt.show()

Customized Cooridnate System for Line Plots

Axes spines can be repositioned or hidden to create centered coordinate systems.

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-8, 8, 2)
y = np.random.randint(-4, 4, size=len(x))

plt.plot(x, y)
plt.axis([-10, 10, -10, 10])

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))

plt.show()

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.