You need to enable JavaScript to run this app. 如何基于DataFrame绘制各ticker为折线、x轴为月度时段的Plotly折线图
优惠活动
大模型
产品
解决方案
定价
更多

如何基于DataFrame绘制各ticker为折线、x轴为月度时段的Plotly折线图

你当前的DataFrame为宽表结构,ticker为行维度、月度时段为列维度,不符合Plotly Express折线图的入参要求,需要先将数据重塑为长表结构再绘图,完整实现代码如下:

import pandas as pd
import plotly.express as px

# 如果ticker存储在DataFrame的行索引中,先将索引转为普通列,列名自定义为ticker即可
df_mentioned = df_mentioned.reset_index(names='ticker')

# 宽表转长表
df_long = df_mentioned.melt(
    id_vars='ticker',
    value_vars=['1-10_Ap','21-31_Ap','1-10_May','11-20_May','21-31_May','1-10_June','11-20_June','21-30_June'],
    var_name='月度时段',
    value_name='对应数值'
)

# 绘制折线图
fig = px.line(
    df_long,
    x='月度时段',
    y='对应数值',
    color='ticker',
    labels={'ticker': '标的代码'}
)
# 固定x轴顺序,避免默认排序错乱
fig.update_xaxes(
    categoryorder='array',
    categoryarray=['1-10_Ap','21-31_Ap','1-10_May','11-20_May','21-31_May','1-10_June','11-20_June','21-30_June']
)
fig.show()

如果你的标的代码存储的列名不是ticker而是Term,对应替换上述代码中id_vars和color参数的字段名即可。

如果不需要用Plotly,也可以用Matplotlib快速实现,代码如下:

import matplotlib.pyplot as plt

# 直接用宽表绘图,将ticker设为索引后转置绘图即可
df_plt = df_mentioned.set_index('ticker').T
df_plt.plot(kind='line', figsize=(12,6), xlabel='月度时段', ylabel='对应数值')
plt.legend(title='标的代码')
plt.show()

内容的提问来源于stack exchange,提问作者amc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 00:24:04