Python Jupyter Notebook: Put two histogram subplots side by side in one figure
21,476
Solution 1
Yes this is possible. See the following code.
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
list1 = np.random.rand(10)*2.1
list2 = np.random.rand(10)*3.
bins = np.linspace(0, 1, 3)
fig, ax = plt.subplots(1,2)
ax[0].hist(list1, bins, alpha = 0.5, color = 'r')
ax[1].hist(list2, bins, alpha = 0.5, color = 'g')
plt.show()
Solution 2
You can use matplotlib.pyplot.subplot for that:
import matplotlib.pyplot as plt
import numpy as np
list1 = np.random.rand(10)*2.1
list2 = np.random.rand(10)*3.0
plt.subplot(1, 2, 1) # 1 line, 2 rows, index nr 1 (first position in the subplot)
plt.hist(list1)
plt.subplot(1, 2, 2) # 1 line, 2 rows, index nr 2 (second position in the subplot)
plt.hist(list2)
plt.show()
Author by
Edamame
Updated on July 05, 2022Comments
-
Edamame almost 2 years
I am using Python (3.4) Jupyter Notebook. I have the following two histograms in two separated cells, each has their own figure:
bins = np.linspace(0, 1, 40) plt.hist(list1, bins, alpha = 0.5, color = 'r')
and
bins = np.linspace(0, 1, 40) plt.hist(list2, bins, alpha = 0.5, color = 'g')
Is it possible to put the above two histograms as two subplots side by side in one figure?
-
mgilson over 6 yearsIt's better practice to explain what you're doing. For example, the arguments of
plt.subplot
aren't intuitive to the un-initiated and it is frequently nice to include your imports as well :-) -
Tanmoy over 6 yearsThis is a solution to the question put by @Edamame to display two histograms as two subplots side by side in one figure.
-
Tanmoy over 6 years@mgilson - Edamame was already using plt.hist. So, it was inherent that s/he had already imported matplotlib.pyplot as plt. Hencce the import was not included.
-
mgilson over 6 years@Tanmoy -- Just because the asker and you know doesn't mean that future visitors to this question will know. Remember, you're not just addressing Edamame's question -- You're also addressing the questions of future visitors who might be trying to accomplish the same thing.
-
fraxture about 6 yearsCan you explain what you are doing with the expression for
bins
:np.linspace(0, 1, 3)
? -
ImportanceOfBeingErnest about 6 years@fraxture
bins
is the array that contains the edges of the bins for the histogram. -
WoJ about 5 years@mgilson: I updated the answer with working code (a bit taken from the other answer).This answer helped me so it could be useful for others too, as you mention.