Skip to main content
 首页 » 编程设计

python之在 Bokeh 刻度标签中插入换行符

2024年12月31日10xiaohuochai

我想在 Bokeh 中创建多行格式的刻度标签。 在常规 Python 中以这种方式格式化很简单,例如

'{} \n{}'.format('Category', 'Percentage') 

将打印

Percentage 

在我的代码中,我这样做是为了创建我的绘图数据:

ds = OrderedDict(sorted(subdict.items(), key=lambda v: v[1], reverse=True)) 
ks = [i+', {:}% '.format(str(round(j/sum(ds.values())*100, None))) for i, j in ds.items()] 
data = {'kz': ks, 'vals':list(ds.values())} 
source = ColumnDataSource(data=data) 

如果我在上面代码中的 format() 语句中插入换行符(例如 ',\n {:}%'),bokeh 会忽略它。

bokeh.models.PrintfTickFormatter 似乎没有提供换行符,

和

bokeh.models.CategoricalTickFormatter 什么都不做(方法是“通过”)

隐藏在 Bokeh 文档中

https://docs.bokeh.org/en/latest/docs/reference/models/formatters.html

DatetimeTickFormatter 是声明:

%n A newline character. Bokeh text does not currently support newline characters.

我只能假设这适用于 Bokeh 中的所有和任何文本。

任何人都可以确认、更正或提供解决方法吗?

nb 在我的用例中,图表仅导出为 png。

请您参考如下方法:

从 Bokeh 2.3 开始,多行刻度标签仅适用于分类因素:

from bokeh.plotting import figure, show 
 
factors = [ 
    "a very long label \n that needs a break", 
    "a short label", 
] 
 
x = [50, 40] 
 
p = figure(y_range=factors) 
p.circle(x, factors, size=25, fill_color="orange", line_color="green", line_width=3) 
 
show(p)