在散点图上放置直方图

时间:2014-07-19 19:58:30

标签: python matplotlib histogram scatter-plot

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

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

enter image description here

1 个答案:

答案 0 :(得分: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()

给出:

enter image description here

所以,显然,答案是肯定的。现在需要根据您的需要调整直方图特征。在上面的示例中,它使用与散点数据相同的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()

enter image description here

顺便说一下,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)以控制缩放。(经验法则:如果手动设置刻度,则应手动设置范围,同样。)