The Python Oracle

Python - How to have same maximum on multiple histograms

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 Question
00:54 Accepted answer (Score 3)
01:58 Answer 2 (Score 1)
02:19 Thank you

--

Full question
https://stackoverflow.com/questions/5108...

Question links:
[image]: https://i.stack.imgur.com/wYKi2.png

Accepted answer links:
https://matplotlib.org/gallery/api/two_s...
[image]: https://i.stack.imgur.com/X2FeA.png

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #matplotlib #plot #histogram

#avk47



ACCEPTED ANSWER

Score 3


I'm not sure I would do that really, but if you want to I think the best way is to add two axes (also so that you can see how tall they really are). For example, see here: https://matplotlib.org/gallery/api/two_scales.html

import numpy as np
from matplotlib import pyplot as plt
fig, ax1 = plt.subplots()
ax1.hist(a, histtype='step', color='b', lw=2, density=True)
ax1.tick_params(axis='y', labelcolor='b')
ax2 = ax1.twinx()
ax2.hist(b, histtype='step', color='r', lw=2, density=True)
ax2.tick_params(axis='y', labelcolor='r')

This gives the following output (which, I think, looks worse than what you obtained; I also changed cumulative=True to density=True in the first plot to be in line with the plot you provided):

enter image description here

Also, strictly speaking this does not make sure that the maxima are really identical. If you want to do that you can force it by doing e.g.

import numpy as np
from matplotlib import pyplot as plt
fig, ax1 = plt.subplots()
n1, _, _ = ax1.hist(a, histtype='step', color='b', lw=2, density=True)
ax1.tick_params(axis='y', labelcolor='b')
ax2 = ax1.twinx()
n2, _, _ = ax2.hist(b, histtype='step', color='r', lw=2, density=True)
ax2.tick_params(axis='y', labelcolor='r')
ax1.set_ylim([0, n1.max()*1.1])
ax2.set_ylim([0, n2.max()*1.1])



ANSWER 2

Score 1


The following code would give a the same max as b:

a *= b.max()/a.max()

The cumulative flag in a might break this though and it should be placed before the histograms are generated.