5

I have a list of pre-existing figures with the same x-axis and I want to stack them on a single canvas. For example, here I generate two figures separately - how would I put them together on a single plot?

import matplotlib.pyplot as plt

time = [0, 1, 2, 3, 4]
y1 = range(10, 15)
y2 = range(15, 20)

## Plot figure 1
fig1 = plt.figure()
plt.plot(time, y1)

## plot figure 2
fig2 = plt.figure()
plt.plot(time, y2)

## collect in a list
figs = [fig1, fig2]

plt.subplot(1, 1, 1)
## code to put fig1 here

plt.subplot(1, 1, 2)
## code to put fig2 here
CiaranWelsh
  • 7,014
  • 10
  • 53
  • 106
  • That's not possible. There is ever only a single figure per canvas. You can in theory move the artists from one figure to another, but that is really cumbersome (I have an answer on how to do that but I won't link to it, because it's really not recommended.) Instead you create the artists inside a figure. The design principle is to create functions which plot to axes. Call those functions with the only axes from some figure, or with one axes from a figure with several axes. – ImportanceOfBeingErnest Dec 04 '18 at 11:52
  • Okay, thanks for the advice – CiaranWelsh Dec 04 '18 at 12:10

1 Answers1

2

Yes:

import matplotlib.pyplot as plt
from matplotlib import gridspec

time = [0, 1, 2, 3, 4]
y1 = range(10, 15)
y2 = range(15, 20)

plt.figure(figsize = (5,10))
fig = gridspec.GridSpec(2, 1, height_ratios=[1,1])

x1 = plt.subplot(fig[0])
plt.plot(time, y1)

x2 = plt.subplot(fig[1])
plt.plot(time, y2)

Output:

enter image description here

B.Gees
  • 1,125
  • 2
  • 11
  • 28
  • Hi. Thanks for the answer. GridSpec looks promising but I have a list of preexisting figure objects (since I have output from a function that I don't want to modify). Is it possible to create a new figure from these pre-existing ones? – CiaranWelsh Dec 04 '18 at 11:33
  • 1
    I don't know if it's possible to concatenate two figures, but I would tend to think not. try to understand this post https://stackoverflow.com/questions/22521560/how-to-combine-several-matplotlib-figures-into-one-figure. Good lucke CiaranWelsh. – B.Gees Dec 04 '18 at 11:49