6

While trying to plot a cumulative distribution function (CDF) using matplotlib's hist function, the last point goes back to zero. I read some threads explaining that this is because of the histogram-like format, but couldn't find a solution for my case.

Here's my code:

import matplotlib.pyplot as plt

x = [7.845419,7.593756,7.706831,7.256211,7.147965]

fig, ax=plt.subplots()
ax.hist(x, cumulative=True, normed=1, histtype='step', bins=100, label=('Label-1'), lw=2)
ax.grid(True)
ax.legend(loc='upper left')

plt.show()

which produces the following image

enter image description here

As you can see, the stepfunction goes to zero after the last bin of the histogram, which is undesired. How can I change my code so the CDF does not go back to zero?

Thank you

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Hi @ImportanceOfBeingErnest. Thanks for your answer. I added the complete code in the question. –  Sep 05 '17 at 21:36
  • I see. I edited the question in a shape which makes the problem clear with a [mcve] of the issue. (And I would like to ask you to provide a question in that form next time asking, as it saves everyone a lot of time.) – ImportanceOfBeingErnest Sep 06 '17 at 11:22
  • See the hack given by OP https://stackoverflow.com/q/10690094/3797285 – Mohit Pandey May 21 '20 at 17:14

1 Answers1

2

One option you always have is to calculate the histogram first and then plot the result the ways you like it, instead of relying on plt.hist.

Here you would use numpy.histogram to calculate the histogram. Then you can create an array with each point repeated in it, as to obtain a step-like behaviour.

import numpy as np
import matplotlib.pyplot as plt

x = [7.845419,7.593756,7.706831,7.256211,7.147965]

h, edges = np.histogram(x, density=True, bins=100, )
h = np.cumsum(h)/np.cumsum(h).max()

X = edges.repeat(2)[:-1]
y = np.zeros_like(X)
y[1:] = h.repeat(2)

fig, ax=plt.subplots()

ax.plot(X,y,label='Label-1', lw=2)

ax.grid(True)
ax.legend(loc='upper left')
plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712