如何在 Bokeh 中添加颜色条


在 Python 中,Bokeh 是一个功能强大的数据可视化库,它超越了传统的绘图方式。它遵循独特的“图形语法”架构,允许开发者通过管理图形元素来构建交互式可视化。Bokeh 图表通过与 Pandas、NumPy 和 SciPy 的无缝集成,使您的数据栩栩如生。

什么是颜色条?

颜色条是一种可视化工具,使用颜色来表示连续变量,例如热图。颜色条的主要目的是让用户了解数据值与用于表示它们的颜色之间的关系。让我们学习如何在 Bokeh 中添加颜色条。

在 Bokeh 中添加颜色条的分步过程

步骤 1:导入必要的库

我们将导入 numpy 和 bokeh.plotting、bokeh.models 以及 bokeh.io 库来创建基本图表。如果您使用 Google Collab 或 Jupyter Notebook,则必须使用 bokeh.io 和 output_notebook 函数来显示图表。

示例

# import NumPy library
import numpy as np

# from bokeh.plot import figure and show for creating and displaying plot
from bokeh.plotting import figure, show

# from bokeh.models import LinearColorMapper and ColorBar to generate a color bar
from bokeh.models import LinearColorMapper, ColorBar
from bokeh.io import output_notebook
output_notebook()

步骤 2:生成或导入数据以创建图表

我们可以使用 NumPy 的 random.rand 函数生成所需长度的随机数组

示例

# Generate a random array of size 10 to plot
data = np.random.rand(10,10)

步骤 3:为颜色条确定调色板

#使用线性颜色映射函数选择颜色条的调色板

#指定颜色图的低值和高值以确定值的范围。

color = LinearColorMapper(palette = "Magma256", low = 0, high = 1)

在这里,我们使用 palette 属性确定了颜色条的调色板。我们使用了 Magma256 作为调色板,但您可以随时尝试其他调色板,例如 Greys256、Inferno256、Plasma256、Viridis256、Cividis256、Turbo256

步骤 4:定义 X 轴和 Y 轴的限制

# Defining X axis and Y axis limits
plot = figure(x_range = (0, 1), y_range = (0,1))

步骤 5:生成图表的图像

#Add the plot's width and height, scalar data, and a color mapper to generate a plot image
plot.image(image = [data], color_mapper = color, dh = [1], dw = [1], x = [0], y = [0])

步骤 6:创建颜色条

使用 ColorBar 函数创建颜色条。

# Creating the color bar and setting the color bar position at (0,0)
color_bar = ColorBar(color_mapper = color, location = (0,0))

步骤 7:放置颜色条并显示图表

请注意,在 Bokeh 中,您可以将颜色条放置在任何位置,例如右侧、左侧、上方或下方。因此,在代码中必须指定颜色条的位置。

# Incorporating the color bar on the right
plot.add_layout(color_bar, 'right')
# display the plot
show(plot)

输出

结论

颜色条是关联数据之间关系的有用工具之一。Bokeh 还提供了更多工具来使您的图表具有交互性,例如颜色选择器、添加日期、表格等。

更新于: 2023年8月29日

274 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.