如何在饼图中旋转百分比标签以匹配类别标签旋转?

2024-05-08 19:38:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在进行一个个人预算可视化项目,以建立我的python能力,但在如何使用饼图显示数据方面遇到了一个障碍。现在,我有一个饼图,上面有每个类别的支出和每个类别的预算支出,饼图外有类别标签。使用plt.pie中的“rotatelabels=True”旋转标签,使其与从饼图中心到楔块中心的光线对齐。这非常有效,但我希望显示在楔体内部的百分比标签也可以旋转,以便类别标签和百分比都与前面提到的光线平行。我已经能够将所有的百分比按给定的数量进行轮换,如这里的帖子所示:How can I improve the rotation of fraction labels in a pyplot pie chart ,但我想根据我的目标改进它。关于如何使用text.set_旋转或其他函数或参数来实现这一点,有什么提示吗

修改代码段,使其在整个项目中起独立作用:

import pandas as pd
cat = ['Utilities', 'Home', 'Bike', 'Medical', 'Personal', 'Food', 'Groceries', 'Student Loans', 'Transit', 'Rent']
dict = {8:54.99,14:59.91,3:69.03,10:79.00,9:119.40,1:193.65,0:205.22,4:350.00,7:396.51,2:500.00}
nonzero_spending = pd.DataFrame(list(dict.items()), columns = ['index_col', 'Sum'])
plt.pie(nonzero_spending['Sum'],labels=cat,radius = 2,startangle = 160,autopct=lambda p : '{:.2f}%  ({:,.0f})'.format(p,p * sum(nonzero_spending['Sum'])/100), rotatelabels = True, pctdistance=0.8)
plt.title('Spending')
plt.axis('equal')
plt.show()

Tags: 项目truelabelsplt标签中心类别pd
1条回答
网友
1楼 · 发布于 2024-05-08 19:38:15

您可以提取外部标签的旋转并将其应用于百分比文本:

import matplotlib.pyplot as plt
import pandas as pd

cat = ['Utilities', 'Home', 'Bike', 'Medical', 'Personal', 'Food', 'Groceries', 'Student Loans', 'Transit', 'Rent']
dict = {8: 54.99, 14: 59.91, 3: 69.03, 10: 79.00, 9: 119.40, 1: 193.65, 0: 205.22, 4: 350.00, 7: 396.51, 2: 500.00}
nonzero_spending = pd.DataFrame(list(dict.items()), columns=['index_col', 'Sum'])
patches, labels, pct_texts = plt.pie(nonzero_spending['Sum'], labels=cat, radius=2, startangle=160,
                                     autopct=lambda p: f"{p:.2f}%  ({p * sum(nonzero_spending['Sum']) / 100:,.0f})",
                                     rotatelabels=True, pctdistance=0.5)
for label, pct_text in zip(labels, pct_texts):
    pct_text.set_rotation(label.get_rotation())
plt.title('Spending')
plt.axis('equal')
plt.tight_layout()
plt.show()

example plot

^{}返回3个列表(如果没有百分比文本,则返回2个):

  • {a3}列表(圆形三角形)
  • 文本标签的列表,如matplotlib^{}对象
  • (可选)百分比文本列表(也是Text对象)

for label, pct_text in zip(labels, pct_texts):是Python同时loop through the two lists的方式

pct_text.set_rotation(label.get_rotation())获取每个标签Text对象的旋转,并将此值设置为相应百分比文本对象的旋转

相关问题 更多 >