Show both value and percentage on a pie chart [duplicate]
Asked Answered
A

2

11

Here's my current code

values = pd.Series([False, False, True, True])
v_counts = values.value_counts()
fig = plt.figure()
plt.pie(v_counts, labels=v_counts.index, autopct='%.4f', shadow=True);

Currently, it shows only the percentage (using autopct)

I'd like to present both the percentage and the actual value (I don't mind about the position)

Appreciable answered 8/1, 2020 at 11:21 Comment(0)
T
16

Create your own formatting function. Note that you have to recalculate the actual value from the percentage in that function somehow

def my_fmt(x):
    print(x)
    return '{:.4f}%\n({:.0f})'.format(x, total*x/100)


values = pd.Series([False, False, True, True, True, True])
v_counts = values.value_counts()
total = len(values)
fig = plt.figure()
plt.pie(v_counts, labels=v_counts.index, autopct=my_fmt, shadow=True);

enter image description here

Tyndall answered 8/1, 2020 at 11:36 Comment(0)
G
13

@diziet-asahi's code didn't work for me, instead you can use:

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

plt.pie(mydata,labels = mylabels, autopct=autopct_format(mydata))

And here is my output:

enter image description here

Note: if you want more decimals, just change the number in the return of my_format(pct)

Grew answered 17/3, 2022 at 15:32 Comment(2)
@diziet-asahi's code works for me, but I prefer this solution as it is more self-contained (does not rely a global variable not passed as a parameter). However, this version didn't work for me, until I substituted the variables used in both the original post and the the other solution: plt.pie(v_counts, labels=v_counts.index, autopct=autopct_format(values))Isabeau
Thank you for your comment, it is still working for me I use it daily, really weird. I guess it depends on how your data format is.Detwiler

© 2022 - 2024 — McMap. All rights reserved.