好吧,如果您有一个字符串列表作为 x 轴,那么显然计数从 1 开始,那么您必须修改 x 数据以使绘图从 1 开始。实际上,brewer 示例(http://docs.bokeh.org/en/latest/docs/gallery/stacked_area.html)的范围是 0 到 19,所以它有 20 个数据点,而不是像你的那样有 19 个数据点timesteps
列表。我将绘图的 x 输入修改为:data['x'] = np.arange(1,N+1)
从 1 开始到 N。我在你的列表中又添加了一天:timesteps = [str(x.date()) for x in pd.date_range('1950-01-01', '1951-08-01', freq='MS')]
这是完整的代码:
import numpy as np
import pandas as pd
from bokeh.plotting import figure, show, output_file
from bokeh.palettes import brewer
N = 20
categories = ['y' + str(x) for x in range(10)]
data = {}
data['x'] = np.arange(1,N+1)
for cat in categories:
data[cat] = np.random.randint(10, 100, size=N)
df = pd.DataFrame(data)
df = df.set_index(['x'])
def stacked(df, categories):
areas = dict()
last = np.zeros(len(df[categories[0]]))
for cat in categories:
next = last + df[cat]
areas[cat] = np.hstack((last[::-1], next))
last = next
return areas
areas = stacked(df, categories)
colors = brewer["Spectral"][len(areas)]
x2 = np.hstack((data['x'][::-1], data['x']))
timesteps = [str(x.date()) for x in pd.date_range('1950-01-01', '1951-08-01', freq='MS')]
p = figure(x_range=bokeh.models.FactorRange(factors=timesteps), y_range=(0, 800))
p.grid.minor_grid_line_color = '#eeeeee'
p.patches([x2] * len(areas), [areas[cat] for cat in categories],
color=colors, alpha=0.8, line_color=None)
p.xaxis.major_label_orientation = np.pi/4
bokeh.io.show(p)
这是输出:
UPDATE
你可以走了data['x'] = np.arange(0,N)
从 0 到 19,然后使用offset=-1
inside FactorRange
, i.e. figure(x_range=bokeh.models.FactorRange(factors=timesteps,offset=-1),...
更新版本散景0.12.16
在这个版本中我使用的是datetime
对于 x 轴,其优点是放大时格式更好。
import numpy as np
import pandas as pd
from bokeh.plotting import figure, show, output_file
from bokeh.palettes import brewer
timesteps = [x for x in pd.date_range('1950-01-01', '1951-07-01', freq='MS')]
N = len(timesteps)
cats = 10
df = pd.DataFrame(np.random.randint(10, 100, size=(N, cats))).add_prefix('y')
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((timesteps[::-1], timesteps))
p = figure( x_axis_type='datetime', y_range=(0, 800))
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)
p.xaxis.formatter = bokeh.models.formatters.DatetimeTickFormatter(
months=["%Y-%m-%d"])
p.xaxis.major_label_orientation = 3.4142/4
output_file('brewer.html', title='brewer.py example')
show(p)