user1821176
user1821176

Reputation: 1191

Placing a histogram over scatter plot

I am wondering if there is a way in matplotlib to place a histogram to cover up to the height of the points I have for my scatter plot in the plot bellow? I'm just finding a way to make a histogram to cover the 10 bins in the axis. Here is the code I have so far:

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

Upvotes: 0

Views: 524

Answers (1)

DrV
DrV

Reputation: 23500

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

gives:

enter image description here

So, obviously, the answer is "yes". Now the histogram characteristics need to be adjusted according your needs. In the example above it uses the same X and Y scale as your scatter data, but that does not need to be the case.


Or are you looking for a way to make a bar plot with your histogram data? Then:

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

By the way, the set_xticks looks a bit odd. You might consider using set_xticks(candid) to show your categories or set_xticks(np.arange(1,11)) for explicitly setting ticks 1..10. Also, I suggest you add some code to set the extents (e.g. a2.set_xlim(-1,11), a2.set_ylim(0, np.max(candyn) + 1) to gain control over the scaling. (Rule of thumb: If you set ticks manually, you should set the extents manually, as well.)

Upvotes: 1

Related Questions