首页 > 解决方案 > 切换 seaborn x 和 y 轴,但计算原始方向的标准偏差

问题描述

我在一个简单的 pandas 表中有两列数据:深度和基准。每个深度有多个样本。使用 seaborn 的 relplot,我可以使用以下方法生成漂亮的数据图:

import seaborn as sns
sns.relplot(x='depth', y='datum', ci='sd', kind='line', data=myData)

这按预期工作。但是,深度位于 y 轴上更有意义,因为它更忠实地代表了地球。如果我告诉 seaborn 像这样交换轴:

sns.relplot(y='depth', x='datum', ci='sd', kind='line', data=myData)

当然,它不起作用,因为标准偏差是相对于 x 轴计算的。有没有办法交换轴,但计算和绘制相对于现在 y 轴的标准偏差?

标签: pythonseaborn

解决方案


我找到了解决方案。我从 seaborn 的源代码中复制了相关位并对其进行了更改。

grouped = myData['myColumn'].groupby(myData['depth'])
est = grouped.agg("mean")
sd = grouped.std()
cis = pd.DataFrame(np.c_[est - sd, est + sd], index=est.index, columns=["low", "high"]).stack()
if cis.notnull().any():
    cis = cis.unstack().reindex(est.index)
else:
    cis = None
x = est.index
y = est
y_ci = cis
x, y = np.asarray(x), np.asarray(y)
low, high = np.asarray(y_ci["low"]), np.asarray(y_ci["high"])
fig = plt.figure(figsize=(8, 8))
ax = fig.gca()
plt.plot(y, x)
plt.fill_betweenx(x, low, high, alpha=0.2)
plt.gca().invert_yaxis()
plt.xlabel('My Column [units]')
plt.ylabel('Depth [m]')

有些变量有点多余,但这是为了避免更改 seaborn 的代码并引入无意的错误。


推荐阅读