9

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?

WoJ
  • 27,165
  • 48
  • 180
  • 345
Edamame
  • 23,718
  • 73
  • 186
  • 320

2 Answers2

18

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()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
7

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()

enter image description here

WoJ
  • 27,165
  • 48
  • 180
  • 345
Tanmoy
  • 789
  • 7
  • 14
  • It'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 :-) – mgilson Oct 10 '17 at 03:10
  • This is a solution to the question put by @Edamame to display two histograms as two subplots side by side in one figure. – Tanmoy Oct 11 '17 at 07:13
  • @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. – Tanmoy Oct 11 '17 at 07:15
  • 4
    @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. – mgilson Oct 11 '17 at 18:14
  • @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. – WoJ May 20 '19 at 11:15