当我在 matplotlib 中绘制绘图时,我对后端发生的事情感到困惑,tbh,我不清楚绘图、轴和图形的层次结构。我阅读了文档,它很有帮助,但我仍然感到困惑......
下面的代码以三种不同的方式绘制相同的图 -
#creating the arrays for testing
x = np.arange(1, 100)
y = np.sqrt(x)
#1st way
plt.plot(x, y)
#2nd way
ax = plt.subplot()
ax.plot(x, y)
#3rd way
figure = plt.figure()
new_plot = figure.add_subplot(111)
new_plot.plot(x, y)
现在我的问题是——
最佳答案
方法一
plt.plot(x, y)
这使您可以仅绘制一个具有 (x,y) 坐标的图形。如果你只想得到一个图形,你可以使用这种方式。
方法二
ax = plt.subplot()
ax.plot(x, y)
这使您可以在同一窗口中绘制一个或多个图形。在编写它时,您将只绘制一个图形,但您可以制作如下内容:
fig1, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
您将绘制 4 个名为 ax1、ax2、ax3 和 ax4 的图形,每个图形都在同一窗口上。在我的示例中,这个窗口将被分为 4 个部分。
方法三
fig = plt.figure()
new_plot = fig.add_subplot(111)
new_plot.plot(x, y)
我没有使用它,但您可以找到文档。
示例:
import numpy as np
import matplotlib.pyplot as plt
# Method 1 #
x = np.random.rand(10)
y = np.random.rand(10)
figure1 = plt.plot(x,y)
# Method 2 #
x1 = np.random.rand(10)
x2 = np.random.rand(10)
x3 = np.random.rand(10)
x4 = np.random.rand(10)
y1 = np.random.rand(10)
y2 = np.random.rand(10)
y3 = np.random.rand(10)
y4 = np.random.rand(10)
figure2, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
ax1.plot(x1,y1)
ax2.plot(x2,y2)
ax3.plot(x3,y3)
ax4.plot(x4,y4)
plt.show()
其他示例:
关于python - 在 matplotlib 中使用绘图、轴或图形绘制绘图有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37970424/