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

如何在Bokeh折线图中绘制多条线并正确配置Y轴数据映射

问题:多线折线图的Y轴命名与数据调用问题

需要以年份为横轴,为数据集的3个类别各绘制一条折线构建多线折线图,目前依据数据集行名设置Y轴名称的配置方式有误,请问应如何正确定义命名以实现数据的准确调用?

用户提供的原始代码

from bokeh.plotting import figure
from bokeh.io import output_file, output_notebook, show
from bokeh.layouts import column
from bokeh.models import HoverTool, ColumnDataSource

data = pd.read_csv('saving.csv',dtype={'year': object})
data.head()

data['financial_year']=pd.to_datetime(data['financial_year'])

p.line(x= data.financial_year, y = data.rent)
p.line(x= data.financial_year, y = data.entertainment)

show(p)

# create a new plot with a title and axis labels
p = figure(title="Monthly expenditure", x_axis_type='datetime', x_axis_label="financial year", y_axis_label="expenses")

# add a line renderer with legend and line thickness
p.line(x, y, legend_label="expenses", line_width=2)

# Plot date along the x axis and price along the y axis
p.line(data['financial_year'], data['rent'], line_color='green')
p.line(data['financial_year'], data['entertainment'], line_color='blue')

# show the results
show(p)

数据集预览

数据集


解决方案

问题分析

原代码存在几个核心问题:

  1. 先调用p.line但未提前初始化figure对象,会触发报错;
  2. 存在未定义的x、y变量,导致代码无法执行;
  3. 未处理数据集中的第三个类别(餐饮支出);
  4. 数据调用方式不规范,容易出现列名匹配错误。

修正后的完整代码

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

# 读取数据集并转换日期格式
data = pd.read_csv('saving.csv')
data['financial_year'] = pd.to_datetime(data['financial_year'])

# 用ColumnDataSource统一管理数据,规范调用方式
source = ColumnDataSource(data={
    'year': data['financial_year'],
    'rent': data['rent'],
    'entertainment': data['entertainment'],
    'food': data['food']  # 对应数据集中的第三个支出类别
})

# 初始化绘图对象,设置标题与轴标签
p = figure(
    title="年度支出趋势",
    x_axis_type='datetime',
    x_axis_label="财年",
    y_axis_label="支出金额",
    tools="pan,box_zoom,reset,hover"
)

# 绘制三条折线,分别对应三个支出类别
p.line(
    x='year', y='rent', source=source,
    line_color='green', line_width=2, legend_label='房租'
)
p.line(
    x='year', y='entertainment', source=source,
    line_color='blue', line_width=2, legend_label='娱乐'
)
p.line(
    x='year', y='food', source=source,
    line_color='red', line_width=2, legend_label='餐饮'
)

# 配置悬浮提示,显示详细数据
hover = p.select_one(HoverTool)
hover.tooltips = [
    ("财年", "@year{%Y}"),
    ("房租", "@rent"),
    ("娱乐", "@entertainment"),
    ("餐饮", "@food")
]
hover.formatters = {'@year': 'datetime'}

# 调整图例位置,避免遮挡图表
p.legend.location = "top_left"

# 展示图表
show(p)

关键要点说明

  1. 规范数据调用:使用ColumnDataSource将所有需要的列统一包装,绘图时直接通过列名字符串调用,既避免了直接引用DataFrame列的潜在错误,也符合Bokeh的最佳实践;
  2. 正确设置轴标签:在初始化figure时通过y_axis_label参数直接定义Y轴名称,确保与数据含义匹配;
  3. 多折线清晰区分:为每个类别单独设置折线颜色、宽度和图例,明确对应关系,避免混淆;
  4. 修复执行顺序问题:确保先初始化figure对象,再进行折线绘制,避免报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 09:10:06