Search code examples
pythonpandaspie-chart

Nested pie chart from dataframe


I have a dataframe df like this:

product   count  Class
stuff       3      A
thing       7      A
another     1      B

I can do 2 different pie charts with my code:

my_data = df['count']
my_labels = df['Product']
plt.pie(my_data,labels=my_labels,autopct='%1.1f%%')
plt.title('Distribution 1')
plt.axis('equal')
plt.show()

my_data = df['count']
my_labels = df['Class']
plt.pie(my_data,labels=my_labels,autopct='%1.1f%%')
plt.title('Distribution 2')
plt.axis('equal')
plt.show()

but I want to do a nested pie that could combine both:

When I checked https://matplotlib.org/3.1.1/gallery/pie_and_polar_charts/nested_pie.html I did not understand how to do it not with static values.


Solution

  • I would write your code more closely according to the link you shared. Just replace the array in the example with your columns. You'll probably have to do some additional formatting with the labels, but perhaps it turns out okay with your actual data:

    import matplotlib.pyplot as plt
    df = d1.copy()
    fig, ax = plt.subplots()
    
    size = 0.3
    vals = np.array([[60., 32.], [37., 40.], [29., 10.]])
    
    cmap = plt.get_cmap("tab20c")
    outer_colors = cmap(np.arange(3)*4)
    inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10]))
    
    ax.pie(df.groupby('Class', sort=False)['count'].sum(), radius=1, colors=outer_colors, labels=df['Class'].drop_duplicates(), autopct='%1.1f%%',
           wedgeprops=dict(width=size, edgecolor='w'))
    
    ax.pie(df['count'], radius=1-size, colors=inner_colors, labels=df['product'], autopct='%1.1f%%',
           wedgeprops=dict(width=size, edgecolor='w'))
    
    ax.set(aspect="equal", title='Distribution 1 and 2')
    plt.show()
    

    enter image description here