Search code examples
pythonmatplotlibmatplotlib-animation

Error while updating a plot + How to improve its appearance


I have this code:

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)

If you run it, you'll see:

  1. That ax2 is plotting upside, while it should be below.
  2. How each subplot overlaps the other.

This is a screenshot of the result: screenshot

I want it to be more "good loocking", but I've searched and I just don't know where to start. I'd appreciate your help!


Solution

  • You got the indexes wrong, it should be:

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

    from the docs:

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