Matplotlib: Adding an axes using the same arguments as a previous axes

This is a good example that shows the benefit of using matplotlib's object oriented API.

import numpy as np
import matplotlib.pyplot as plt

# Generate random data
data = np.random.rand(100)

# Plot in different subplots
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(data)

ax2.plot(data)

ax1.plot(data+1)

plt.show()

Note: it is more pythonic to have variable names start with a lower case letter e.g. data = ... rather than Data = ... see PEP8


Using plt.subplot(1,2,1) creates a new axis in the current figure. The deprecation warning is telling that in a future release, when you call it a second time, it will not grab the previously created axis, instead it will overwrite it.

You can save a reference to the first instance of the axis by assigning it to a variable.

plt.figure()
# keep a reference to the first axis
ax1 = plt.subplot(1,2,1)
ax1.plot(Data)

# and a reference to the second axis
ax2 = plt.subplot(1,2,2)
ax2.plot(Data)

# reuse the first axis
ax1.plot(Data+1)