0

I know how to do figures with subplots in principle. What I'm trying to do is to create some figures containing only one ax. Subsequently, I want to use them further within the same subplot without creating them again. Below is what I have.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 2*np.pi, 0.01)
y1 = np.sin(x)
y2 = np.sin(2*x)

plt.clf()
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.plot(x,y1)

fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.plot(x,y2)

Now I want to use ax1 and ax2 within a new figure. How can I do that without specifying the plots again? In my actual code, there are lots of options to set and I'd like to avoid that. Something like

fig3 = plt.figure()
ax1 = fig3.add_subplot(121)
ax2 = fig3.add_subplot(122)

such that the axes defined above are reused within a new figure alongside each other.

EDIT: I found a solution. It turns out that it is not really possible to use a defined axis, as the definition of the axis includes whether it is a subplot or nor. Instead, I went for something along these lines:

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(data)
ax2.plot(data)
fig.show()

This way, the specfication of the axis is largely independent of defining the overall plot.

E. Sommer
  • 710
  • 1
  • 7
  • 28
  • What is the problem? You can still use the instances `ax1` and `ax2` to plot and it will appear in the corresponding subplots. – Sheldore Dec 23 '18 at 17:23
  • 1
    so, just `fig3 = plt.figure()` and then `ax1 = fig3.add_subplot(121)` `ax2 = fig3.add_subplot(122)`? This doesn't work, the fig3 will be empty. – E. Sommer Dec 23 '18 at 17:25
  • Your question is unclear to me. Please add some example/explanation in the question. – Sheldore Dec 23 '18 at 17:36

0 Answers0