如何使用Bokeh绘制二维数组?求类似Matplotlib imshow()的示例
使用Bokeh实现类似Matplotlib imshow()的二维数组可视化
当然可以!Bokeh里没有直接对应imshow()的函数,但用image组件完全能实现相同的效果,还能生成交互式的图表。下面是针对你给出的二维数组的完整示例:
import numpy as np from bokeh.plotting import figure, show from bokeh.models import ColorBar, LinearColorMapper # 定义你的二维数组 a = np.array([[1, 2], [3, 4]]) # 创建颜色映射器,选用和Matplotlib默认类似的Viridis色系 color_mapper = LinearColorMapper(palette="Viridis256", low=a.min(), high=a.max()) # 初始化绘图对象,设置坐标轴范围匹配数组的行列尺寸 p = figure( x_range=(0, a.shape[1]), y_range=(0, a.shape[0]), toolbar_location=None, # 隐藏工具栏(可选) tools="", title="Bokeh 二维数组可视化" ) # 添加图像渲染层:注意Bokeh要求image参数是数组列表,x/y是图像左下角坐标,dw/dh是宽高 p.image( image=[a], x=0, y=0, dw=a.shape[1], dh=a.shape[0], color_mapper=color_mapper ) # 添加颜色条,和imshow的颜色条功能一致 color_bar = ColorBar(color_mapper=color_mapper, location=(0, 0)) p.add_layout(color_bar, 'right') # 显示交互式图表 show(p)
关键细节说明:
- 图像参数设置:Bokeh的
image函数需要将数组放在列表中(image=[a]),这样支持同时渲染多个图像;x和y指定图像左下角的坐标,这里设为(0,0)对应数组的起始位置;dw和dh分别对应数组的列数和行数,确保图像尺寸匹配数组。 - 颜色映射:
LinearColorMapper负责将数组数值映射到颜色,palette参数可以替换成任意Bokeh支持的色系,比如"Plasma256"、"Inferno256",加_r后缀可以反转色系(如"Viridis256_r")。 - 交互性:如果保留工具栏(去掉
toolbar_location=None),还能缩放、平移图像,这是Bokeh比Matplotlib静态图更灵活的地方。
内容的提问来源于stack exchange,提问作者Soerendip
相关产品推荐
相关产品推荐

