Search code examples
pythonpandasmatplotlibplotpie-chart

plotting a series pie chart


I have a series df2 which I want to plot using pie chart

 Index
Friday       2
Thursday     2
Wednesday    3

I have tried

 colors =  ["#E13F29", "#D69A80", "#D63B59", "#AE5552", "#CB5C3B", "#EB8076", "#96624E"]
df2.plot().pie(df2['counts'],df2.index,shadow=False,colors=colors, explode=(0, 0, 0, 0, 0.15), startangle=90,autopct='%1.1f%%', )
# View the plot drop above
pyplot.axis('equal')
# View the plot
pyplot.tight_layout()
pyplot.show()

ValueError: could not convert string to float: 'Wednesday'


Solution

  • Consider a pd.Series -

    s
    
    Index
    Monday       2
    Tuesday      4
    Wednesday    5
    Thursday     2
    Friday       1
    Saturday     6
    Sunday       3
    Name: counts, dtype: int64
    

    Now, call pd.Series.plot.pie on counts column -

    s.plot.pie(y=df.index,
               shadow=False,
               colors=colors, 
               explode=(0, 0, 0, 0, 0.15, 0, 0),   # exploding 'Friday'
               startangle=90,
               autopct='%1.1f%%')
    
    plt.axis('equal')
    plt.tight_layout()
    plt.show()
    

    Don't call plot()! Call pie on plot.

    enter image description here


    If you need your index sorted by weekday, make sure to convert it to pd.Categorical -

    cat = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday']
    
    df.index = pd.Categorical(df.index, categories=cat, ordered=True)
    df = df.sort_index()
    

    And then, you can plot as shown above.