Donut chart python

▼魔方 西西 提交于 2019-12-06 05:25:04

问题


So I using this code to create a donut chart with python (inspired in this Donut plot 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'])

which results in:

My problem is that now I want the respective percentages. For that I was simply adding the argument:

autopct='%1.1f%%'

like this:

kwargs = dict(colors=col, startangle=180,autopct='%1.1f%%')

but this results in the following error:

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

So, what am I doing wrong?


回答1:


From the docstring:

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.

So if you want to unpack the result of pie() using autopct you need 3 values:

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

Or maybe it will be more robust without unpacking so it works with or without autopct:

outside = ax.pie(sizes, radius=1, pctdistance=1-width/2,
                 labels=labels,**kwargs)[0]


来源:https://stackoverflow.com/questions/36296101/donut-chart-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!