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}")) # 格式化