1

I am plotting two normalized histograms in the same plot using axes and want to have a bin that catches any value higher than 6000. This is what I have done so far:-

fig,ax=plt.subplots(1,2)
x1 = (60, 80, 1000, 7000, 8000)
x2 = (9000, 10000, 11000, 12000, 13000)


weights1= np.ones_like(x1)/float(len(x1))
weights2= np.ones_like(x2)/float(len(x2))

bins= np.arange(0, 6000, 100)
ax[0].hist(np.clip(x1, bins[0], bins[-1]),  bins=bins,  weights=weights1, 
           alpha =.5, label = "A", color = "blue")
ax[1].hist(np.clip(x2, bins[0], bins[-1]),  bins=bins,  weights=weights2, 
           alpha =.5, label = "B", red = "red")
plt.show()

This is what I get: enter image description here

How can I change the x tick label at 6000 to 6000+ to show that it captures all observations above that?

Andy
  • 35
  • 4

1 Answers1

1

Something like this should work:

ticks, labels = plt.xticks()
labels[-1].set_text('6000+')
plt.xticks(ticks, labels)

Update: You can do it all manually:

bins= np.arange(0, 6000, 100)
plt.sca(ax[0])
plt.hist(np.clip(x1, bins[0], bins[-1]),  bins=bins,  weights=weights1, 
           alpha =.5, label = "A", color = "blue")
plt.xticks([0,2000,4000,6000], ['0','2000','4000','6000+'])

plt.sca(ax[1])
plt.hist(np.clip(x2, bins[0], bins[-1]),  bins=bins,  weights=weights2, 
           alpha =.5, label = "B", color = "red")
plt.xticks([0,2000,4000,6000], ['0','2000','4000','6000+'])

In theory this should work too, but for some reason not... If someone can shed light on this issue... ?

plt.sca(ax[1])
plt.hist(np.clip(x2, bins[0], bins[-1]),  bins=bins,  weights=weights2, 
           alpha =.5, label = "B", color = "red")
ticks, labels = plt.xticks()
labels[-1].set_text('6000+')
plt.xticks(ticks, labels)
Julien
  • 13,986
  • 5
  • 29
  • 53
  • Tried this. Does not really work. I have multiple axes (plotting 2 figures each with 2 histograms side by side) so the new xtick goes over to the next plot. Also now I see that the bar isnt really at 6000 but before that in my OP. I expect it to be at 6000. – Andy Dec 05 '19 at 00:36
  • "Also now I see that the bar isnt really at 6000 but before that" this is bacause how you defined your bins. You can either adjust that , or where you plot the bar relative to the bin center. – Julien Dec 05 '19 at 00:40
  • Ok Thanks. I guess I will read more into this. Any idea how to change the xtick label using ax and not plt? – Andy Dec 05 '19 at 00:44
  • Check update... – Julien Dec 05 '19 at 00:54
  • plt.sca is smelly code – Mad Physicist Dec 05 '19 at 01:00
  • @MadPhysicist in what way? – Julien Dec 05 '19 at 01:02
  • You're switching from the oo interface to the plt one after setting up the oo controls – Mad Physicist Dec 05 '19 at 01:41