Akash Kumar
Akash Kumar

Reputation: 1406

Plotting CDF of Uniform continuous distribution

I am trying to plot pdf and cdf of uniform continuous distribution. Following is the code:

from scipy.stats import uniform
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 1)

# Genrating uniform distribution
uniform_distribution = uniform.rvs(0, 1, 1000)
x = np.linspace(uniform.ppf(0.01),uniform.ppf(0.99), 1000)
ax.hist(uniform_distribution, density=True, histtype='stepfilled', alpha=0.2)

# Plotting pdf
pdf = uniform.pdf(x)
ax.plot(x, pdf, 'r-', lw=5, alpha=0.6, label='pdf')

# Plotting cdf
cdf = uniform.cdf(x)
ax.plot(x, cdf, 'k-', lw=2, label='cdf')
ax.legend(loc='best', frameon=False)

Upon experimenting with some values I am getting this right. As far as my understanding, the variable x is for x-axis values to plot pdf and cdf, which can be seen passes in both the function. The uniform_distribution variable takes the actual distribution.

But the function uniform.pdf and uniform.cdf takes x which seems unintuitive. On changing the x in both the function I get my pdf plot as it is but cdf gets distorted. Not sure what should be the exact argument of cdf and pdf function and why.

Upvotes: 1

Views: 2693

Answers (1)

David
David

Reputation: 445

You can change a and b to see different figures:

from scipy.stats import uniform
import matplotlib.pyplot as plt
import numpy as np

a, b = 1, 5
size = 1000

fig, ax = plt.subplots(1, 1)

# Genrating uniform distribution
uniform_distribution = uniform(loc=a, scale=b)
x = np.linspace(uniform_distribution.ppf(0), uniform_distribution.ppf(1), size)

# Plotting pdf
pdf = uniform_distribution.pdf(x)
ax.plot(x, pdf, 'r-', lw=5, alpha=0.6, label='pdf')

# Plotting cdf
cdf = uniform_distribution.cdf(x)
ax.plot(x, cdf, 'k-', lw=2, label='cdf')
ax.legend(loc='best', frameon=False)

# Histogram
ax.hist(uniform_distribution.rvs(size=size), density=True, histtype='stepfilled', alpha=0.2)
ax.set_ylim(-0.05, 1.05)

fig.show()

enter image description here

Upvotes: 2

Related Questions