Polars DataFrame与Plotly绘图:轴映射异常及ValueError问题
问题描述
使用Polars 0.15.0和Plotly 5.11.0绘制折线图时遇到两个问题:
- 直接调用
px.line(df)生成了10个系列(每个系列3个点),而非预期的2个系列(每个系列10个点),且未将time列作为X轴。 - 尝试指定
x='time', y=['A', 'B']时触发报错:
ValueError: Value of 'x' is not the name of a column in 'data_frame'. Expected one of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] but received: time
原因分析
旧版本的Plotly Express(5.11.0)对Polars DataFrame兼容性不足,无法正确识别Polars的列名,会错误地将DataFrame按行索引处理,而非按列名解析。
解决方案
方案1:转换为Pandas DataFrame
将Polars DataFrame转换为Plotly支持更完善的Pandas DataFrame后再绘图:
from numpy import linspace import polars as pl import plotly.express as px import plotly.io as pio pio.renderers.default = 'browser' times = linspace(1, 6, 10) df = pl.DataFrame({ 'time': times, 'A': times**2, 'B': times**3, }) # 转换为Pandas DataFrame df_pd = df.to_pandas() fig = px.line(df_pd, x='time', y=['A', 'B']) fig.show()
方案2:使用Plotly Graph Objects手动构建
直接从Polars列提取数据,用graph_objects手动创建折线图:
from numpy import linspace import polars as pl import plotly.graph_objects as go import plotly.io as pio pio.renderers.default = 'browser' times = linspace(1, 6, 10) df = pl.DataFrame({ 'time': times, 'A': times**2, 'B': times**3, }) fig = go.Figure() # 添加A系列折线 fig.add_trace(go.Scatter(x=df['time'], y=df['A'], mode='lines', name='A')) # 添加B系列折线 fig.add_trace(go.Scatter(x=df['time'], y=df['B'], mode='lines', name='B')) # 设置X轴标题 fig.update_layout(xaxis_title='time') fig.show()
额外建议
如果长期搭配使用Polars和Plotly,建议升级到Polars ≥0.16.0、Plotly ≥5.12.0的版本,新版本对Polars的兼容性有明显提升,无需转换即可直接用列名指定X/Y轴。
内容的提问来源于stack exchange,提问作者mins
相关产品推荐
相关产品推荐

