In Matplotlib, we can draw multiple graphs in a single plot in two ways. One is by using subplot() function and other by superimposition of second graph on the first i.e, all graphs will appear on the same plot.
To create multiple plots we use the subplot function of pyplot module in Matplotlib. Parameters: nrows is for number of rows means if the row is 1 then the plots lie horizontally. ncolumns stands for column means if the column is 1 then the plot lie vertically.
Change your subplot settings to:
plt.subplot(1, 2, 1)
...
plt.subplot(1, 2, 2)
The parameters for subplot
are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1
means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2
means "a 1-row, 2-column figure: go to the second subplot."
You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:
In order to minimize the overlap of subplots, you might want to kick in a:
plt.tight_layout()
before the show. Yielding:
Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html
plt.subplots
is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()
When stacking subplots in one direction, the matplotlib documentation advocates unpacking immediately if you are just creating a few axes.
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(20,8))
sns.histplot(df['Price'], ax=ax1)
sns.histplot(np.log(df['Price']),ax=ax2)
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With