首页 > 解决方案 > 使用 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()

在此处输入图像描述

标签: pythonpandasmatplotlibjupyter

解决方案


你可以给每一年涂上不同的颜色。

创建一些数据:

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)

在此处输入图像描述


推荐阅读