Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Jupyter Notebook: Put two histogram subplots side by side in one figure

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?

like image 644
Edamame Avatar asked Dec 18 '16 21:12

Edamame


People also ask

How do you plot two histograms in one figure in Python?

For example, to make a plot with two histograms, we need to use pyplot's hist() function two times. Here we adjust the transparency with alpha parameter and specify a label for each variable. Here we customize our plot with two histograms with larger labels, title and legend using the label we defined.

How do you plot a histogram side by side in Python?

Make two dataframes, df1 and df2, of two-dimensional, size-mutable, potentially heterogeneous tabular data. Create a figure and a set of subplots. Make a histogram of the DataFrame's, df1 and df2. To display the figure, use show() method.

How do you plot two histograms together?

For plotting two histograms together, we have to use hist() function separately with two datasets by giving some setting. Used to represent the label of the histogram it is of string type. Used for setting amount of transparency. Used to represent the name or label of the histogram.


2 Answers

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()
like image 196
ImportanceOfBeingErnest Avatar answered Sep 30 '22 15:09

ImportanceOfBeingErnest


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

like image 33
Tanmoy Avatar answered Sep 30 '22 17:09

Tanmoy