Ras*_*ang 5 python matplotlib seaborn
鉴于 regplot 计算间隔和引导程序中的平均值来查找每个箱的置信区间,因此必须手动重新计算它们以进行进一步研究似乎是一种浪费,因此:
问题:如何访问正则图的计算平均值和置信区间?
示例:此代码生成一个漂亮的 bin 均值与 CI 的图:
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# just some random numbers to get started
fig, ax = plt.subplots()
x = np.random.uniform(-2, 2, 1000)
y = np.random.normal(x**2, np.abs(x) + 1)
# Manual binning to retain control
binwidth=4./10
x_bins=np.arange(-2+binwidth/2,2,binwidth)
sns.regplot(x=x, y=y, x_bins=x_bins, fit_reg=None)
plt.show()
Run Code Online (Sandbox Code Playgroud)
并不是说按箱计算平均值并不容易,而是 CI 是使用随机数计算的。最好能够访问与绘制的完全相同的数字,那么我如何访问它们呢?一定有某种我忽略的 get_* 方法。
按照 MWE 中的设置进行设置:
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# Random numbers for plotting
x = np.random.uniform(-2, 2, 1000)
y = np.random.normal(x**2, np.abs(x) + 1)
# Manual binning to retain control
binwidth = 4 / 10
x_bins = np.arange(binwidth/2 - 2, 2, binwidth)
sns.regplot(x=x, y=y, x_bins=x_bins, fit_reg=None)
Run Code Online (Sandbox Code Playgroud)
我们可以通过循环绘制的线并提取最小值和最大值(分别对应于上部和下部 CI)来提取置信区间:
ax = plt.gca()
lower = [line.get_ydata().min() for line in ax.lines]
upper = [line.get_ydata().max() for line in ax.lines]
Run Code Online (Sandbox Code Playgroud)
作为健全性检查,我们可以在原始数据之上绘制这些提取的点(此处用红叉显示):
plt.scatter(x_bins, lower, marker='x', color='C3', zorder=3)
plt.scatter(x_bins, upper, marker='x', color='C3', zorder=3)
Run Code Online (Sandbox Code Playgroud)
平均值的值可以从ax.collections以下公式中提取:
means = ax.collections[0].get_offsets()[:, 1]
Run Code Online (Sandbox Code Playgroud)
同样,作为健全性检查,我们可以将提取的值覆盖在原始图上:
plt.scatter(x_bins, means, color='C1', marker='x', zorder=3)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3485 次 |
| 最近记录: |