brewer.py将xaxis转换为日期

2024-06-10 10:37:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图把这个例子改成x轴,用日期来理解bokeh的概念

https://docs.bokeh.org/en/latest/docs/gallery/brewer.html

N = 4
cats = 3
data = [[2,3,4], [2,2,3], [0,0,0], [1,2,3]]
df = pd.DataFrame(data, columns=['y0', 'y1', 'y2'])

print df
dates = ['2016-06-01','2016-06-02','2016-06-03','2016-06-04']

def stacked(df):
    df_top = df.cumsum(axis=1)
    df_bottom = df_top.shift(axis=1).fillna({'y0': 0})[::-1]
    df_stack = pd.concat([df_bottom, df_top], ignore_index=True)
    return df_stack

areas = stacked(df)
colors = brewer['Spectral'][areas.shape[1]]
x2 = np.hstack((df.index[::-1], df.index))
p = figure(x_range=(0, N-1), y_range=(0, 50))
# p.xaxis.major_label_overrides = {
#     i: date.strftime('%b %d') for i, date in enumerate(pd.to_datetime(dates))
# }
# p.xaxis.bounds = (0, df.index[-1])
p.grid.minor_grid_line_color = '#eeeeee'

p.patches([x2] * areas.shape[1], [areas[c].values for c in areas],
          color=colors, alpha=0.8, line_color=None)

output_file('brewer.html', title='brewer.py example')

show(p)

通过上面的例子,我得到了x轴0,1,2,3,我可以放大

如何将此更改为日期。我可以做一些类似于x_range=dates,遍历日期列表的事情吗。 我试过注释代码,但它不更新次要标签,我不能放大。 日期必须在df'? Currently mydf`is中吗

   y0  y1  y2
0   2   3   4
1   2   2   3
2   0   0   0
3   1   2   3

如果dates必须在df中,我可以添加如下内容

   y0  y1  y2        date
0   2   3   4  2016-06-01
1   2   2   3  2016-06-02
2   0   0   0  2016-06-03
3   1   2   3  2016-06-04

但仍然不知道如何在x轴上绘制这些日期


Tags: dfdateindextopbokehrange例子color
1条回答
网友
1楼 · 发布于 2024-06-10 10:37:21

您可以在bokeh.plotting.figure函数中使用x_axis_type='datetime'来指示您的x轴将要显示时间

import pandas as pd
import numpy as np
import bokeh
import bokeh.plotting

N = 4
cats = 3
data = [[2,3,4], [2,2,3], [0,0,0], [1,2,3]]
df = pd.DataFrame(data, columns=['y0', 'y1', 'y2'])

print df
dates = ['2016-06-01','2016-06-02','2016-06-03','2016-06-04']
dt = [pd.datetime.strptime(x,'%Y-%m-%d') for x in dates]
def stacked(df):
    df_top = df.cumsum(axis=1)
    df_bottom = df_top.shift(axis=1).fillna({'y0': 0})[::-1]
    df_stack = pd.concat([df_bottom, df_top], ignore_index=True)
    return df_stack

areas = stacked(df)
colors = bokeh.palettes.brewer['Spectral'][areas.shape[1]]

x2 = np.hstack((dt[::-1], dt))
p = bokeh.plotting.figure(x_axis_type='datetime', y_range=(0, 10))

p.xaxis.formatter = bokeh.models.formatters.DatetimeTickFormatter(
    days=["%Y-%m-%d"])

p.grid.minor_grid_line_color = '#eeeeee'

p.patches([x2] * areas.shape[1], [areas[c].values for c in areas],
          color=colors, alpha=0.8, line_color=None)
bokeh.io.output_file('brewer.html', title='brewer.py example')

bokeh.io.show(p)

enter image description here

相关问题 更多 >