如何用Plotly Express批量绘制DataFrame多列折线图?
问题:如何用Plotly Express批量绘制DataFrame所有列的多折线图
我有一个包含Day列和52个其他列的DataFrame,想要绘制多折线图。目前手动指定单个列可以正常绘图:
fig = px.line(cart_acum_t, x=cart_acum_t.index, y=[cart_acum_t[cart_acum_t.columns[0]],cart_acum_t[cart_acum_t.columns[1]],cart_acum_t[cart_acum_t.columns[2]]]) fig.show()
但直接传入所有列名时出现错误:
fig = px.line(cart_acum_t, x=cart_acum_t.index, y=cart_acum_t.columns) fig.show()
错误信息:
ValueError: All arguments should have the same length. The length of argument `y` is 53, whereas the length of previously-processed arguments ['index'] is 2
请问如何无需逐个指定列,实现所有列的多折线图绘制?
解决方案
报错原因是px.line的y参数需要接收对应数据的序列/数组列表,而非列名列表。直接传入cart_acum_t.columns相当于把53个列名作为y值序列,和x轴索引的长度不匹配,因此触发错误。以下是两种可行的解决方法:
方法1:批量获取列数据传入y参数
通过列表推导式批量提取每一列的数据集,传入y参数:
# 绘制所有列的折线图 fig = px.line(cart_acum_t, x=cart_acum_t.index, y=[cart_acum_t[col] for col in cart_acum_t.columns]) fig.show()
如果需要排除Day列,只绘制其余52列,可先过滤列名:
target_cols = [col for col in cart_acum_t.columns if col != 'Day'] fig = px.line(cart_acum_t, x=cart_acum_t.index, y=[cart_acum_t[col] for col in target_cols]) fig.show()
方法2:转换为长格式数据绘图(推荐)
Plotly Express对长格式数据的支持更友好,用melt方法将宽表转成长表后绘图,可读性和扩展性更强:
# 将索引转为列,再转成长格式 cart_acum_t_long = cart_acum_t.reset_index().melt(id_vars=['index'], var_name='Series', value_name='Value') # 按系列区分颜色绘制折线图 fig = px.line(cart_acum_t_long, x='index', y='Value', color='Series') fig.show()
如果Day列是你需要的x轴,可直接以Day作为保留列转换:
cart_acum_t_long = cart_acum_t.melt(id_vars=['Day'], var_name='Series', value_name='Value') fig = px.line(cart_acum_t_long, x='Day', y='Value', color='Series') fig.show()
内容的提问来源于stack exchange,提问作者Luís Henrique Angélico
相关产品推荐
相关产品推荐

