gpt4 book ai didi

python - Brewer.py 将 x 轴转换为日期

转载 作者:行者123 更新时间:2023-12-01 09:22:47 25 4
gpt4 key购买 nike

我正在尝试将此示例更改为带有日期的 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 my
中df` 是

   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 轴上绘制这些日期。

最佳答案

您可以在 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

关于python - Brewer.py 将 x 轴转换为日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50689985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com