Python Jupyter Notebook:将两个直方图子图并排放置在一个图中

Eda*_*ame 4 python matplotlib histogram python-3.x

我正在使用Python(3.4)Jupyter Notebook。我在两个单独的单元格中具有以下两个直方图,每个直方图都有自己的图形:

bins = np.linspace(0, 1, 40)
plt.hist(list1, bins, alpha = 0.5, color = 'r')
Run Code Online (Sandbox Code Playgroud)

bins = np.linspace(0, 1, 40)
plt.hist(list2, bins, alpha = 0.5, color = 'g')
Run Code Online (Sandbox Code Playgroud)

是否可以将上述两个直方图作为两个子图并排放置在一个图中?

Imp*_*est 9

是的,这是可能的。请参阅以下代码。

%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()
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以为此使用matplotlib.pyplot.subplot

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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • @Tanmoy——仅仅因为提问者和你知道并不意味着这个问题的未来访问者会知道。请记住,您不仅在解决 Edamame 的问题——您还在解决可能试图完成相同任务的未来访客的问题。 (4认同)