要怎么在matplotlib饼图上加百分比

代码如图,这样获得的饼图

df = pd.read_csv('data.csv',encoding='ANSI')
ownership = df['description'].value_counts()
print(ownership)
plt.title('数量分布:\n')
ownership.plot(kind='pie')
plt.show()

要在Matplotlib的饼图上添加百分比标签,您可以使用autopct参数来实现。

df = pd.read_csv('data.csv', encoding='ANSI')
ownership = df['description'].value_counts()

plt.title('数量分布:\n')
ownership.plot(kind='pie', autopct='%1.1f%%')

plt.show()

在上面的代码中,autopct='%1.1f%%'表示将百分比以保留一位小数的形式显示在每个饼图块上。您还可以根据需要调整百分比的显示格式,例如,如果想要保留两位小数,可以使用autopct='%1.2f%%'。

最后,调用plt.show()方法显示饼图。请确保在运行该代码之前已经导入了必要的库(import matplotlib.pyplot as plt 和 import pandas as pd)。

【以下回答由 GPT 生成】

可以使用Matplotlib中的autopct参数来在饼图上显示百分比。下面是修改后的代码:

df = pd.read_csv('data.csv', encoding='ANSI')
ownership = df['description'].value_counts()

print(ownership)
plt.title('数量分布:')
ownership.plot(kind='pie', autopct='%1.1f%%')
plt.show()

此处的autopct='%1.1f%%'表示在饼图的每个部分上显示一个带有一位小数的百分比。可以根据需要调整autopct参数的格式。

希望能帮到你!



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^