6

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
2
  • 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. Commented Dec 4, 2018 at 11:52
  • Okay, thanks for the advice Commented Dec 4, 2018 at 12:10

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
I don't know if it's possible to concatenate two figures, but I would tend to think not. try to understand this post stackoverflow.com/questions/22521560/…. Good lucke CiaranWelsh.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.