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

Pyplot中箱线图叠加折线图时子图对齐问题求助

解决折线图与箱线图x轴偏移的问题

问题原因

pandas绘制箱线图时,每个箱体对应的x轴坐标是从1开始的连续整数(对应你的20列数据,坐标范围120);而直接调用`ax.plot(line_plot1)`时,折线图默认使用从0开始的索引(019),两者坐标起点差1,导致整体偏移。

解决思路

手动指定折线图的x轴坐标,让它和箱线图的x坐标一一对应:

  • 因为你有20列数据,折线图的x坐标应设为1到20,完全匹配箱线图的位置。

修改后的代码

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("PlotData2.csv")
df_plot = df.iloc[:, 0:20]
line_plot1 = df_plot.iloc[1]
line_plot2 = df_plot.iloc[0]

fig, ax = plt.subplots()
ax.set_ylim(-3.2, -1.6)

# 直接在已创建的ax上绘制箱线图,避免覆盖ax对象
df_plot.boxplot(grid=False, rot=90, showmeans=True, manage_ticks=True, ax=ax)
ax.set(ylabel='Voltage (V)')
ax.invert_yaxis()

# 指定x坐标为1到20,和箱线图对齐
x_coords = range(1, len(line_plot1)+1)
ax.plot(x_coords, line_plot1, label='设备1')
ax.plot(x_coords, line_plot2, label='设备2')

ax.legend()
fig.tight_layout()
plt.show()

额外优化点

  • 原代码中ax = df_plot.boxplot(...)会覆盖之前创建的ax对象,改为通过ax参数指定绘图轴更稳妥。
  • 添加图例可清晰区分两台设备的折线,便于观察异常值来源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 08:02:09