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

如何使用Bokeh 2.4.3绘制Pandas DataFrame指定多列(multiline已弃用)

使用Bokeh绘制Pandas DataFrame多列折线的正确方法

p.line()无法直接接收多列DataFrame作为参数,因为它一次仅支持一组x-y数据。以下是两种可行的解决方式:

方法一:循环遍历指定列,逐个添加折线

这种方式简单直观,适合列数不多的场景:

import pandas as pd
import numpy as np
from bokeh.plotting import figure, show

df = pd.DataFrame(np.random.randint(0,100,size=(100, 5)), columns=list('ABCDF'))
p = figure(height=300, width=300)

# 定义要绘制的目标列
target_cols = ['A', 'C', 'F']
x = df.index

# 循环为每列添加折线
for col in target_cols:
    p.line(x, df[col], legend_label=col)

# 设置图例位置
p.legend.location = "top_left"
show(p)

方法二:转换数据格式后使用multi_line

如果需要绘制的列较多,可以先将宽格式数据转为长格式,再用multi_line批量绘制:

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

df = pd.DataFrame(np.random.randint(0,100,size=(100, 5)), columns=list('ABCDF'))
target_cols = ['A', 'C', 'F']

# 将数据转为长格式,保留索引作为x轴
melted_df = df.reset_index().melt(id_vars='index', value_vars=target_cols, var_name='column', value_name='value')

# 整理成multi_line所需的x、y列表格式
x_list = [melted_df[melted_df['column'] == col]['index'].tolist() for col in target_cols]
y_list = [melted_df[melted_df['column'] == col]['value'].tolist() for col in target_cols]

# 创建数据源
source = ColumnDataSource(data=dict(
    xs=x_list,
    ys=y_list,
    labels=target_cols
))

p = figure(height=300, width=300)
# 使用multi_line绘制多条折线,绑定图例
p.multi_line(xs='xs', ys='ys', legend_field='labels', source=source)

p.legend.location = "top_left"
show(p)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 15:43:25