使用Plotly.express绘制圆柱温度数据极坐标动画遇长度不匹配错误
解决Plotly Express line_polar动画的ValueError:参数长度不匹配问题
错误原因分析
你遇到的错误:
ValueError: All arguments should have the same length. The length of column argument
df[animation_frame]is 10, whereas the length of previously-processed arguments ['r', 'theta'] is 6
核心问题是数据格式不兼容:你的原始DataFrame是宽格式(每行对应1个时间点的6个传感器数据),但Plotly Express的动画逻辑要求每个数据点(单传感器温度值)都对应一个animation_frame值。当前Time列仅10行,而r/theta对应的是6组值,长度无法对齐,导致报错。
解决方案:数据格式重塑
需要将宽格式数据转换为长格式(窄表),让每个时间点的每个传感器数据成为单独一行,使用pandas.melt完成转换,再为传感器映射对应的极坐标角度。
完整修正代码
import pandas as pd import plotly.express as px # 读取原始数据 df = pd.read_excel('TempData.xlsx') # 1. 将宽表转为长表:保留Time列,将#1-#6列转为Sensor和Temperature列 df_melted = df.melt(id_vars='Time', var_name='Sensor', value_name='Temperature') # 2. 为每个传感器映射对应的极坐标角度 sensor_angle_map = { '#1': '0', '#2': '60', '#3': '120', '#4': '180', '#5': '240', '#6': '300' } df_melted['theta'] = df_melted['Sensor'].map(sensor_angle_map) # 3. 绘制极坐标动画 fig = px.line_polar(df_melted, r='Temperature', theta='theta', line_close=True, color_discrete_sequence=px.colors.sequential.Plasma_r, template="plotly_dark", animation_frame="Time") # 保持原有的极坐标设置 fig.update_polars(radialaxis_range=[160, 190]) fig.update_polars(radialaxis_rangemode="normal") fig.update_polars(radialaxis=dict(tickvals=[150, 160, 170, 180, 190, 200])) fig.show()
代码说明
- 数据重塑:
df.melt将原始的10行数据转换为60行(10个时间点 × 6个传感器),每行对应一个(Time, Sensor, Temperature)组合,确保animation_frame能为每个数据点分配对应时间。 - 角度映射:通过字典将
#1-#6传感器对应到0°-300°的极坐标角度,保证theta参数与温度值正确关联。 - 动画绘制:此时
r(Temperature)、theta和animation_frame(Time)的长度完全匹配,动画可正常生成。
内容的提问来源于stack exchange,提问作者stein
相关产品推荐
相关产品推荐

