How can i create multiple pie chart using matplotlib

Viewed 1544

I have a Pandas DataFrame seems like this

Year    EventCode   CityName    EventCount
2015    10          Jakarta     12
2015    10          Yogjakarta  15
2015    10          Padang      27
...
2015    13          Jayapura    34 
2015    14          Jakarta     24
2015    14          Yogjaarta   15
...
2019    14          Jayapura    12  

i want to visualize top 5 city that have the biggest EventCount (with pie chart), group by eventcode in every year

How can i do that?

2 Answers

This could be achieved by restructuring your data with pivot_table, filtering on top cities using sort_values and the DataFrame.plot.pie method with subplots parameter:

# Pivot your data
df_piv = df.pivot_table(index='EventCode', columns='CityName',
                        values='EventCount', aggfunc='sum', fill_value=0)


# Get top 5 cities by total EventCount
plot_cities = df_piv.sum().sort_values(ascending=False).head(5).index

# Plot
df_piv.reindex(columns=plot_cities).plot.pie(subplots=True,
                                             figsize=(10, 7),
                                             layout=(-1, 3))

[out]

enter image description here

Pandas supports plotting each column into a subplot automatically. So you want to select the CityName as index, make EventCode as column and plot.

(df.sort_values('EventCount', ascending=False) # sort descending by `EventCount`  
   .groupby('EventCode', as_index=False)
   .head(5)                                    # get 5 most count within `EventCode`
   .pivot(index='CityName',                    # pivot for plot.pie
          columns='EventCode',
          values='EventCount'
         )
   .plot.pie(subplots=True,                    # plot with some options
             figsize=(10,6), 
             layout=(2,3))
)

Output:

enter image description here

Related