使用Plotly绘制时间序列DataFrame折线图时触发ValueError错误
问题原因
你遇到的ValueError核心是列名不匹配,代码存在两处关键错误:
- 你的DataFrame实际列名是
'2001-07-21 10:45:00+05:00'、'Col 2'、'Col 3'、'Col 4'(注意Col与数字间有空格),但绘图代码里写的是'Col2'、'Col3'、'Col4'(无空格),导致Plotly无法匹配对应列,引发长度不匹配报错。 - 原始DataFrame生成逻辑混乱,把时间字符串设为列名,容易引发后续索引、列名混淆问题。
修正方案
方案1:重构DataFrame(推荐)
先调整数据结构,让索引为时间、列名为清晰的指标名称,避免混乱:
import pandas as pd import pytz import plotly.express as px # 修正模拟数据生成逻辑 data = { 'Col1': [45, 46, 47, 50], 'Col2': [51, 50, 51, 50], 'Col3': [31, 32, 34, 33], 'Col4': [3, 3, 7, 9] } # 直接将时间设为索引 df = pd.DataFrame( data, index=pd.to_datetime([ '2001-07-21 10:00:00+05:00', '2001-07-21 10:15:00+05:00', '2001-07-21 10:30:00+05:00', '2001-07-21 10:45:00+05:00' ], utc=True).tz_convert(pytz.FixedOffset(60)) ) df.index.name = 'date'
对应绘图代码可简化,Plotly会自动识别索引为X轴、所有列为Y轴系列:
def plot_graph(): fig = px.line(df, markers='.') fig.update_xaxes( rangeslider_visible=True, rangeselector=dict( buttons=[ dict(count=1, label="1H", step="hour", stepmode="backward"), dict(step="all") ] ) ) fig.show() plot_graph()
方案2:保留原DataFrame结构
如果必须使用原始DataFrame,需严格匹配列名(注意空格):
def plot_graph(): # 严格匹配列名中的空格 fig = px.line(df, x=df.index, y=[df.columns[0], 'Col 2', 'Col 3', 'Col 4'], markers='.') fig.update_xaxes( rangeslider_visible=True, rangeselector=dict( buttons=[ dict(count=1, label="1H", step="hour", stepmode="backward"), dict(step="all") ] ) ) fig.show() plot_graph()
关键提示
- 用
print(df.columns)查看实际列名,避免拼写、格式错误。 - 绘制全列折线图时,
px.line支持直接传入DataFrame,无需手动指定x和y,工具会自动识别索引与列,更简洁不易出错。
内容的提问来源于stack exchange,提问作者A Newbie
相关产品推荐
相关产品推荐

