How can I plot multiple figure in the same line with matplotlib?
Just use subplots.
plt.plot(data1)
plt.show()
plt.subplot(1,2,1)
plt.plot(data2)
plt.subplot(1,2,2)
plt.plot(data3)
plt.show()
(This code shouldn't work, it's just the idea behind it that matters)
For number 2, again same thing: use subplots:
# 1. Plot in same line, this would work
fig = plt.figure(figsize = (15,8))
ax1 = fig.add_subplot(1,2,1, projection = '3d')
custom_plot1(ax1)
ax2 = fig.add_subplot(1,2,2)
custom_plot2(ax2)
# 2. Plot in same line, on two rows
fig = plt.figure(figsize = (8,15)) # Changed the size of the figure, just aesthetic
ax1 = fig.add_subplot(2,1,1, projection = '3d') # Change the subplot arguments
custom_plot1(ax1)
ax2 = fig.add_subplot(2,1,2) # Change the subplot arguments
custom_plot2(ax2)
This won't display two different figures (which is what I understand from 'different lines') but puts two figures, one above the other, in a single figure.
Now, explanation of subplot arguments: subplot(rows, cols, axnum)
rows
would be the number of rows the figure is divided into.
cols
would be the number of columns the figure is divided into.
axnum
would be which division you're going to plot into.
In your case, if you want two graphics side by side, then you want one row with two columns --> subplot(1,2,...)
In the second case, if you want two graphics one above the other, then you want 2 rows and one column --> subplot(2,1,...)
For more complex distributions, use gridspec
http://matplotlib.org/users/gridspec.html
cqcn1991
Updated on June 18, 2022Comments
-
cqcn1991 almost 2 years
In my
Ipython Notebook
, I have a script produces a series of multiple figures, like this:The problem is that, these figures
take too much space
, and I'm producing many of these combinations. This makes me very difficult to navigate between these figures.I want to make some of the plot in the same line. How can I do it?
UPDATE:
Thanks for the fjarri's suggestion, I have changed the code and this works for plotting in the same line.
Now, I want to make them plot in different lines(the default option). What should I do? I have tried some, but not sure if this is the right way.
def custom_plot1(ax = None): if ax is None: fig, ax = plt.subplots() x1 = np.linspace(0.0, 5.0) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) ax.plot(x1, y1, 'ko-') ax.set_xlabel('time (s)') ax.set_ylabel('Damped oscillation') def custom_plot2(ax = None): if ax is None: fig, ax = plt.subplots() x2 = np.linspace(0.0, 2.0) y2 = np.cos(2 * np.pi * x2) ax.plot(x2, y2, 'r.-') ax.set_xlabel('time (s)') ax.set_ylabel('Undamped') # 1. Plot in same line, this would work fig = plt.figure(figsize = (15,8)) ax1 = fig.add_subplot(1,2,1, projection = '3d') custom_plot1(ax1) ax2 = fig.add_subplot(1,2,2) custom_plot2(ax2) # 2. Plot in different line, default option custom_plot1() custom_plot2()