【问题标题】:How to rotate the percentage label in a pie chart to match the category label rotation?如何旋转饼图中的百分比标签以匹配类别标签旋转?
【发布时间】:2020-10-18 09:20:32
【问题描述】:

我正在做一个个人预算可视化项目来培养我的 Python 能力,但在我希望饼图显示数据的方式上遇到了困难。现在,我有一个饼图,其中包含每个类别的支出和每个类别的预算支出,在饼图之外有类别标签。使用 plt.pie 中的“rotatelabels = True”,旋转标签以与从饼图中心穿过楔形中心的射线对齐。这很好用,但我希望显示在楔形内部的百分比标签也可以旋转,以便类别标签和百分比都与上述光线平行。我已经能够将所有百分比旋转给定的数量,如下面的帖子所示:How can I improve the rotation of fraction labels in a pyplot pie chart ,但我想将其改进为我的目标。关于使用 text.set_rotation 或其他函数或参数来实现这一点的任何提示?

将代码 sn-p 修改为独立于整个项目:

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

【问题讨论】:

    标签: python pandas matplotlib pie-chart


    【解决方案1】:

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

    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 个):

    • "Wedge patches" 列表(圆角三角形)
    • 文本标签列表,作为 matplotlib Text 对象
    • (可选)百分比文本列表(还有Text 对象)

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

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

    【讨论】:

    • 谢谢!补丁、标签、pct_texts 元组有什么用?我对第 7-11 行的语法如何工作有点迷茫(正如您可能期望的那样,我是自学成才的)。饼图定义中元组元素映射到什么,zip() 起什么作用?
    猜你喜欢
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2019-08-25
    • 1970-01-01
    • 2013-10-29
    • 2016-07-06
    相关资源
    最近更新 更多