Home > Blockchain >  How to show multiple already plotted matplotlib figures side-by-side or on-top in Python without re-
How to show multiple already plotted matplotlib figures side-by-side or on-top in Python without re-

Time:02-01

I have already plotted two figures separately in a single jupyter notebook file, and exported them.

What I want is to show them side by side, but not plot them again by using matplotlib.pyplot.subplots.

For example, in Mathematica, it's easier to do this by just saving the figures into a Variable, and displaying them afterwards.


What I tried was saving the figures, using

fig1, ax1 = plt.subplots(1,1)
... #plotting using ax1.plot()
fig2, ax2 = plt.subplots(1,1)
... #plotting using ax2.plot()

Now, those fig1 or fig2 are of type Matplotlib.figure.figure which stores the figure as an 'image-type' instance. I can even see them separately by calling just fig1 or fig2 in my notebook.

But, I can not show them together as by doing something like

plt.show(fig1, fig2)

It returns nothing since, there wasn't any figures currently being plotted.


You may look at this link or this, which is a Mathematica version of what I was talking about.

CodePudding user response:

assuming u want to merge those subplots in the end. Here is the code

import numpy as np
import matplotlib.pyplot as plt

#e.x function to plot
x = np.linspace(0, 10)
y = np.exp(x)

#almost your code
figure, axes = plt.subplots(1,1)
res_1, = axes.plot(x,y) #saving the results in a tuple
plt.show()
plt.close(figure)
figure, axes = plt.subplots(1,1)
res_2, = axes.plot(x,-y) #same before
plt.show()


#restructure to merge
figure_2, (axe_1,axe_2) = plt.subplots(1,2)  #defining rows and columns
axe_1.plot(res_1.get_data()[0], res_1.get_data()[1]) #using the already generated data 
axe_2.plot(res_2.get_data()[0], res_2.get_data()[1])
#if you want show them in one

plt.show()







CodePudding user response:

Not quite sure what you mean with:

but not plot them again by using matplotlib.pyplot.subplots.

But you can display two figures next to each other in a jupyter notebook by using:

fig, ax = plt.subplots(nrows=1, ncols=2)

ax[0] = ...  # Code for first figure
ax[1] = ...  # Code for second figure

plt.show()

Or above each other:

fig, ax = plt.subplots(nrows=2, ncols=1)

ax[0] = ...  # Top figure
ax[1] = ...  # Bottom figure

plt.show()
  • Related