【问题标题】:Python Jupyter Notebook: Put two histogram subplots side by side in one figurePython Jupyter Notebook:将两个直方图子图并排放在一个图中
【发布时间】:2023-03-13 13:58:02
【问题描述】:

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

bins = np.linspace(0, 1, 40)
plt.hist(list1, bins, alpha = 0.5, color = 'r')

bins = np.linspace(0, 1, 40)
plt.hist(list2, bins, alpha = 0.5, color = 'g')

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

【问题讨论】:

    标签: python python-3.x matplotlib histogram


    【解决方案1】:

    您可以为此使用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()
    

    【讨论】:

    • 最好解释一下你在做什么。例如,plt.subplot 的参数对于未启动的人来说并不直观,并且通常也可以很好地包含您的导入 :-)
    • 这是@Edamame 提出的问题的解决方案,即在一个图中并排显示两个直方图作为两个子图。
    • @mgilson - Edamame 已经在使用 plt.hist。因此,他/她已经将 matplotlib.pyplot 作为 plt 导入是固有的。因此不包括导入。
    • @Tanmoy -- 仅仅因为提问者和你知道并不意味着未来的访问者会知道这个问题。请记住,您不仅要解决毛豆的问题,还要解决未来访问者可能会尝试完成同样事情的问题。
    • @mgilson:我用工作代码更新了答案(从另一个答案中摘录了一点)。正如你提到的,这个答案对我有帮助,因此对其他人也有用。
    【解决方案2】:

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

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

    【讨论】:

    • 你能解释一下你对bins:np.linspace(0, 1, 3)的表达式做了什么吗?
    • @fraxture bins 是包含直方图 bin 边缘的数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 2021-10-11
    相关资源
    最近更新 更多