绘制概率密度图

3
我想绘制一条曲线,例如x^5 + x^4 + x^3 + x + 1,其中每个x值都来自正态分布。我有一个均值向量和一个标准差向量。
使用matplotlib.pyplot,我可以绘制平均值并绘制围绕平均值的方差,但这看起来不够优雅,并且会使输出混乱(如下图所示)。是否有其他方法来绘制密度函数?
我使用了类似于以下的代码:
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="--")

其中x是一个输入数组。


2
imshow? bar? 我们需要更多关于您的图表、其他元素以及示例的信息。提供示例代码作为起点也会有帮助。 - Thorsten Kranz
1个回答

4
最常见的方法是使用fill_between函数来填充置信区间之间的区域。例如:
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


非常感谢。这正是我正在寻找的。 - Ada Xu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接