2016-03-29 4 views
3

So verwende ich diesen Code ein Ringdiagramm mit Python zu erstellen (inspiriert in diesem Donut Plot recipe):Donut Chart 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']) 

die Ergebnisse:

enter image description here

Mein Problem ist, dass ich jetzt die jeweiligen Prozentsätze möchte. Dafür wurde das Hinzufügen ich einfach das Argument:

autopct='%1.1f%%' 

wie folgt aus:

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

aber dies führt zu dem folgenden Fehler:

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 

Also, was mache ich falsch?

Antwort

3

Vom 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. 

Also, wenn Sie das Ergebnis pie() mit autopct Sie müssen 3 Werte entpacken möchten:

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

Oder vielleicht wird es robuster ohne Auspacken, so dass es funktioniert mit oder ohne autopct:

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

Ok, danke. Es funktionierte. – Miguel

Verwandte Themen