Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas pie plot actual values for multiple graphs

I'm trying to print actual values in pies instead of percentage, for one dimensonal series this helps:

Matplotlib pie-chart: How to replace auto-labelled relative values by absolute values

But when I try to create multiple pies it won't work.

d = {'Yes':pd.Series([825, 56], index=["Total", "Last 2 Month"]), 'No':pd.Series([725, 73], index=["Total", "Last 2 Month"])}
df = pd.DataFrame(d)
df = df.T
def absolute_value(val):
    a  = np.round(val/100.*df.values, 0)
    return a

df.plot.pie(subplots=True, figsize=(12, 6),autopct=absolute_value)
plt.show()

How can I make this right?

Thanks.

like image 238
yigitozmen Avatar asked Nov 15 '25 23:11

yigitozmen


1 Answers

A hacky solution would be to index the dataframe within the absolute_value function, considering that this function is called exactly once per value in that dataframe.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

d = {'Yes':pd.Series([825, 56], index=["Total", "Last 2 Month"]), 
     'No':pd.Series([725, 73], index=["Total", "Last 2 Month"])}
df = pd.DataFrame(d)
df = df.T

i = [0]
def absolute_value(val):
    a  = df.iloc[i[0]%len(df),i[0]//len(df)]
    i[0] += 1
    return a

df.plot.pie(subplots=True, figsize=(12, 6),autopct=absolute_value)
plt.show()

The other option is to plot the pie charts individually by looping over the columns.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

d = {'Yes':pd.Series([825, 56], index=["Total", "Last 2 Month"]), 
     'No':pd.Series([725, 73], index=["Total", "Last 2 Month"])}
df = pd.DataFrame(d)
df = df.T
print df.iloc[:,0].sum()

def absolute_value(val, summ):
    a  = np.round(val/100.*summ,0)
    return a

fig, axes = plt.subplots(ncols=len(df.columns))
for i,ax in enumerate(axes):
    df.iloc[:,i].plot.pie(ax=ax,autopct=lambda x: absolute_value(x,df.iloc[:,i].sum()))
plt.show()

In both cases the output would look similar to this

enter image description here

like image 51
ImportanceOfBeingErnest Avatar answered Nov 18 '25 11:11

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!