python - 二维图的 1sigma 置信区域

标签 python matplotlib confidence-interval

我有两个使用 matplotlib 散点函数绘制的变量。 enter image description here

我想通过在图中突出显示 68% 的置信区域来显示它。 我知道在直方图中显示它,但我不知道如何为这样的 2D 图执行此操作 (x vs y)。在我的例子中,x 是 Massy 是 Ngal Mstar+2

我正在寻找的示例图像如下所示:

在这里,他们使用深蓝色显示了 68% 的置信区域,使用浅蓝色显示了 95% 的置信区域。

可以使用scipy.stats 模块之一实现吗?

enter image description here

最佳答案

要绘制两条曲线之间的区域,您可以使用 pyplot.fill_between()

至于您的置信区域,我不确定您想要实现什么,所以我通过修改以下代码以同步置信带为例:

https://en.wikipedia.org/wiki/Confidence_and_prediction_bands#cite_note-2

import numpy as np
import matplotlib.pyplot as plt
import scipy.special as sp

## Sample size.
n = 50

## Predictor values.
XV = np.random.uniform(low=-4, high=4, size=n)
XV.sort()

## Design matrix.
X = np.ones((n,2))
X[:,1] = XV

## True coefficients.
beta = np.array([0, 1.], dtype=np.float64)

## True response values.
EY = np.dot(X, beta)

## Observed response values.
Y = EY + np.random.normal(size=n)*np.sqrt(20)

## Get the coefficient estimates.
u,s,vt = np.linalg.svd(X,0)
v = np.transpose(vt)
bhat = np.dot(v, np.dot(np.transpose(u), Y)/s)

## The fitted values.
Yhat = np.dot(X, bhat)

## The MSE and RMSE.
MSE = ((Y-EY)**2).sum()/(n-X.shape[1])
s = np.sqrt(MSE)

## These multipliers are used in constructing the intervals.
XtX = np.dot(np.transpose(X), X)
V = [np.dot(X[i,:], np.linalg.solve(XtX, X[i,:])) for i in range(n)]
V = np.array(V)

## The F quantile used in constructing the Scheffe interval.
QF = sp.fdtri(X.shape[1], n-X.shape[1], 0.95)
QF_2 = sp.fdtri(X.shape[1], n-X.shape[1], 0.68)

## The lower and upper bounds of the Scheffe band.
D = s*np.sqrt(X.shape[1]*QF*V)
LB,UB = Yhat-D,Yhat+D
D_2 = s*np.sqrt(X.shape[1]*QF_2*V)
LB_2,UB_2 = Yhat-D_2,Yhat+D_2


## Make the plot.
plt.clf()
plt.plot(XV, Y, 'o', ms=3, color='grey')
plt.hold(True)
a = plt.plot(XV, EY, '-', color='black', zorder = 4)

plt.fill_between(XV, LB_2, UB_2, where = UB_2 >= LB_2, facecolor='blue', alpha= 0.3, zorder = 0)
b = plt.plot(XV, LB_2, '-', color='blue', zorder=1)
plt.plot(XV, UB_2, '-', color='blue', zorder=1)

plt.fill_between(XV, LB, UB, where = UB >= LB, facecolor='blue', alpha= 0.3, zorder = 2)
b = plt.plot(XV, LB, '-', color='blue', zorder=3)
plt.plot(XV, UB, '-', color='blue', zorder=3)

d = plt.plot(XV, Yhat, '-', color='red',zorder=4)

plt.ylim([-8,8])
plt.xlim([-4,4])

plt.xlabel("X")
plt.ylabel("Y")

plt.show()

输出如下所示: enter image description here

关于python - 二维图的 1sigma 置信区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25994048/

相关文章:

python - 如何更改 python 模块的名称或别名

python - Matplotlib - 尽管在 font_manager 中,但当前字体中缺少字形 8722

python-3.x - matplotlib 中如何使用 zorder?

Python/matplotlib mplot3d-如何设置 z 轴的最大值?

python - seaborn 置信区间计算正确吗?

r - 从 lme fit 中提取预测带

python - 将置信区间计算为分位数

python - numpy.random.seed 是否使结果固定在不同的计算机上?

python - 为什么这个函数没有返回值?

python - django 查询返回错误 : expected str instance, 找到 ValuesListQuerySet