【发布时间】:2017-09-26 17:13:55
【问题描述】:
我需要创建一个按月分组的行频条形图。
问题在于横轴不是一个正确的时间轴:它错过了没有数据的月份,所以它不是一个连续的时间轴。
示例代码:
%matplotlib inline
import pandas as pd
d = {'model': 'ep',
'date': ('2017-02-02', '2017-02-04', '2017-03-01')}
df1 = pd.DataFrame(d)
d = {'model': 'rs',
'date': ('2017-01-12', '2017-01-04', '2017-05-01')}
df2 = pd.DataFrame(d)
df = pd.concat([df1, df2])
# Create a column containing the month
df['month'] = pd.to_datetime(df['date']).dt.to_period('M')
# Group by the month and plot
df.groupby('month')['model'].count().plot.bar();
生成的条形图缺少 2017-04 月份。
如何让 pandas 绘制所有月份,即使是那些没有数据的月份?
【问题讨论】:
标签: python pandas datetime matplotlib plot