如何向Matplotlib饼图添加图例?
Matplotlib是一个用于绘制2D图形的Python库,其中饼图是一种很常见的图形类型。但有时候在饼图上添加图例,可以使得饼图更加易读且专业。在这篇文章中,我们将讨论如何向Matplotlib的饼图中添加图例。
示例代码
在开始之前,我们需要安装Matplotlib库。如果你还没有安装,可以运行以下命令来安装Matplotlib。
pip install matplotlib
接下来,我们可以使用如下示例代码来创建一个标准的Matplotlib饼图。
import matplotlib.pyplot as plt
labels = ['Apple', 'Banana', 'Orange']
sizes = [30, 40, 30]
colors = ['red', 'yellow', 'orange']
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
ax.axis('equal')
plt.show()
这个代码会绘制一个由三个部分构成的饼图,每个部分的标签分别为“Apple”、“Banana”和“Orange”。
现在我们将在这个饼图中添加图例。
添加图例的4个方法
1.使用ax.legend()
函数
在Matplotlib中,可以使用ax.legend()
函数来添加图例。我们只需将每部分的标签与颜色存储在一个元组列表中,并将其传递给该函数即可。
import matplotlib.pyplot as plt
labels = ['Apple', 'Banana', 'Orange']
sizes = [30, 40, 30]
colors = ['red', 'yellow', 'orange']
labels_colors = list(zip(labels, colors))
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
ax.legend(labels_colors, title='Fruit', loc='center right')
ax.axis('equal')
plt.show()
这个代码会在饼图的右侧添加一个图例,其中包含有关每个部分的信息。
注意:ax.legend()
函数的第一个参数是一个元组列表,其中每个元组都包含了一个标签和一个颜色,第二个参数是题目。
2.使用plt.legend()
函数
除了使用ax.legend()
函数之外,还可以使用plt.legend()
函数向饼图中添加图例。这种方法与第一种方法非常相似,但我们必须使用bbox_to_anchor
参数来决定图例的位置。
import matplotlib.pyplot as plt
labels = ['Apple', 'Banana', 'Orange']
sizes = [30, 40, 30]
colors = ['red', 'yellow', 'orange']
labels_colors = list(zip(labels, colors))
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
plt.legend(labels_colors, title='Fruit', bbox_to_anchor=(1, 0.5))
ax.axis('equal')
plt.show()
这个代码会在饼图的右侧添加一个图例,距离饼图有一定距离。
3.使用Pandas库绘制饼图
如果你使用的是Pandas库绘制饼图,那么可以使用DataFrame.plot.pie()
方法来绘制饼图,并通过设置legend=True
启用图例。
import pandas as pd
import matplotlib.pyplot as plt
data = {'size': [30, 40, 30]}
df = pd.DataFrame(data, index=['Apple', 'Banana', 'Orange'])
ax = df.plot.pie(y='size', figsize=(5, 5), legend=True, autopct='%1.1f%%', startangle=90)
plt.show()
4.使用Seaborn库绘制饼图
如果你使用的是Seaborn库绘制饼图,那么可以使用seaborn.pieplot()
函数来绘制饼图,并通过设置legend=True
启用图例。
import seaborn as sns
import matplotlib.pyplot as plt
labels = ['Apple', 'Banana', 'Orange']
sizes = [30, 40, 30]
colors = ['red', 'yellow', 'orange']
sns.set(style='whitegrid')
fig, ax = plt.subplots()
sns.pieplot(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90, legend=True)
plt.show()
这个代码会绘制一个与第一个示例代码相同的饼图,并在饼图下方添加一个图例。
结论
在本文中,我们介绍了向Matplotlib饼图添加图例的4种方法。我们可以使用ax.legend()
函数、plt.legend()
函数、Pandas库或Seaborn库来实现这个目标。在实践过程中,你可以选择最适合你的方法。无论你选择哪种方法,通过添加图例,你可以使饼图变得更加易读、专业。