使用Plotly绘制带DateTime索引的收益率利差折线图报错求助
Fixing ValueError When Plotting Time Series Yield Spread with Plotly Express
我来帮你解决这个Plotly的ValueError问题!咱们先拆解下错误的根源:
你传入px.line()的第一个参数是data['yieldsp']——这是一个Pandas Series,Plotly会自动把它视为只有一列的DataFrame,这列的名字就是yieldsp。但你在y参数里写了'Yield Spread',这个名字并不存在于这个"虚拟DataFrame"的列名列表中,所以才会触发报错提示"Expected one of ['yieldsp'] but received: Yield Spread"。
这里有两种简单的修复方案,都能完美适配你的DateTime索引:
方法1:使用原DataFrame并自定义显示标签
直接把整个data作为data_frame传入,指定y为真实列名yieldsp,再通过labels参数把显示名称改成你想要的"Yield Spread":
import plotly.express as px fig = px.line(data, x=data.index, y='yieldsp', labels={'yieldsp': 'Yield Spread'}, # 将y轴标签替换为自定义名称 line_shape="spline", render_mode="svg") fig.update_layout(xaxis_title='Date') # 可选:给x轴添加明确的标题 fig.show()
方法2:将Series转为重命名后的DataFrame
如果你更倾向于单独处理yieldsp这个序列,可以把它转换成DataFrame并重命名列,这样就能直接用'Yield Spread'作为y的参数:
import plotly.express as px # 将Series转为DataFrame并重命名列 yieldsp_df = data['yieldsp'].rename('Yield Spread').to_frame() fig = px.line(yieldsp_df, x=yieldsp_df.index, y='Yield Spread', line_shape="spline", render_mode="svg") fig.show()
两种方法都能生成你需要的时间序列折线图,完全匹配你的数据结构~
内容的提问来源于stack exchange,提问作者Frodo Baggins
相关产品推荐
相关产品推荐

