初学Bokeh:格式化坐标轴刻度【19】跬步

发布时间 2023-11-03 11:36:25作者: ohfaint

格式化坐标轴刻度

可以使用 Bokeh 的 TickFormatter 对象来格式化显示在坐标轴旁的文本。

例如,使用这些格式话可以在 Y 轴上显示货币符号:

fig19-1

要在 Y 轴上显示美元金额而不只是数字,请使用 NumeralTickFormatter:

  1. 从 bokeh.models 中导入 NumeralTickFormatter:
    from bokeh.models import NumeralTickFormatter
  1. 使用 figure() 函数创建绘图后,将 NumeralTickFormatter 赋值给绘图的 yaxis 的 formatter 属性:
    p.yaxis[0].formatter = NumeralTickFormatter(format="$0.00")

NumeralTickFormatter 支持不同的格式,包括用"$0.00 "生成"$7.42 "等值。

最终的代码如下:

# 引入库
from bokeh.models import NumeralTickFormatter
from bokeh.plotting import figure, show

# prepare some data
# 定义显示文件
x = [1, 2, 3, 4, 5]
y = [4, 5, 5, 7, 2]

# create new plot
# 创建图像
p = figure(
    title="Tick formatter example", # 标题
    sizing_mode="stretch_width",    # 自动宽度拉伸
    max_width=500,  # 最大宽度
    height=250, # 高度
)

# format axes ticks
# 使用NumeralTickFormatter定义y轴的formatter属性
p.yaxis[0].formatter = NumeralTickFormatter(format="$0.00")

# add renderers
# 添加圆对象和线对象
p.circle(x, y, size=8)  # 大小8
p.line(x, y, color="navy", line_width=1)    # 颜色navy,线宽1

# show the results
# 显示图
show(p)

fig19-2