【问题标题】:Placing a histogram over scatter plot在散点图上放置直方图
【发布时间】:2014-09-10 17:41:44
【问题描述】:

我想知道 matplotlib 中是否有一种方法可以放置直方图以覆盖我在下图中的散点图所具有的点的高度?我只是想办法制作一个直方图来覆盖轴上的 10 个 bin。这是我到目前为止的代码:

bglstat = np.array([9.0, 10.0, 2.0, 7.0, 7.0, 4.0])
candyn = np.array([2.0, 2.0, 1.0, 1.0, 1.0, 3.0, 1.0, 2.0, 1.0, 1.0])
candid = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0])

fig = plt.figure()
a2 = fig.add_subplot(111)
a2.scatter(candid, candyn, color='red')
a2.set_xlabel("Candidate Bulgeless Galaxy ID #")
a2.set_ylabel("Classified as Bulgeless")
a2.set_xticks([1,2,3,4,5,6,7,8,9,10])
plt.show()

【问题讨论】:

    标签: python matplotlib histogram scatter-plot


    【解决方案1】:
    bglstat = np.array([9.0, 10.0, 2.0, 7.0, 7.0, 4.0])
    candyn = np.array([2.0, 2.0, 1.0, 1.0, 1.0, 3.0, 1.0, 2.0, 1.0, 1.0])
    candid = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0])
    
    fig = plt.figure()
    a2 = fig.add_subplot(111)
    a2.scatter(candid, candyn, color='red')
    a2.set_xlabel("Candidate Bulgeless Galaxy ID #")
    a2.set_ylabel("Classified as Bulgeless")
    a2.set_xticks([1,2,3,4,5,6,7,8,9,10])
    a2.hist(candyn, bins = arange(-.5,10.5,1))
    plt.show()
    

    给予:

    所以,很明显,答案是“是”。现在需要根据您的需要调整直方图特征。在上面的示例中,它使用与散点图数据相同的 X 和 Y 比例,但不必如此。


    或者您是否正在寻找一种使用直方图数据制作条形图的方法?那么:

    bglstat = np.array([9.0, 10.0, 2.0, 7.0, 7.0, 4.0])
    candyn = np.array([2.0, 2.0, 1.0, 1.0, 1.0, 3.0, 1.0, 2.0, 1.0, 1.0])
    candid = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0])
    
    fig = plt.figure()
    a2 = fig.add_subplot(111)
    a2.bar(candid-.8/2, candyn, width=.8)
    a2.set_xlabel("Candidate Bulgeless Galaxy ID #")
    a2.set_ylabel("Classified as Bulgeless")
    a2.set_xticks([1,2,3,4,5,6,7,8,9,10])
    plt.show()
    

    顺便说一句,set_xticks 看起来有点奇怪。您可以考虑使用 set_xticks(candid) 来显示您的类别或使用 set_xticks(np.arange(1,11)) 来明确设置刻度 1..10。另外,我建议您添加一些代码来设置范围(例如a2.set_xlim(-1,11)a2.set_ylim(0, np.max(candyn) + 1) 以控制缩放。(经验法则:如果您手动设置刻度,您也应该手动设置范围。)

    【讨论】:

    • 谢谢。我现在意识到我需要的是条形图而不是直方图。
    • 有时解决方案比 on 认为的要简单得多 :)
    猜你喜欢
    • 1970-01-01
    • 2013-08-29
    • 2015-08-27
    • 2019-12-27
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    相关资源
    最近更新 更多