繁体   English   中英

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

[英]How to rotate the percentage label in a pie chart to match the category label rotation?

我正在开展一个个人预算可视化项目来培养我的 Python 能力,并且在我希望饼图如何显示数据方面遇到了障碍。 现在,我有一个饼图,其中包含每个类别的支出和每个类别的预算支出,饼图外有类别标签。 使用 plt.pie 中的“rotatelabels = True”,旋转标签以与从饼图中心到楔形中心的光线对齐。 这很好用,但我希望楔形内显示的百分比标签也可以旋转,以便类别标签和百分比都与上述光线平行。 我已经能够将所有百分比旋转给定的数量,如此处的帖子所示: 如何改进 pyplot 饼图中分数标签的旋转,但我想将其改进为我的目标。 关于使用 text.set_rotation 或其他函数或参数来实现这一目标的任何提示?

修改后的代码片段可以独立于整个项目运行:

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()

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

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()

示例图

plt.pie()返回 3 个列表(如果没有百分比文本,则返回 2 个):

  • “楔形补丁”列表(圆形三角形)
  • 文本标签列表,作为 matplotlib Text对象
  • (可选)百分比文本列表(也是Text对象)

for label, pct_text in zip(labels, pct_texts):是 Python 同时循环遍历两个列表的方式。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM