blo*_*ley 6 python plot datetime matplotlib pandas
我需要创建按月分组的行频条形图。
问题在于水平轴不是正确的时间轴:它错过了没有数据的月份,因此它不是连续的时间轴。
示例代码:
%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();
Run Code Online (Sandbox Code Playgroud)
生成的条形图缺少2017-04月份。
如何制作熊猫来绘制整个月,甚至没有数据的月份?
为了记录,我使用了这个代码:
%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')
# Get the start and end months
months = df['month'].sort_values()
start_month = months.iloc[0]
end_month = months.iloc[-1]
index = pd.PeriodIndex(start=start_month, end=end_month)
df.groupby('month')['model'].count().reindex(index).plot.bar();
Run Code Online (Sandbox Code Playgroud)
这给出了这个情节:
感谢 EdChum