ZetCode

Matplotlib 饼图

最后修改于 2025 年 2 月 25 日

Matplotlib 是一个强大的 Python 库,用于创建静态、动画和交互式可视化。饼图用于可视化数据集中类别的比例。本教程介绍了如何使用 Matplotlib 创建各种类型的饼图。

饼图非常适合显示类别的大小相对于整体的比例。 Matplotlib 提供了一个灵活且易于使用的界面,用于创建具有自定义设置的饼图。

基本饼图

此示例演示如何创建基本饼图。

basic_pie_chart.py
import matplotlib.pyplot as plt

# Data
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]

# Create a pie chart
plt.pie(sizes, labels=labels)

# Add a title
plt.title("Basic Pie Chart")

# Display the chart
plt.show()

plt.pie() 函数用于创建饼图。 labels 参数为每个切片分配标签。

自定义饼图

此示例演示如何使用颜色、突出显示和阴影效果自定义饼图。

custom_pie_chart.py
import matplotlib.pyplot as plt

# Data
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
colors = ['gold', 'lightcoral', 'lightskyblue', 'lightgreen']
explode = (0.1, 0, 0, 0)  # "Explode" the first slice

# Create a pie chart with custom styles
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        shadow=True, startangle=90)

# Add a title
plt.title("Custom Pie Chart")

# Display the chart
plt.show()

explodecolorsshadowstartangle 参数用于自定义饼图的外观。

带有百分比的饼图

此示例演示如何在饼图的每个切片上显示百分比。

pie_chart_with_percentages.py
import matplotlib.pyplot as plt

# Data
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]

# Create a pie chart with percentages
plt.pie(sizes, labels=labels, autopct='%1.1f%%')

# Add a title
plt.title("Pie Chart with Percentages")

# Display the chart
plt.show()

autopct 参数用于在每个切片上显示百分比。

甜甜圈图

此示例演示如何创建甜甜圈图。

donut_chart.py
import matplotlib.pyplot as plt

# Data
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]

# Create a pie chart
plt.pie(sizes, labels=labels, startangle=90)

# Draw a circle at the center to create a donut chart
centre_circle = plt.Circle((0, 0), 0.7, color='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)

# Add a title
plt.title("Donut Chart")

# Display the chart
plt.show()

plt.Circle() 函数用于在饼图的中心绘制一个白色圆圈,从而创建一个甜甜圈图。

嵌套饼图

此示例演示如何创建嵌套饼图。

nested_pie_chart.py
import matplotlib.pyplot as plt

# Data for the outer pie
outer_labels = ['A', 'B', 'C', 'D']
outer_sizes = [15, 30, 45, 10]

# Data for the inner pie
inner_labels = ['X', 'Y', 'Z']
inner_sizes = [25, 35, 40]

# Create the outer pie chart
plt.pie(outer_sizes, labels=outer_labels, radius=1.2,
        wedgeprops=dict(width=0.3, edgecolor='w'))

# Create the inner pie chart
plt.pie(inner_sizes, labels=inner_labels, radius=0.8,
        wedgeprops=dict(width=0.4, edgecolor='w'))

# Add a title
plt.title("Nested Pie Chart")

# Display the chart
plt.show()

radiuswedgeprops 参数用于创建嵌套饼图。

饼图的最佳实践

来源

Matplotlib 饼图文档

在本文中,我们探讨了使用 Matplotlib 的各种类型的饼图,包括基本饼图、自定义饼图、甜甜圈图和嵌套饼图。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我已经撰写了超过 1,400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出 所有 Python 教程