You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas DataFrame以行作x轴列作曲线绘图时行值未排序如何解决

问题原因

你的DataFrame索引(行数值)本身是无序的,matplotlib绘制折线时会严格按照传入数据的顺序连接点,不会自动排序,因此出现线条跳转的问题。

解决方案

核心操作是先对DataFrame按索引排序,再执行绘图,以下是两种实现方式:

  • 方式1:修改你原有写法,适配你的绘图逻辑
# 先按行索引升序排序
df_sorted = df.sort_index()
# 遍历每一列绘图
for name, series in df_sorted.iteritems():
    plt.plot(series, df_sorted.index, label=name)
# 增加图例区分不同列
plt.legend()
plt.show()
plt.close()
  • 方式2:使用pandas内置绘图接口,无需手动循环遍历列
# 排序后转置,保持x为列值、y为行索引的绘图逻辑
df.sort_index().T.plot(kind='line', subplots=False)
plt.show()
plt.close()

如果需要将行索引作为x轴、列值作为y轴,直接去掉转置即可:

df.sort_index().plot(kind='line', subplots=False)
plt.show()
plt.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:15:04