目录
-
- [1️⃣ `export`](#1️⃣
export) - [2️⃣ `MPLBACKEND`](#2️⃣
MPLBACKEND) - [3️⃣ `Agg` 是什么](#3️⃣
Agg是什么) - [4️⃣ 为什么要设置 `Agg`](#4️⃣ 为什么要设置
Agg) - [5️⃣ 典型使用场景](#5️⃣ 典型使用场景)
- [6️⃣ Python等价写法](#6️⃣ Python等价写法)
- [1️⃣ `export`](#1️⃣
export MPLBACKEND=Agg 是一个 Linux / bash 环境变量设置命令 ,用于指定 Python 的 Matplotlib 使用的绘图后端(backend)。
我们拆开解释:
1️⃣ export
export 是 Linux shell 的命令,用于 设置环境变量,并让子进程继承。
例如:
bash
export A=10
表示:
- 当前 shell 设置变量
A - 之后启动的程序(python、bash脚本等)都可以读取这个变量。
2️⃣ MPLBACKEND
MPLBACKEND 是 Matplotlib 的环境变量 ,用于指定 绘图后端。
Matplotlib 有很多 backend,例如:
| Backend | 作用 |
|---|---|
| TkAgg | GUI窗口绘图 |
| Qt5Agg | Qt GUI |
| MacOSX | macOS GUI |
| Agg | 无GUI,直接渲染图片 |
3️⃣ Agg 是什么
Agg 指的是:
Anti-Grain Geometry
它是一个 纯 CPU 的图像渲染引擎,特点:
- 不需要 GUI
- 不需要 X11
- 可以直接生成图片
常见输出:
png
jpg
svg
pdf
例如:
python
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig("a.png")
4️⃣ 为什么要设置 Agg
在 服务器 / Docker / CI / SSH 远程环境 中,通常 没有图形界面。
如果使用默认 backend:
TkAgg
Qt5Agg
就会报错:
cannot connect to X server
或者:
RuntimeError: Invalid DISPLAY variable
所以设置:
bash
export MPLBACKEND=Agg
意思是:
让 Matplotlib 在无图形环境下运行,只生成图片,不打开窗口。
5️⃣ 典型使用场景
例如在 Docker / 训练脚本:
bash
export MPLBACKEND=Agg
python train.py
或者:
bash
MPLBACKEND=Agg python plot.py
常见于:
- 机器学习训练日志画图
- CI pipeline
- 服务器绘图
- ROS / robot 可视化日志
6️⃣ Python等价写法
如果不想用环境变量,也可以在 Python 中写:
python
import matplotlib
matplotlib.use("Agg")
然后再:
python
import matplotlib.pyplot as plt
⚠️ 注意顺序必须在 pyplot 之前。
✅ 一句话总结
export MPLBACKEND=Agg
意思是:
让 Matplotlib 使用 Agg 无GUI后端 ,在服务器或Docker中 只生成图片,不弹出窗口。