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

如何移除Matplotlib/Seaborn绘制图表的左右白边?

去除Matplotlib图表左右白边并保持固定尺寸

我用Matplotlib和Seaborn绘制了包含技术测量数据的图表,已经移除了大部分非内容元素,但左右两侧仍有白边(为便于观察,将背景设为黄色,并用红色标注需移除的白边)。我希望移除这些白边,让图表线条恰好从边缘开始/结束,且最终图像保持480x480px的尺寸。

修改后的代码

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({"x":[1,2,3,4,5,6,7,8,9,10],
                   "y1":[4,3,2,6,6,2,1,5,7,3],
                   "y2":[1,0,6,0,9,2,3,5,4,7]})

size=[480,480]

fig, ax = plt.subplots(figsize=(size[0]/100, size[1]/100), dpi=100, facecolor="yellow")

# 绘制两条折线,无需重复调用set方法
sns.lineplot(data=df, x="x", y="y1", ax=ax)
sns.lineplot(data=df, x="x", y="y2", ax=ax)

# 统一配置轴标签、刻度及范围
ax.set(xlabel=None, ylabel=None,
       xticklabels=[], yticklabels=[],
       xlim=(df['x'].min(), df['x'].max()),  # 让x轴范围精准匹配数据首尾
       ylim=(0, 10))

# 隐藏边框和刻度
ax.box(False)
ax.tick_params(left=False, bottom=False)

# 彻底消除子图与画布的边距,替代tight_layout
plt.subplots_adjust(left=0, right=1, top=1, bottom=0)

plt.show()

关键调整点

  • 给x轴设置完全匹配数据首尾值的范围,让折线刚好对齐画布左右边缘
  • 用plt.subplots_adjust(left=0, right=1, top=1, bottom=0)替代plt.tight_layout(),彻底移除子图周围的留白
  • 合并重复的配置代码,简化逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:55:27