python - 使用 matplotlib 绘制熊猫数据框,数据按年/月分组
问题描述
我正在使用 jupyter、pandas 和 matplotlib 来创建一个包含以下数据的图。
如何创建一个绘图,将 x 轴上的月份和年份中的数据组合在一起,以更清楚地表明月份与年份相关联
year month count
2005 9 40789
2005 10 17998
...
2014 12 2168
2015 1 2286
2015 2 1274
2015 3 1126
2015 4 344
df.plot(kind='bar',x='month',y='num',color='blue', title="Num per year")
plt.show()
解决方案
你可以给每一年涂上不同的颜色。
创建一些数据:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
# here's some data
N=50
df = pd.DataFrame({'year': np.random.randint(2005,2015,N),
'month': np.random.randint(1,12,N),
'count': np.random.randint(1,1500,N)})
df.sort_values(by=['year', 'month'],inplace=True)
然后为每一年创建一个颜色数组:
# color map based on years
yrs = np.unique(df.year)
c = cm.get_cmap('tab20', len(yrs))
## probably a more elegant way to do this...
yrClr = np.zeros((len(df.year),4))
for i, v in enumerate(yrs):
yrClr[df.year==v,:]=c.colors[i,:]
# then use yrClr for color
df.plot(kind='bar', x='month', y='count', color=yrClr, title="Num per year")
更新:将 x 轴组合为月+年也可能会有所帮助,就像这样。
fig, axs = plt.subplots(figsize=(12, 4))
df['MonthYr']=pd.to_datetime(df.assign(day=1)[['year','month','day']]).dt.strftime('%m-%Y')
df.plot(kind='bar', x='MonthYr', y='count', color=yrClr, title="Num per year",ax=axs)
推荐阅读
- functional-programming - 了解单子遍历的副作用
- android - 在 Android 上生成单元测试
- xslt-2.0 - XML 到 XML,无法使用带有重复元素的选择副本
- regex - 在 nifi 中使用正则表达式删除额外值时出错
- vba - 如何在 Outlook 打开后 2 分钟在 Outlook 上启动宏
- php - 使用 $write->save 的 Phpspreadsheet 不起作用 - 错误处理
- angular - 它的等效事件在 blazor 中发出 angular/vue?
- oracle - Oracle APEX - 没有前导零
- selenium - Webdriver-manager 错误:无法使用 *my config* 创建会话
- java - 我如何解决这种死锁情况?