Matplotlib的编码风格

125 阅读1分钟

使用Matplotlib基本上有两种方式:

  1. 显式创建Figure和Axes,并调用它们的方法(即“面向对象(OO)风格”)。
  2. 依靠pyplot隐式创建和管理Figure和Axes,并使用pyplot函数进行绘图。

使用OO风格:

x = np.linspace(0, 2, 100) # Sample data.

# Note that even in the OO-style, we use `.pyplot.figure` to create the Figure.

fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')

ax.plot(x, x, label='linear') # Plot some data on the axes.

ax.plot(x, x**2, label='quadratic') # Plot more data on the axes...

ax.plot(x, x**3, label='cubic') # ... and some more.

ax.set_xlabel('x label') # Add an x-label to the axes.

ax.set_ylabel('y label') # Add a y-label to the axes.

ax.set_title("Simple Plot") # Add a title to the axes.

ax.legend() # Add a legend.

image.png

或 pyplot 风格:

x = np.linspace(0, 2, 100) # Sample data.

plt.figure(figsize=(5, 2.7), layout='constrained')

plt.plot(x, x, label='linear') # Plot some data on the (implicit) axes.

plt.plot(x, x**2, label='quadratic') # etc.

plt.plot(x, x**3, label='cubic')

plt.xlabel('x label')

plt.ylabel('y label')

plt.title("Simple Plot")

plt.legend()

两者结果一样。