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

如何用Bokeh创建4个以上带交互式图例的堆叠折线图?

解决Bokeh堆叠折线图数量限制问题

核心原因

你遇到的问题大概率是原代码存在硬编码限制——比如只手动创建了4个折线实例、仅配置了4个图例项,或者堆叠逻辑没有遍历所有新增的系列数据,导致第五个"AAP"系列没有被正确添加到图表和图例中。

扩展到20个折线图的实现方法

1. 动态生成数据与数据源

确保所有系列数据都被纳入统一的ColumnDataSource,避免手动硬编码列名:

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, LegendItem
import pandas as pd

# 模拟20个系列的测试数据
data = {"x": list(range(10))}
for idx in range(20):
    series_name = f"series_{idx}"
    data[series_name] = [x + idx for x in data["x"]]

df = pd.DataFrame(data)
source = ColumnDataSource(df)

2. 循环创建堆叠折线与图例

不要手动逐个创建折线,而是遍历所有系列名称动态生成,并绑定对应的图例项:

p = figure(x_axis_label="X轴", y_axis_label="Y轴", width=800, height=500)

# 提取所有系列名称(排除x轴列)
series_names = [col for col in df.columns if col != "x"]
renderers = []

# 循环生成每个折线图
for name in series_names:
    renderer = p.line("x", name, source=source, legend_label=name, line_width=2)
    renderers.append(renderer)

# 动态配置交互式图例(支持点击隐藏)
p.legend.items = [LegendItem(label=name, renderers=[r]) for name, r in zip(series_names, renderers)]
p.legend.click_policy = "hide"

3. 优化图例显示(可选)

20个系列的图例会较长,可通过以下配置提升体验:

p.legend.location = "top_left"
p.legend.max_height = 300  # 设置最大高度,超出部分自动滚动
p.legend.spacing = 3
p.legend.label_text_font_size = "8pt"

4. 验证与运行

执行show(p)即可看到包含20个可交互堆叠折线的图表,点击图例项可单独隐藏对应折线。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:30:43