matplotlib 如何在饼图上显示标签、值和百分比

taor4pac  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(253)

我尝试在饼图上显示:
1.标号
1.价值
1.百分比
我知道如何同时显示值和百分比:

def autopct_format(values):
    def my_format(pct):
        total = sum(values)
        val = int(round(pct*total/100.0)/1000000)
       
        LaString = str('{:.1f}%\n{v:,d}'.format(pct, v=val))
        return LaString
    return my_format

但我不知道如何显示标签,我尝试了以下操作:

def autopct_format(values,MyString):
    def my_format(pct,MyString):
        total = sum(values)
        val = int(round(pct*total/100.0)/1000000)
       
        LaString = str('{0},{:.1f}%\n{v:,d}'.format(MyString, pct, v=val))
        return LaString
    return my_format

但这会引发以下错误:

TypeError: my_format() missing 1 required positional argument: 'MyString'

以下是可重现的示例:

import matplotlib.pyplot as plt
import numpy as np

def autopct_format(values,MyString):
    def my_format(pct,MyString):
        total = sum(values)
        val = int(round(pct*total/100.0)/1000000)
       
        LaString = str('{0},{:.1f}%\n{v:,d}'.format(MyString, pct, v=val))
        return LaString
    return my_format

fig, ax = plt.subplots(1,1,figsize=(10,10),dpi=100,layout="constrained")

ax.axis('equal')

width = 0.3
#Color
A, B, C=[plt.cm.Blues, plt.cm.Reds, plt.cm.Greens]

#OUTSIDE
cin = [A(0.5),A(0.4),A(0.3),B(0.5),B(0.4),C(0.3),C(0.2),C(0.1), C(0.5),C(0.4),C(0.3)]

Labels_Smalls = ['groupA', 'groupB', 'groupC']
labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'I']
Sizes_Detail = [4,3,5,6,5,10,5,5,4,6]
Sizes = [12,11,30]

pie2, _ ,junk = ax.pie(Sizes_Detail ,radius=1,
                 #labels=labels,labeldistance=0.85, 
                 autopct=autopct_format(Sizes_Detail,labels) ,pctdistance = 0.7,
                 colors=cin)

    
plt.setp(pie2, width=width, edgecolor='white')

#INSIDE
pie, _ = ax.pie(Sizes, radius=1-width, 
                #autopct=autopct_format(Sizes) ,pctdistance = 0.8,
                colors = [A(0.6), B(0.6), C(0.6)])

plt.setp(pie, width=width, edgecolor='white')
plt.margins(0,0)

并且有例外输出:

svmlkihl

svmlkihl1#

您可以将带有值的标签发送到autopct_format,并跟踪对内部my_format的调用

def autopct_format(values, labels):
    def my_format(pct):
        total = sum(values)
        val = int(round(pct * total / 100.0) / 1000000)
        LaString = '{l}\n{p:.1f}%\n{v:,d}'.format(l=labels[autopct_format.counter], p=pct, v=val)
        print(LaString)
        autopct_format.counter += 1
        return LaString
    autopct_format.counter = 0
    return my_format

....

labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
Sizes_Detail = [4, 3, 5, 6, 5, 10, 5, 5, 4, 6]

pie2, _, junk = ax.pie(Sizes_Detail, radius=1,
                       autopct=autopct_format(Sizes_Detail, labels),
                       pctdistance=0.7, colors=cin)

相关问题