簡體   English   中英

plot 如何在周期時間內分類堆積條形圖?

[英]How can plot categorical stacked bar over periodic time?

我試圖在周期性時間(5 年)內提取堆積條形圖:

import pandas as pd
categorical = ["RL","CD(others)","DL","ML","ML","ML","DL","ML","DL","DL"]
year = [2014,2014,2015,2015,2016,2017,2019,2021,2022,2022]
df = pd.DataFrame({'year':year,
                   'keywords':categorical})
df

我嘗試了相關的 post1post2post3來解決問題:

#solution1:Pivot table
df.pivot_table(index='year',
               columns='keywords',
              # values='paper_count',
               aggfunc='sum')
#df.plot(x='year', y='paper_count', kind='bar')


#solution2: groupby
# reset_index() gives a column for counting after groupby uses year and category
ctdf = (df.reset_index()
          .groupby(['year'], as_index=False)
          .count()
          # rename isn't strictly necessary here; it's just for readability
          .rename(columns={'index':'paper_count'})
       )
ctdf.plot(x='year', y='paper_count', kind='bar')

最后,我無法弄清楚 plot 是如何通過每 5 年定期計數的:

2000-20052005-20102015-20202020-2025

預計 output

在此處輸入圖像描述

如果提供的示例應該與數據匹配,我不明白完整的邏輯,但您可以使用pandas.cut來形成箱子,然后使用cumsum來獲得累計總和(如果您只想要一個簡單的總和,請刪除它):

years = list(range(2000, 2030, 5))
# [2000, 2005, 2010, 2015, 2020, 2025]
labels = [f'{a}-{b}' for a,b in zip(years, years[1:])]
# ['2000-2005', '2005-2010', '2010-2015', '2015-2020', '2020-2025']

(df.assign(year=pd.cut(df['year'], bins=years, labels=labels))
   .groupby(['year', 'keywords'])['year'].count()
   .unstack()
   .plot.bar(stacked=True)
)

用紅線:

years = list(range(2000, 2030, 5))
# [2000, 2005, 2010, 2015, 2020, 2025]
labels = [f'{a}-{b}' for a,b in zip(years, years[1:])]
# ['2000-2005', '2005-2010', '2010-2015', '2015-2020', '2020-2025']

df2 = (df
 .assign(year=pd.cut(df['year'], bins=years, labels=labels))
 .groupby(['year', 'keywords'])['year'].count()
 .unstack()
)

ax = df2.plot.bar(stacked=True)
# adding arbitrary shift (0.1)
df2.sum(axis=1).add(0.1).plot(ax=ax, color='red', marker='s', label='paper count')
ax.legend()

output:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM