我如何使用matplotlib创建多个饼图

问题描述 投票:0回答:2

我有一个Pandas DataFrame看起来像这样

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  

我想以每年的事件代码可视化具有最大EventCount(带有饼图)的前5个城市

我该怎么做?

python pandas matplotlib data-visualization pie-chart
2个回答
1
投票

此行的内容:

(df.sort_values('EventCount', ascending=False)
   .groupby('EventCode', as_index=False)
   .head(5)
   .pivot(index='CityName',
                columns='EventCode',
                values='EventCount'
               )
   .plot.pie(subplots=True, figsize=(10,6), layout=(2,3))
)

输出:

enter image description here


1
投票

这可以通过使用数据透视表重组数据,使用sort_valuesDataFrame.plot.pie方法,并使用DataFrame.plot.pie参数在热门城市进行过滤来实现:

subplots

[out]

# 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))

© www.soinside.com 2019 - 2024. All rights reserved.