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

如何填充Matplotlib图表负区域背景且保留数据与轴边距?

解决方法

要保留数据与坐标轴的边距,同时填满y=0以下的整个视口区域,别再用基于数据坐标的fill_between了,改用轴坐标系统画一个覆盖下半区的矩形即可,具体步骤和代码如下:

修改后的完整代码

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

fig, ax = plt.subplots()

# 替换成你实际的文件读取与数据处理逻辑
# 这里模拟两条水平线段示例
x1 = [-5, 5]
y1 = [2, 2]
x2 = [-4, 6]
y2 = [-3, -3]

plt.plot(x1, y1, color='blue', linewidth=3, marker='|', markerfacecolor='blue', markersize=12, label='Line 1')
plt.plot(x2, y2, color='green', linewidth=3, marker='|', markerfacecolor='green', markersize=12, label='Line 2')

plt.axvline(x=0, color="k", linestyle='dashed')
plt.axhline(y=0, color="r", linewidth=4)

# 关键:填充y=0以下的整个视口
# 把数据坐标的y=0转换为轴坐标(轴左下角为(0,0),右上角为(1,1))的y值
y0_axes = ax.transLimits.transform((0, 0))[1]
# 添加矩形:覆盖整个轴的宽度,y从轴底部延伸到y=0的位置
ax.add_patch(Rectangle((0, 0), 1, y0_axes, transform=ax.transAxes, color='lightgray', zorder=-1))

plt.legend()
plt.show()

代码说明

  • ax.transLimits.transform((0,0)):将数据坐标的(0,0)转换为轴坐标(范围0-1),取第二个值就是y=0在轴上的相对位置。
  • Rectangle((0,0), 1, y0_axes):从轴左下角(0,0)开始,宽度设为1(覆盖整个轴的宽度),高度延伸到y=0对应的轴坐标位置。
  • transform=ax.transAxes:告诉matplotlib用轴坐标系统绘制矩形,这样不管数据边距怎么设置,矩形都会完美贴合轴的边框。
  • zorder=-1:确保矩形在所有绘图元素的下方,不会挡住你的线条和标记。

这样既保留了数据与坐标轴的边距,又能完全填充y=0以下的视口区域,不会出现空白。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:52:52