You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Bokeh为一组线条应用颜色映射(附Matplotlib参考)

How to Replicate Matplotlib Color-Mapped Lines in Bokeh

Got it! Converting your matplotlib color-mapped line plot to Bokeh is straightforward—here's how you can replicate that exact functionality step by step:

Key Concepts to Translate

In matplotlib, you use cm(colors_l[i]) to map a numerical value to a color from the Jet colormap. In Bokeh, we'll use LinearColorMapper to handle this same mapping, or directly index into the Jet palette if you prefer.

Full Code Example

First, make sure you have the necessary imports, then adapt your logic to Bokeh's API:

import numpy as np
from bokeh.plotting import figure, show
from bokeh.models import LinearColorMapper
from bokeh.palettes import Jet256

# Assume your data and state_means variables are already defined
step = 15
xi = np.linspace(data[data.columns[0]].min(), data[data.columns[0]].max(), 2)
colors_l = np.linspace(0.1, 1, len(state_means[::step]))

# 1. Set up the color mapper (equivalent to plt.cm.get_cmap('jet'))
color_mapper = LinearColorMapper(palette="Jet256", low=0.1, high=1.0)

# 2. Create your Bokeh figure
p = figure(title="Color-Mapped Lines with Bokeh", x_axis_label=data.columns[0], y_axis_label="Y Value")

# 3. Loop through your state means and plot each line
for i, beta in enumerate(state_means[::step]):
    # Calculate the line's y-values (same as your original code)
    y_values = beta[0] * xi + beta[1]
    # Get the mapped color for this line (equivalent to cm(colors_l[i]))
    line_color = color_mapper.to_rgba(colors_l[i])
    # Plot the line with matching alpha and line width
    p.line(xi, y_values, alpha=0.2, line_width=1, color=line_color)

# Show the plot
show(p)

Alternative: Direct Palette Indexing

If you'd rather work directly with the palette list (no mapper), you can normalize your colors_l values to index into the Jet256 palette:

palette = Jet256
# Normalize colors_l to 0-1 range (since your values go from 0.1 to 1)
normalized_colors = (colors_l - 0.1) / (1.0 - 0.1)
# Convert to integer indices for the palette
color_indices = (normalized_colors * (len(palette) - 1)).astype(int)

# Then in your loop:
line_color = palette[color_indices[i]]

Notes

  • Bokeh's Jet256 palette matches matplotlib's jet colormap closely, with 256 distinct colors.
  • The to_rgba method returns an RGBA tuple (e.g., (255, 0, 0, 1.0)), which Bokeh accepts directly as a color value.
  • Adjust the low and high parameters of LinearColorMapper if your colors_l range changes—this ensures your values map correctly across the full palette.

内容的提问来源于stack exchange,提问作者Parikshit Bhinde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:34:04