x 轴上带有日期时间段(月-年)的散景图

Bokeh plot with datetime period (month-year) on x-axis

我是 bokeh/pandas 的新手,正在尝试通过使用 x 轴的月-年和 y 轴的整数值来绘制趋势线。

我的数据如下所示:

year_month  emp_count
0   2015-09     1450425
1   2015-10     3093811
2   2015-11     3316241
3   2015-12     3308658
4   2016-01     3402191

为了使用散景绘图,我将两列都转换为 ndarray。当我将年月列转换为 ndarray 时,它将每个值显示为一个期间。我使用 to_period('M') 方法从日期列中获取 year_month 。

    temp_df.year_month.values
>>output
    array([Period('2015-09', 'M'), Period('2015-10', 'M'),
           Period('2015-11', 'M'), Period('2015-12', 'M'),
           Period('2016-01', 'M'), Period('2016-02', 'M'),

所以当我使用这些数据绘图时,出现以下错误:

TypeError: Object of type 'Period' is not JSON serializable

为避免此错误,我将 year_month 列类型转换为字符串,但我仍然遇到相同的错误。我的完整代码如下所示:

temp_df.year_month = temp_df.year_month.astype(str)
output_file('trend1.html')
p = figure(title='Employee trend', 
           plot_width=800, 
           plot_height=350,
           x_axis_label='Month-Year', y_axis_label='No of Employees', 
          x_axis_type='datetime')

p.line(x= temp_df.year_month, 
       y = temp_df.emp_count)

show(p)

有谁知道如何使用散景在 x 轴上绘制年月?

我想我找到了问题所在。您应该将列转换为日期时间。

df['year_month']=pd.to_datetime(df['year_month'])

这应该将您的列值更改为如下(天默认为 01):

   year_month      emp_count
0   2015-09-01     1450425
1   2015-10-01     3093811
2   2015-11-01     3316241
3   2015-12-01     3308658
4   2016-01-01     3402191

那么剧情就可以了。我在虚拟值上测试了它,因为输出如下。

Value   month_year
2   2018-11-01
3   2018-01-01
4   2018-02-01
5   2018-05-01


sample=pd.DataFrame(pd.read_csv('sample.csv'))
sample['month_year']=pd.to_datetime(sample['month_year'])
p = figure(title='Employee trend', 
           plot_width=800, 
           plot_height=350,
           x_axis_label='Month-Year', y_axis_label='No of Employees', 
          x_axis_type='datetime')

p.scatter(x= sample.month_year, 
       y = sample.Value)

show(p)

让我知道这是否有效。 谢谢

我已经通过替代方法解决了这个问题。感谢@Samira 的启发。

我从日期对象中提取年月并将日期默认为“1”。

    df = df.join(df.as_of_date.apply(lambda x : pd.Series({
    'day': x.day, 
    'year':x.year, 
    'month': x.month, 
    'year_month': x.to_period('M'),
    'year_month_01': pd.datetime(x.year,x.month,1)
})))

之后在轴上使用 'year_month_01',散景图看起来符合预期。

bokeh graph