因此,我使用以下代码用python创建了一个甜甜圈图(在此甜甜圈图recipe中得到启发):

def make_pie(sizes, text,colors,labels):
    import matplotlib.pyplot as plt
    import numpy as np

    col = [[i/255. for i in c] for c in colors]

    fig, ax = plt.subplots()
    ax.axis('equal')
    width = 0.35
    kwargs = dict(colors=col, startangle=180)
    outside, _ = ax.pie(sizes, radius=1, pctdistance=1-width/2,labels=labels,**kwargs)
    plt.setp( outside, width=width, edgecolor='white')

    kwargs = dict(size=20, fontweight='bold', va='center')
    ax.text(0, 0, text, ha='center', **kwargs)
    plt.show()

c1 = (226,33,7)
c2 = (60,121,189)

make_pie([257,90], "Gender (AR)",[c1,c2],['M','F'])

结果是:

python - 甜甜圈图python-LMLPHP

我的问题是,现在我想要各自的百分比。为此,我只是添加了参数:
autopct='%1.1f%%'

像这样:
kwargs = dict(colors=col, startangle=180,autopct='%1.1f%%')

但这会导致以下错误:
Traceback (most recent call last):
  File "draw.py", line 30, in <module>
    make_pie([257,90], "Gender (AR)",[c1,c2],['M','F'])
  File "draw.py", line 13, in make_pie
    outside, _ = ax.pie(sizes, radius=1, pctdistance=1-width/2,labels=labels,**kwargs)
ValueError: too many values to unpack

那么,我在做什么错呢?

最佳答案

从文档字符串:



因此,如果要使用pie()解压缩autopct的结果,则需要3个值:

kwargs = dict(colors=col, startangle=180, autopct='%1.1f%%')
outside, _, _ = ax.pie(sizes, radius=1, pctdistance=1-width/2,
                       labels=labels,**kwargs)

或者,也许在不解压的情况下它会更健壮,因此无论是否使用autopct,它都可以工作:
outside = ax.pie(sizes, radius=1, pctdistance=1-width/2,
                 labels=labels,**kwargs)[0]

09-26 21:15