【问题标题】:Grouping values in a clustered pie chart在聚类饼图中对值进行分组
【发布时间】:2022-11-20 23:04:55
【问题描述】:
我正在处理一个关于某些房屋何时建造的数据集,我的数据从 1873 年到 2018 年(143 个切片)。我试图以饼图的形式将这些数据可视化,但由于大量的独立切片,整个饼图显得杂乱无章。
我试图通过将 15 年时间段内的值分组并在饼图上显示这些时间段来解决这个问题。我在 StackOverflow 上看到了一篇类似的帖子,其中建议的解决方案是使用字典并定义一个阈值来对值进行分组,但是在我自己的饼图上实现一个版本并没有奏效,我想知道如何解决这个问题
代码
testing = df1.groupby("Year Built").size()
testing.plot.pie(autopct="%.2f",figsize=(10,10))
plt.ylabel(None)
plt.show()
Dataframe(testing)
Current Piechart
【问题讨论】:
标签:
python
pandas
dataframe
graph
pie-chart
【解决方案1】:
为了将来,始终提供您正在处理的数据的 reproducible example(可能使用 df.head().to_dict())。使用pd.resample 可以解决您的问题。
# Data Used
df = pd.DataFrame( {'year':np.arange(1890, 2018), 'built':np.random.randint(1,150, size=(2018-1890))} )
>>> df.head()
year built
0 1890 34
1 1891 70
2 1892 92
3 1893 135
4 1894 16
# First, convert your 'year' values into DateTime values and set it as the index
df['year'] = pd.to_datetime(df['year'], format=('%Y'))
df_to_plot = df.set_index('year', drop=True).resample('15Y').sum()
>>> df_to_plot
built
year
1890-12-31 34
1905-12-31 983
1920-12-31 875
1935-12-31 1336
1950-12-31 1221
1965-12-31 1135
1980-12-31 1207
1995-12-31 1168
2010-12-31 1189
2025-12-31 757
你也可以使用pd.cut()
df['group'] = pd.cut(df['year'], 15, precision=0)
df.groupby('group')[['year']].sum().plot(kind='pie', subplots=True, figsize=(10,10), legend=False)