Skip to main content
 首页 » 编程设计

python之Bokeh 中具有多个 x 轴刻度的水平条形图和折线图

2025年02月15日12zhwl

我试图在一张图表上绘制水平直方图和直方图下数据的时间序列。自然地,这需要一个共享的 y 轴和两个 x 轴——一个用于直方图频率,另一个用于日期时间。但是,我似乎无法让日期时间轴很好地发挥作用。它最终合并了与直方图关联的 0 值,然后将其转换为 1970-01-01(不是我想要的)。

import numpy as np 
import pandas as pd 
from bokeh.io import show  
from bokeh.plotting import figure 
from bokeh.models import LinearAxis, DatetimeTickFormatter, Range1d 
 
testData = pd.Series(np.random.rand(10), index=pd.date_range('2016-01-01', periods=10) 
counts, bins = np.histogram(testData, bins=5) 
 
 
histAndLine = figure(x_axis_type='datetime') 
 
f = ['%Y-%m-%d'] 
histAndLine.xaxis.formatter = DatetimeTickFormatter(years=f, months=f, days=f) 
histAndLine.extra_x_ranges = {'Counts': Range1d(0, max(counts)+1)} 
histAndLine.add_layout(LinearAxis(x_range_name='Counts'), 'above') 
 
histAndLine.line(x=testData.index, y=testData) 
histAndLine.circle(x=testData.index, y=testData) 
 
histAndLine.hbar(y=bins[:-1], height=np.diff(bins), left=0, right=counts, x_range_name='Counts') 
 
show(histAndLine) 

这应该在一条线上产生一个条形图,线条和条形图占用了大部分图表空间,但我的线被挤压到右边(因为 2016 年的日期要大得多比 0 = 1970。

我是不是漏掉了什么?

请您参考如下方法:

数字自动使用的默认 DataRange1d 范围覆盖所有可用的字形。如果你想排除字形的一个子集,你可以明确:

l = histAndLine.line(x=testData.index, y=testData) 
c = histAndLine.circle(x=testData.index, y=testData) 
 
# only auto-range over the line and circle, not the bar 
histAndLine.x_range.renderers = [l,c]