为什么每个绘图命令(即标签、标题)在 spyder 中开始一个新绘图而不是出现在一个图表上?

why does each plot command (i.e. labels,title) start a new plot in spyder instead of appearing on one graph?

我正在尝试在 spyder 中绘制图表,但我的代码中的每一行都会开始一个新的绘图。我已经尝试使用 python 教程之一中的示例,我包含了其中的代码,但发生了同样的情况。

import matplotlib.pyplot as plt

x = [1,2,3]
y = [5,7,4]

x2 = [1,2,3]
y2 = [10,14,12]

plt.plot(x, y, label='First Line')
plt.plot(x2, y2, label='Second Line')

plt.xlabel('Plot Number')
plt.ylabel('Important var')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()

每行生成一个新图,而不是添加到第一个图。所以 plt.xlabel 给出了一个带有 x 标签的新空图,而不是向原始图添加 x 标签,plt.ylabel 做同样的事情等等。

这可能是一个愚蠢的问题,但我非常感谢任何帮助。picture of plots

您必须创建一个唯一轴,然后将绘图添加到该轴。

您可以通过创建 子图 来实现。试试这个代码:

import matplotlib.pyplot as plt

# Data:
x = [1,2,3]
y = [5,7,4]

x2 = [1,2,3]
y2 = [10,14,12]

# Figure creation:
fig, ax = plt.subplots()

ax.plot(x,  y,  label = 'First Line' )
ax.plot(x2, y2, label = 'Second Line')

ax.set_xlabel('Plot Number',  fontsize = 12)
ax.set_ylabel('Important var', fontsize = 12)
ax.set_title('Interesting Graph\nCheck it out', fontsize = 12)

ax.legend()
plt.show()

如果你想创建两个轴,你可以这样做:

fig, (ax1, ax2) = plt.subplots(2)

然后以独立的方式将绘图添加到其轴上。

ax1.plot(x,  y,  label = 'First Line' )
ax2.plot(x2, y2, label = 'Second Line')

你的代码对我来说工作正常。