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

Python3.9下用pandas_bokeh绘折线图遇AttributeError,求解决及替代库

解决pandas_bokeh绘图报错及交互式绘图替代方案

一、解决AttributeError: unexpected attribute 'plot_width' to figure报错

这个报错的核心原因是bokeh 3.x版本后将plot_width参数更名为width,旧版本的pandas_bokeh仍在使用过时的参数名,和matplotlib无冲突。可通过以下方式解决:

1. 手动指定兼容参数

调用plot_bokeh时显式传入width参数替代默认的plot_width:

import pandas_bokeh
pandas_bokeh.output_notebook()

# 显式指定width/height参数,覆盖库默认的过时参数
bucketed_df.plot_bokeh(kind='line', width=800, height=400)

2. 调整版本兼容性

  • 降级bokeh到3.0以下版本,适配旧版pandas_bokeh:
pip install bokeh<3.0
  • 升级pandas_bokeh到最新版本,部分新版本已适配bokeh 3.x参数变化:
pip install --upgrade pandas_bokeh

二、更优的交互式绘图替代库

1. Plotly Express

极简语法,原生支持pandas DataFrame,内置丰富交互功能(缩放、hover提示、图表导出等),适合快速出图:

import plotly.express as px
# 直接传入DataFrame生成折线图
fig = px.line(bucketed_df)
# 在Notebook中渲染图表
fig.show()

2. Altair

基于声明式语法的可视化库,遵循Vega-Lite规范,适合构建规范、可复用的可视化,与pandas兼容性好:

import altair as alt
# 将索引转为列,适配Altair输入格式
chart_data = bucketed_df.reset_index()
# 创建交互式折线图
alt.Chart(chart_data).mark_line().encode(
    x='index',  # 替换为你的X轴列名
    y=alt.Y(alt.repeat("column"), type='quantitative'),
    color=alt.repeat("column")
).repeat(
    column=bucketed_df.columns.tolist()
).interactive()

3. Bokeh原生库

如果需要高度定制化的交互式图表,直接使用Bokeh原生API,灵活性拉满:

from bokeh.plotting import figure, show
from bokeh.io import output_notebook

output_notebook()
# 初始化画布
p = figure(width=800, height=400, x_axis_label='X轴', y_axis_label='Y轴')
# 遍历DataFrame列绘制折线
for col_name, col_data in bucketed_df.items():
    p.line(bucketed_df.index, col_data, legend_label=col_name, line_width=2)
# 添加图例点击隐藏功能
p.legend.click_policy="hide"
show(p)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 03:50:47