2026/9/14 2:44:28

Bokeh 绘图定制实战:主题、尺寸、坐标轴、网格与工具栏配置完全指南

Bokeh 绘图定制实战:主题、尺寸、坐标轴、网格与工具栏配置完全指南 Bokeh 绘图定制实战主题、尺寸、坐标轴、网格与工具栏配置完全指南【免费下载链接】bokehInteractive Data Visualization in the browser, from Python项目地址: https://gitcode.com/GitHub_Trending/bo/bokeh本篇技术指南基于 Bokeh 官方入门系列文档 first_steps_4.rst 展开围绕“定制整个绘图外观”这一主题系统讲解主题Themes、绘图尺寸与响应式布局、坐标轴外观与类型、网格样式、工具栏配置以及 Hover 提示Tooltips六大板块。读完本文后你将能够用十余行 Python 代码为图表套用深色主题、自定义坐标轴刻度格式、切换对数轴与日期时间轴、调整网格与背景颜色并精确控制工具栏中可用的交互工具直接产出可运行、可复用的定制绘图方案。文档配套的全部示例代码均可在仓库 docs/bokeh/source/docs/first_steps/examples/ 目录下找到。使用主题Themes快速改变绘图外观主题Theme是 Bokeh 提供的一组预定义设计参数涵盖颜色、字体、线型等视觉要素。通过主题你可以用一行代码快速切换整套绘图的视觉风格而无需逐个修改属性。根据文档说明Bokeh 自带五个内置主题caliber、dark_minimal、light_minimal、night_sky和contrast。查看仓库中 src/bokeh/themes/init.py 的源码可以发现当前版本实际上还额外提供了carbon主题built_in_themes字典中共注册了六个主题CALIBER、CARBON、LIGHT_MINIMAL、DARK_MINIMAL、NIGHT_SKY、CONTRAST每个主题均以 JSON 配置的形式定义并统一封装为Theme对象未指定主题时使用的default主题则是一个空配置Theme(json{})。使用内置主题的方式很简单把主题名称字符串赋给当前文档document的theme属性即可。下面是最完整的示例代码对应仓库中的 first_steps_4_themes.pyfrom bokeh.io import curdoc from bokeh.plotting import figure, show # prepare some data x [1, 2, 3, 4, 5] y [4, 5, 5, 7, 2] # apply theme to current document curdoc().theme dark_minimal # create a plot p figure(sizing_modestretch_width, max_width500, height250) # add a renderer p.line(x, y) # show the results show(p)关键点在于curdoc().theme dark_minimal主题作用域是当前文档因此同一文档中创建的所有绘图都会统一继承该主题非常适合在多个图表间保持一致的设计语言。除了内置主题Bokeh 还支持自定义主题格式可以是 YAML 或 JSON。如果你需要在多个绘图甚至多个项目间复用同一套配色与字体规范可以参考用户指南中关于自定义主题的章节将主题定义成独立配置文件后再加载。调整绘图尺寸Resizing your plotBokeh 的Plot对象拥有一系列影响绘图外观的属性其中最基础的就是尺寸控制。设置宽度和高度在调用figure()函数时直接传入width和height参数即可指定绘图尺寸。完整示例见 first_steps_4_plot_size.pyfrom bokeh.plotting import figure, show # prepare some data x [1, 2, 3, 4, 5] y [4, 5, 5, 7, 2] # create a new plot with a specific size p figure( titlePlot sizing example, width350, height250, x_axis_labelx, y_axis_labely, ) # add scatter renderer p.scatter(x, y, fill_colorred, size15) # show the results show(p)这里width350, height250的单位是 CSS 像素直接决定了绘图在浏览器中的初始渲染大小。创建之后动态修改尺寸与之前教程中“修改已有 glyph 的设计”类似绘图尺寸也可以在创建完成后的任意时刻修改——直接为width和height属性重新赋值即可。完整示例见 first_steps_4_resize_plot.pyfrom bokeh.plotting import figure, show # prepare some data x [1, 2, 3, 4, 5] y [4, 5, 5, 7, 2] # create a new plot with a specific size p figure( titlePlot resizing example, width350, height250, x_axis_labelx, y_axis_labely, ) # change plot size p.width 450 p.height 150 # add scatter renderer p.scatter(x, y, fill_colorred, size15) # show the results show(p)示例中创建时的尺寸是 350×250随后通过p.width 450和p.height 150覆盖为新的尺寸。这一机制意味着你可以在运行时根据数据量、窗口状态或用户交互动态调整绘图大小。启用响应式尺寸responsive sizing固定像素尺寸无法适应不同的浏览器窗口或屏幕尺寸。要解决这个问题可以使用Plot的sizing_mode属性让绘图自动适配其所在容器。完整示例见 first_steps_4_plot_size_responsive.pyfrom bokeh.plotting import figure, show # prepare some data x [1, 2, 3, 4, 5] y [4, 5, 5, 7, 2] # create a new plot with responsive width p figure( titlePlot responsive sizing example, sizing_modestretch_width, height250, x_axis_labelx, y_axis_labely, ) # add scatter renderer p.scatter(x, y, fill_colorred, size15) # show the results show(p)stretch_width表示绘图宽度会跟随浏览器/容器宽度自动拉伸同时保持height固定不变。Bokeh 还支持stretch_height、stretch_both、scale_width、scale_height、scale_both、fixed、inherit等模式分别对应不同的自适应策略可根据布局需求如配合网格布局使用灵活选用。定制坐标轴Customizing axes坐标轴是绘图信息传达的核心载体Bokeh 允许你通过属性定制坐标轴的标签、数字格式、颜色和布局还可以改变坐标轴类型对数轴、日期时间轴以及手动定义数值范围。定制坐标轴外观坐标轴可定制的外观选项主要包括为坐标轴设置标签axis label为坐标轴显示的数字定制样式字体、颜色、方向等为坐标轴本身定义颜色及其他布局属性线宽、刻度线等完整的综合示例见 first_steps_4_axes_customizing.pyfrom bokeh.plotting import figure, show # prepare some data x [1, 2, 3, 4, 5] y [4, 5, 5, 7, 2] # create a plot p figure( titleCustomized axes example, sizing_modestretch_width, max_width500, height350, ) # add a renderer p.scatter(x, y, size10) # change some things about the x-axis p.xaxis.axis_label Temp p.xaxis.axis_line_width 3 p.xaxis.axis_line_color red # change some things about the y-axis p.yaxis.axis_label Pressure p.yaxis.major_label_text_color orange p.yaxis.major_label_orientation vertical # change things on all axes p.axis.minor_tick_in -3 p.axis.minor_tick_out 6 # show the results show(p)这个示例展示了三种访问级别p.xaxis/p.yaxis用于修改单个坐标轴如轴标签axis_label、轴线宽axis_line_width、轴线颜色axis_line_color、主刻度文字颜色major_label_text_color、主刻度文字方向major_label_orientation而p.axis则同时作用于所有坐标轴这里把次要刻度的内外长度分别设为-3和6。major_label_orientation vertical在刻度文字较长、水平排列会重叠时尤其实用。手动定义坐标轴范围绘制坐标轴时Bokeh 会根据数据自动计算每个轴需要覆盖的范围。例如 y 轴数据值在 2 到 17 之间时Bokeh 会自动生成略低于 2、略高于 17 的 y 轴范围。如需手动控制范围可以在调用figure()函数时传入x_range或y_range。完整示例见 first_steps_4_plot_axis_ranges.pyfrom bokeh.plotting import figure, show # prepare some data x [1, 2, 3, 4, 5] y [4, 5, 5, 7, 2] # create a new plot with responsive width p figure( y_range(0, 25), titleAxis range example, sizing_modestretch_width, max_width500, height250, ) # add scatter renderer with additional arguments p.scatter(x, y, size8) # show the results show(p)y_range(0, 25)以二元组形式指定 y 轴的上下界即使数据点的最大值只有 7坐标轴也会固定绘制 0 到 25 的范围。手动定义范围适用于需要对齐多个子图、突出特定数据区间或留出额外空间的场景。格式化坐标轴刻度Bokeh 提供TickFormatter对象族来格式化坐标轴旁显示的文字最典型的应用是在 y 轴上显示货币符号。实现这一效果需要用到 bokeh.models 模块中的NumeralTickFormatter。首先从bokeh.models导入from bokeh.models import NumeralTickFormatter然后在用figure()创建绘图之后把NumeralTickFormatter赋给 y 轴的formatter属性p.yaxis[0].formatter NumeralTickFormatter(format$0.00)NumeralTickFormatter支持多种格式例如$0.00会生成$7.42这样的美元金额形式。完整的可运行示例见 first_steps_4_tick_formatter.pyfrom 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( titleTick formatter example, sizing_modestretch_width, max_width500, height250, ) # format axes ticks p.yaxis[0].formatter NumeralTickFormatter(format$0.00) # add renderers p.scatter(x, y, size8) p.line(x, y, colornavy, line_width1) # show the results show(p)Bokeh 的bokeh.models.formatters模块中还提供了其他刻度格式化器如百分比、科学计数法等可以根据展示需求选择。关于刻度格式化的更多细节可参考用户指南中关于坐标轴刻度标签格式的章节。启用对数坐标轴当数据跨越多个数量级时线性坐标轴往往无法有效展示细节。此时可以把y_axis_type或x_axis_type设为log切换为对数轴。完整示例见 first_steps_4_axes_logarithmic.pyfrom bokeh.plotting import figure, show # prepare some data x [0.1, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0] y0 [i**2 for i in x] y1 [10**i for i in x] y2 [10**(i**2) for i in x] # create a new plot with a logarithmic axis type p figure( titleLogarithmic axis example, sizing_modestretch_width, height300, max_width500, y_axis_typelog, y_range[0.001, 10 ** 11], x_axis_labelsections, y_axis_labelparticles, ) # add some renderers p.line(x, x, legend_labelyx) p.scatter(x, x, legend_labelyx, fill_colorwhite, size8) p.line(x, y0, legend_labelyx^2, line_width3) p.line(x, y1, legend_labely10^x, line_colorred) p.scatter(x, y1, legend_labely10^x, fill_colorred, line_colorred, size6) p.line(x, y2, legend_labely10^x^2, line_colororange, line_dash4 4) # show the results show(p)示例中数据y1 10^x和y2 10^(x^2)增长极快配合y_axis_typelog以及y_range[0.001, 10**11]的对数范围才能在同一个坐标系里同时看清三条曲线。注意对数轴要求数据必须为正数大于 0否则对应刻度无法在数轴上表示。启用日期时间坐标轴把x_axis_type或y_axis_type设为datetime即可在坐标轴上显示日期/时间信息Bokeh 会自动创建DatetimeAxis。若要格式化日期时间轴的刻度则使用DatetimeTickFormatter。完整示例见 first_steps_4_datetime_axis.pyimport random from datetime import datetime, timedelta from bokeh.models import DatetimeTickFormatter, NumeralTickFormatter from bokeh.plotting import figure, show # generate list of dates (todays date in subsequent weeks) dates [(datetime.now() timedelta(day * 7)) for day in range(0, 26)] # generate 25 random data points y random.sample(range(0, 100), 26) # create new plot p figure( titledatetime axis example, x_axis_typedatetime, sizing_modestretch_width, max_width500, height250, ) # add renderers p.scatter(dates, y, size8) p.line(dates, y, colornavy, line_width1) # format axes ticks p.yaxis[0].formatter NumeralTickFormatter(format$0.00) p.xaxis[0].formatter DatetimeTickFormatter(months%b %Y) # show the results show(p)这个示例综合展示了两种坐标轴的组合用法x 轴为日期时间轴数据由datetime.now()加上以周为步长的timedelta生成共 26 个时间点y 轴使用货币格式。DatetimeTickFormatter(months%b %Y)指定了以“月份 年份”如 Jan 2026的形式格式化月刻度%b和%Y是标准的strftime风格占位符。定制网格Customizing the grid网格线帮助读者对齐和读数Bokeh 允许通过xgrid、ygrid和grid这三个属性分组来定制网格外观分别对应 x 方向网格、y 方向网格以及全部网格。样式化网格线通过设置各种grid_line属性可以改变网格水平线和垂直线的外观。完整示例见 first_steps_4_grid_lines.pyfrom bokeh.plotting import figure, show # prepare some data x [1, 2, 3, 4, 5] y [4, 5, 5, 7, 2] # create a plot p figure( titleCustomized grid lines example, sizing_modestretch_width, max_width500, height250, ) # add a renderer p.line(x, y, line_colorgreen, line_width2) # change things only on the x-grid p.xgrid.grid_line_color red # change things only on the y-grid p.ygrid.grid_line_alpha 0.8 p.ygrid.grid_line_dash [6, 4] # show the results show(p)这里对 x 网格设置了红色网格线p.xgrid.grid_line_color red对 y 网格设置了透明度 0.8grid_line_alpha以及[6, 4]的虚线模式grid_line_dash表示 6 像素实线加 4 像素空白交替。网格线相关的属性通常还包括grid_line_width、grid_line_dash_offset等且网格同样支持主刻度网格与次要刻度网格minor lines的分别定制。使用 bands 和 bounds 提升可读性除了网格线Bokeh 还支持网格的“带状填充”bands和“边界限制”bounds两种特性它们都属于你在第 3 篇入门指南中学过的 annotation标注的延伸。完整示例见 first_steps_4_bands.pyfrom bokeh.plotting import figure, show # prepare some data x [1, 2, 3, 4, 5] y [4, 5, 5, 7, 2] # create a plot p figure( titleBands and bonds example, sizing_modestretch_width, max_width500, height250, ) # add a renderer p.line(x, y, line_colorgreen, line_width2) # add bands to the y-grid p.ygrid.band_fill_color olive p.ygrid.band_fill_alpha 0.1 # define vertical bonds p.xgrid.bounds (2, 4) # show the results show(p)Bands色带p.ygrid.band_fill_color olive配合band_fill_alpha 0.1会在 y 网格的相邻刻度之间交替填充淡橄榄色带形成类似“斑马纹”的视觉引导方便逐行读数。Bounds边界p.xgrid.bounds (2, 4)将 x 网格的绘制范围限制在 2 到 4 之间网格线只在指定区间内出现可用于突出关注的数值区域。设置背景颜色Bokeh 支持多种定义颜色的方式文档中列举的四种形式如下使用命名 CSS 颜色例如firebrick使用十六进制值前缀#例如#00ff00使用 RGB 三元组例如(100, 100, 255)使用 RGBA 四元组例如(100, 100, 255, 0.5)最后一个分量是透明度要改变绘图元素所在画布平面plot plane的外观使用Plot对象的各种fill_color属性。完整示例见 first_steps_4_background.pyfrom bokeh.plotting import figure, show # prepare some data x [1, 2, 3, 4, 5] y [4, 5, 5, 7, 2] # create a plot p figure( titleBackground colors example, sizing_modestretch_width, max_width500, height250, ) # add a renderer p.line(x, y, line_colorgreen, line_width2) # change the fill colors p.background_fill_color (204, 255, 255) p.border_fill_color (102, 204, 255) p.outline_line_color (0, 0, 255) # show the results show(p)三个属性分别控制不同的区域background_fill_color绘图内部背景色数据区border_fill_color绘图边框区域背景色包含坐标轴标签、标题所在的边缘区域outline_line_color绘图轮廓线颜色示例统一使用了 RGB 三元组形式定义颜色与命名颜色、十六进制值可以混用。定制工具栏Customizing the toolbarBokeh 自带功能强大的工具栏用于探索绘图数据——包括缩放、平移、重置等交互工具。你可以控制工具栏的位置、可见性以及其中包含的工具集合。定位工具栏通过Plot.toolbar_location属性定义工具栏位置可选值为above、below、left、right。在创建绘图时直接传入p figure(titleToolbar positioning example, toolbar_locationbelow)也可以在创建后任意时刻修改p.toolbar_location below完整示例见 first_steps_4_toolbar.py效果为把工具栏移动到绘图底部。停用与隐藏工具栏要把工具栏完全停用将toolbar_location设为Nonep.toolbar_location None要让工具栏自动隐藏把Toolbar.autohide设为True。完整示例见 first_steps_4_toolbar_autohide.pyfrom bokeh.plotting import figure, show # prepare some data x [1, 2, 3, 4, 5] y [4, 5, 5, 7, 2] # create a plot p figure( titleToolbar autohide example, sizing_modestretch_width, max_width500, height250, ) # activate toolbar autohide p.toolbar.autohide True # add a renderer p.line(x, y) # show the results show(p)启用autohide后工具栏默认隐藏只有当鼠标进入绘图区域或点击绘图区域时才显示从而最大化绘图的可视空间。类似地可以通过Toolbar.logo属性移除工具栏上的 Bokeh 徽标p.toolbar.logo None定制可用工具你可以自定义工具栏中显示的交互工具。首先需要从bokeh.models.tools导入需要的工具类例如from bokeh.models.tools import BoxZoomTool, ResetTool然后在创建绘图时通过tools参数传入工具列表例如只启用框选缩放和重置两个工具p figure(tools [BoxZoomTool(), ResetTool()])完整示例见 first_steps_4_tools.py该示例运行后工具栏中只有 box zoom 和 reset 两个工具可用。如需在创建绘图之后动态增删工具可以使用Plot.add_tools和Plot.remove_tools方法。同时每个工具都有各自的属性来控制其行为方式。例如PanTool可以限制只能水平或垂直平移默认允许双向平移。综合示例见 first_steps_4_add_tools.pyfrom bokeh.models import BoxZoomTool, PanTool, ResetTool from bokeh.plotting import figure, show # prepare some data x [1, 2, 3, 4, 5] y [4, 5, 5, 7, 2] # create a plot p figure( titleModifying tools example, tools[BoxZoomTool(), ResetTool()], sizing_modestretch_width, max_width500, height250, ) # add an additional pan tool # only vertical panning is allowed p.add_tools(PanTool(dimensionswidth)) # add a renderer p.scatter(x, y, size10) # show the results show(p)这个示例先通过tools[BoxZoomTool(), ResetTool()]在创建时限定两个工具随后用p.add_tools(PanTool(dimensionswidth))追加一个只允许水平方向平移的PanTooldimensionswidth表示平移被限制在宽度方向上。最终工具栏中共有三个工具可用。bokeh.models.tools模块中还有ZoomInTool、SaveTool、WheelZoomTool、CrosshairTool、HoverTool等众多工具每个工具都有对应的属性可精细调节行为。添加 Tooltips悬浮提示Tooltips 是当鼠标悬停或点击数据点时出现的小窗口用于展示该数据点的详细信息。它基于HoverTool实现而 hover 工具本身是 Bokeh 工具栏的组成部分。启用 Tooltips 最快的方式分三步从bokeh.models.tools导入HoverTool类在调用figure()函数时把HoverTool()加入tools参数列表在调用figure()函数时传入tooltips参数。tooltips参数接受一个带有特殊语法的字符串。使用符号引用数据源中字段的名称——例如x和y浏览器显示 tooltip 时Bokeh 会用列表x和y中的真实数据替换这两个占位符。完整示例见 first_steps_4_tooltips.pyfrom bokeh.models import HoverTool from bokeh.plotting import figure, show # prepare some data x [1, 2, 3, 4, 5] y [4, 5, 5, 7, 2] p figure( y_range(0, 10), toolbar_locationNone, tools[HoverTool()], tooltipsData point x has the value y, sizing_modestretch_width, max_width500, height250, ) # add renderers p.scatter(x, y, size10) p.line(x, y, line_width2) # show the results show(p)核心是tooltipsData point x has the value y这一行悬停到某个数据点时x和y会被替换为该点的实际坐标值例如显示 Data point 3 has the value 5。示例同时把toolbar_location设为None以隐藏工具栏让 hover 交互成为唯一的探索方式。HoverTool还支持更复杂的用法例如$index、$x、$y等特殊字段以及富 HTML 格式的 tooltip 内容可以参考用户指南中关于 hover tool 的进阶章节。总结至此你已经掌握了 Bokeh 绘图整体定制的主要手段用主题一键切换视觉风格用width/height/sizing_mode精确控制尺寸与响应式行为用坐标轴属性、范围、NumeralTickFormatter/DatetimeTickFormatter、对数轴与日期时间轴定制坐标系统用网格线、bands/bounds 与背景颜色优化可读性用toolbar_location、autohide与add_tools/remove_tools掌控工具栏并用HoverTool与tooltips为数据点添加交互提示。本文所有示例的完整源码都保存在仓库的 docs/bokeh/source/docs/first_steps/examples/ 目录下可以直接复制运行并在此基础上改造快速应用到你的实际可视化项目中。【免费下载链接】bokehInteractive Data Visualization in the browser, from Python项目地址: https://gitcode.com/GitHub_Trending/bo/bokeh创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考