pandas : how to create nested pie chart?

I have a dataframe as such

error_code, num_errors, event_type
404,78,GET
403,8,GET
504,54,POST
304,67,UP

I would like to create a nested ie chart where the first layer would show the breakdown (each slice represents fraction of num_errors) with respect to error_code column.
The next layer would show the breakdown with respect to event_type column

Here is what i tried so far

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

ax.pie(pdfrt.groupby('error_code')['num_errors'].sum(),radius=1,  
       labels=pdfrt['error_code'].values,
       autopct='%1.0f%%',
       wedgeprops=dict(width=0.5, edgecolor='w'))

ax.pie(pdfrt['num_errors'].values, labels=pdfrt['event_type'].values,radius=1-0.5, autopct='%1.0f%%',
       wedgeprops=dict(width=0.5, edgecolor='w'))

ax.set_title('Errors Count')
plt.tight_layout()
plt.show()

but i get error

ValueError: 'label' must be of length 'x'

at

ax.pie(pdfrt.groupby('error_code')['num_errors'].sum(),radius=1,  
           labels=pdfrt['error_code'].values,
           autopct='%1.0f%%',
           wedgeprops=dict(width=0.5, edgecolor='w'))

what am i doing wrong? note that i am able to create a single level pie chart as

ax.pie(pdfrt['num_errors'].values, labels=pdfrt['event_type'].values,radius=1-0.5, autopct='%1.0f%%',
           wedgeprops=dict(width=0.5, edgecolor='w'))

or even

ax.pie(pdfrt['num_errors'].values, labels=pdfrt['error_code'].values,radius=1-0.5, autopct='%1.0f%%',
           wedgeprops=dict(width=0.5, edgecolor='w'))

    

the problem is how do i combine the two?

>Solution :

pdfrt.groupby('error_code')['num_errors'].sum()

&

labels=pdfrt['error_code'].values

Unlike your example, the length of the output of the above two codes in the actual dataset is different()

So modify like below

labels=pdfrt['error_code'].values

->

labels=pdfrt.groupby('error_code')['num_errors'].sum().index

full Code

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

ax.pie(pdfrt.groupby('error_code')['num_errors'].sum(),radius=1,  
       labels=pdfrt.groupby('error_code')['num_errors'].sum().index, autopct='%1.0f%%',
       wedgeprops=dict(width=0.5, edgecolor='w'))



ax.pie(pdfrt['num_errors'], labels=pdfrt['event_type'], radius=1-0.5, autopct='%1.0f%%',
       wedgeprops=dict(width=0.5, edgecolor='w')) # also removed unnecessary values ​​attribute

ax.set_title('Errors Count')
plt.tight_layout()
plt.show()

Leave a Reply