《matplotlib 绘图技巧与常见问题》
记录使用 matplotlib 过程中踩过的一些细节:保存 SVG、坐标轴对齐、刻度步长、图例与轴标签的设置方法。
1 将图片保存为 SVG 格式
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 2])
plt.savefig(fname="figure.svg", format="svg")
format支持的格式取决于后端,多数后端支持png、ps、eps、svg。也可不传format,直接由文件名扩展名推断。
2 坐标轴不重合(x 轴起点不在 y 轴)
画完图后有时 x 轴起点不在 y 轴上(左侧留白 / 被截断),此时通过设置 x 轴范围来修正:
plt.xlim(0, 24) # 强制 x 轴从 0 开始
也可同时收窄到数据实际范围以去除边界留白:
plt.margins(x=0) # 去除 x 轴两侧多余边距
3 设置 x 轴的范围和步长
绘制时间轴(如一天 24 小时)时,使用 xticks 精确控制刻度位置:
import numpy as np
# 设置 x 轴刻度为 -1 到 24,步长 1
plt.xticks(np.arange(-1, 24, 1))
4 画图例(legend)
plt.plot(x, y1, label="pv")
plt.plot(x, y2, label="uv")
plt.legend() # 显示图例
plt.legend(loc="upper right") # 指定位置
| loc 取值 | 位置 |
|---|---|
"best" |
自动选择 |
"upper right" |
右上 |
"upper left" |
左上 |
"lower right" / "lower left" |
右下 / 左下 |
"center" |
中央 |
5 设置 x / y 轴标签
plt.xlabel("time")
plt.ylabel("pv")
注意:xlabel 与 ylabel 各对应一个轴,不要混淆。示例中常见错误是两行都写 plt.xlabel,导致 y 轴没有标签。
6 更多常用调整
# 设置标题
plt.title("daily pv/uv")
# 设置 y 轴范围
plt.ylim(0, 10000)
# 坐标轴标签旋转,避免重叠
plt.xticks(rotation=45)
# 紧凑布局,保存前常用
plt.tight_layout()
7 常见问题
- 保存后的空白过大:保存时加
bbox_inches="tight"裁掉多余空白。 - SVG 打开后文字变形:可改用
format="pdf"或嵌入字体(svg.fonttype="path")。 - 刻度太密/太疏:用
plt.xticks(np.arange(start, stop, step))或plt.gca().xaxis.set_major_locator(...)控制。
阅读 —
·
全站 —