更新绘图时出错 + 如何改善其外观

Error while updating a plot + How to improve its appearance

我有这个代码:

import matplotlib.pyplot as plt
import numpy as np

dat=[0,40]
fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = fig.add_subplot(211)
Ln, = ax.plot(dat)
Ln2, = ax2.plot(dat)

plt.ion()
plt.show() 
x, xx = [], []
for i in range(20):
    x.append(i / 2)
    
    xx = [np.cos(a) for a in x[-10:]]
    x.extend(xx)
    
    
    ax.set_xlim(0, len(x)+5)
    ax.set_ylim(min(x), max(x)+5)
    Ln.set_ydata(x)
    Ln.set_xdata(range(len(x)))
    
    x = x[:-len(xx)]
    ax2.set_xlim(0, len(x)+5)
    ax2.set_ylim(min(x), max(x)+5)
    Ln2.set_ydata(x)
    Ln2.set_xdata(range(len(x)))
    plt.pause(0.5)

如果你 运行 它,你会看到:

  1. ax2 正在上涨,而它应该在下方。
  2. 每个子图如何相互重叠。

这是结果的截图:

我希望它更“好找”,但我已经搜索过了,但我不知道从哪里开始。非常感谢您的帮助!

你弄错了索引,应该是:

ax = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

来自 docs:

first digit is the number of rows, the second the number of columns, and the third the index of the subplot