甜甜圈图 Python

6

我使用以下代码来用Python创建甜甜圈图表(灵感来源于这个甜甜圈图配方):

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'])

这将导致:

enter image description here

我的问题是现在我想要相应的百分比。为此,我只需添加参数:
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

所以,我做错了什么?
1个回答

5

从文档字符串中:

If *autopct* is not *None*, return the tuple (*patches*,
  *texts*, *autotexts*), where *patches* and *texts* are as
  above, and *autotexts* is a list of
  :class:`~matplotlib.text.Text` instances for the numeric
  labels.

如果您想使用autopct来解包pie()的结果,则需要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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接