Pandas Series.plot与plt.plot绘图结果不一致问题求助
问题:Pandas绘图与Matplotlib原生绘图结果不一致
我用两段逻辑看似相同的代码绘制df.cumpnl数据,但输出结果完全不同。已经尝试过去除NaN、强制使用索引作为X轴等调试操作,问题仍未解决。
两段代码如下:
- Pandas内置绘图:
df.cumpnl.plot() plt.show()
- Matplotlib原生绘图:
plt.plot(df.cumpnl) plt.show()
附上该DataFrame的统计描述信息:
GLD GDX USO spread moving_average count 2033.000000 2033.000000 2033.000000 2033.000000 2019.000000 unique NaN NaN NaN NaN NaN top NaN NaN NaN NaN NaN freq NaN NaN NaN NaN NaN mean 138.444161 24.877939 82.818234 4.947196 4.936297 std 24.804896 6.822558 31.199880 11.654489 11.282190 min 100.500000 11.713412 17.040001 -26.767277 -24.238099 25% 118.129997 20.289474 65.540001 -1.851543 -2.149600 50% 126.139999 23.060490 84.959999 3.581103 3.482795 75% 164.919998 30.179216 98.720001 10.767963 10.545780 max 193.889999 42.812782 166.559998 46.173454 33.801446 moving_std_dev upper_band lower_band long_entry long_exit count 2019.000000 2019.000000 2019.000000 2033 2033 unique NaN NaN NaN 2 2 top NaN NaN NaN False False freq NaN NaN NaN 1511 1043 mean 2.696286 7.632582 2.240011 NaN NaN std 1.618263 11.343639 11.451420 NaN NaN min 0.419066 -22.795539 -27.101549 NaN NaN 25% 1.564900 0.601110 -4.709357 NaN NaN 50% 2.397069 5.720233 1.190496 NaN NaN 75% 3.396123 12.700594 8.270555 NaN NaN max 13.845905 41.026057 29.988603 NaN NaN positions_long short_entry short_exit positions_short positions count 2019.00000 2033 2033 2018.000000 2018.000000 unique NaN 2 2 NaN NaN top NaN False True NaN NaN freq NaN 1548 1029 NaN NaN mean 0.39574 NaN NaN -0.376115 0.019822 std 0.48913 NaN NaN 0.484529 0.878659 min 0.00000 NaN NaN -1.000000 -1.000000 25% 0.00000 NaN NaN -1.000000 -1.000000 50% 0.00000 NaN NaN 0.000000 0.000000 75% 1.00000 NaN NaN 0.000000 1.000000 max 1.00000 NaN NaN 0.000000 1.000000 spread_difference pnl cumpnl count 2032.000000 2017.000000 2017.000000 unique NaN NaN NaN top NaN NaN NaN freq NaN NaN NaN mean 0.004847 0.050814 36.617689 std 2.203791 1.976904 27.411697 min -16.347592 -25.266641 -28.377081 25% -1.100998 -0.632126 17.994602 50% 0.010404 0.000000 33.423554 75% 1.075803 0.785296 57.287054 max 25.266641 16.347592 102.491103
原因分析与解决办法
这两种绘图方式的核心差异在于X轴的数据源:
df.cumpnl.plot()会自动使用Series的原索引作为X轴,哪怕索引是非连续或带时间戳的;plt.plot(df.cumpnl)则默认使用**连续整数位置(0、1、2...)**作为X轴,直接忽略原Series的索引结构。
结合你的DataFrame统计信息来看,cumpnl的有效数据量是2017,远小于整个DataFrame的2033行,说明cumpnl存在缺失值且索引可能不连续。Matplotlib原生绘图会跳过NaN但仍按连续整数排列,而Pandas绘图会保留原索引的间隔,最终导致两者的X轴对齐逻辑完全不同,图像自然差异巨大。
具体解决步骤:
- 统一X轴数据源:强制Matplotlib使用原索引作为X轴,和Pandas绘图保持一致:
# Pandas绘图(默认用原索引,无需修改) df.cumpnl.plot() plt.show() # Matplotlib绘图,显式传入原索引作为X轴 plt.plot(df.cumpnl.index, df.cumpnl) plt.show() - 清理缺失值:先删除
cumpnl列的NaN行,保证数据索引连续:df_clean = df.dropna(subset=['cumpnl']) # 再分别绘图 df_clean.cumpnl.plot() plt.show() plt.plot(df_clean.cumpnl) plt.show() - 处理时间索引:如果原索引是时间序列,可添加自动格式化代码优化显示:
plt.plot(df.cumpnl.index, df.cumpnl) plt.gcf().autofmt_xdate() # 自动旋转日期标签,避免重叠 plt.show()
执行以上操作后,两种绘图方式的输出就能保持一致了。
内容的提问来源于stack exchange,提问作者Kazien
相关产品推荐
相关产品推荐

