Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting a probability density

I want plot of a curve say x^5 + x^4 + x^3 + x + 1 each point x has been taken from a normal distribution. I have a vector of means and a vector of sigma values.

Using matplotlib.pyplot I can plot the mean values and I can plot variance around the mean but it doesn't look elegant and clutters the outputHere dashed yellow line is the variance and red line is the mean.

Is there any other way to plot the density function?

I used something like this :

mu = [mu1, mu2, mu3..]
sigma = [sigma1, sigma2, sigma3..]
variance1 = [mu1+sigma1, mu2+sigma2, ..]
variance2 = [mu1-sigma1, mu2-sigma2,..]


import matplotlib.pyplot as plt
plt.plot(x,mu)
plt.plot(x,variance1, ls = "--")
plt.plot(x,variance2,ls="--")

where x is an array of inputs.

like image 553
Ada Xu Avatar asked Nov 23 '25 13:11

Ada Xu


1 Answers

The most common way is to use fill_between to shade the area between the confidence intervals. For example:

import numpy as np
np.random.seed(1977)
import matplotlib.pyplot as plt

# Generate data...
x_obs = np.linspace(-2, 2, 20)
true_model = [0.2, -0.1, 4, 2, 1, 0]

noise = np.random.normal(0, 5, x_obs.shape)
y_obs = np.polyval(true_model, x_obs) + noise

# Fit to a 5-th order polynomial
fit_model = np.polyfit(x_obs, y_obs, 5)

x = np.linspace(-3, 3, 100)
y_true = np.polyval(true_model, x)
y_pred = np.polyval(fit_model, x)

# Made up confidence intervals (I'm too lazy to do the math...)
high_bound = y_pred + 3 * (0.5 * x**4 + 3)
low_bound = y_pred - 3 * (0.5 * x**4 + 3)

# Plot the results...
fig, ax = plt.subplots()
ax.fill_between(x, high_bound, low_bound, color='gray', alpha=0.5)
ax.plot(x_obs, y_obs, 'ko', label='Observed Values')
ax.plot(x, y_pred, 'k--', label='Predicted Model')
ax.plot(x, y_true, 'r-', label='True Model')
ax.legend(loc='upper left')
plt.show()

enter image description here

like image 81
Joe Kington Avatar answered Nov 27 '25 14:11

Joe Kington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!