matplotlib.pyplot

Abstract

记录一些 matplotlib.pyplot 的 tips

1. 如何使绘图时正常显示中文(标注等)
import matplotlib.pyplot as plt
from matplotlib import rcParams
config = {
        "font.family": ["Times New Roman","SimHei"],
        "mathtext.fontset": 'stix',  # matplotlib渲染数学字体时使用的字体,和Times New Roman差别不大
        "font.serif": ['Times New Roman','SimHei'],  # 黑体
        'axes.unicode_minus': False  # 处理负号,即-号
    }
rcParams.update(config)
2. 如何设置坐标轴范围(如“从零开始”)
# 方法一
plt.xlim(0, max(x) + 1)  # x 轴从 0 开始,范围稍微超出最大值
plt.ylim(0, max(y) + 1)  # y 轴从 0 开始,范围稍微超出最大值

# 方法二
plt.axis([0, max(x) + 1, 0, max(y) + 1])  # [xmin, xmax, ymin, ymax]

# 方法三(面向对象)
fig, ax = plt.subplots()        # 创建图形和轴对象
ax.plot(x, y)                   # 绘图
ax.set_xlim(0, max(x) + 1)  # x 轴从 0 开始
ax.set_ylim(0, max(y) + 1)  # y 轴从 0 开始
3. 如何设置坐标轴刻度间隔
# 以下以x轴为例,y轴可类比
# 方法一
x = [0, 2, 4, 6, 8]
plt.xticks(ticks=[0, 2, 4, 6, 8], labels=['0', '2', '4', '6', '8'])

# 方法二(自动设置)
plt.locator_params(axis='x', nbins=5)  # 设置 x 轴的刻度数量为 5

# 方法三(面向对象)
fig, ax = plt.subplots()
ax.plot(x, y) 
ax.set_xticks(ticks=[0, 1, 2, 3, 4], labels=['0', '1', '2', '3', '4'])

# 方法四(面向对象,调用 matplotlib.ticker )
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
fig, ax = plt.subplots()
ax.plot(x, y) 

# 3选1 即可
ax.xaxis.set_major_locator(ticker.MaxNLocator(nbins=5))  # x 轴最多显示 5 个刻度
ax.xaxis.set_major_locator(ticker.MultipleLocator(2))  # x 轴刻度间隔为 2
ax.xaxis.set_major_locator(ticker.MaxNLocator(nbins=5, steps=[1, 2, 5, 10]))  # 自适应 x 轴刻度

ax.xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.1f}"))  # 格式化 
4. 防止坐标轴刻度重合
plt.tight_layout()  # 自动调整布局,防止标签重叠

# 一般来说上述操作已经可以解决,但单个刻度较长时也可旋转刻度:
plt.xticks(rotation=45)  # 将 x 轴标签逆时针倾斜 45 度
5. 坐标轴自定义刻度标签
# 设置自定义刻度标签
plt.xticks(x, [f'{i} s' for i in x])  # 自定义X轴刻度标签
plt.yticks(y, [f'{i} m' for i in y])  # 自定义Y轴刻度标签