首页 > 解决方案 > 使用 seaborn 联合图返回 hexbin 中的值数组

问题描述

我有一个数据集,它随着时间的推移跟踪一些位置和一些取决于位置的值,所以我想使用 seaborn 图来显示这些数据。情节如下所示:

方向和距离的直方图

这是制作它的代码。我无法共享数据集来制作它,但这是为了让您了解我在做什么。

h = sns.jointplot(data=None,x=dimerDistance,y=Orientation,
              kind='hex',cmap="gnuplot",ratio=4,
              marginal_ticks=False,marginal_kws=dict(bins=25, fill=False))


plt.suptitle('Orientation Factor - Distance Histogram of Dimer')
plt.tight_layout()
plt.xlabel('Distance [Angstrom]')
plt.ylabel('k')

我想选择一个由 hexbin 函数生成的 bin 并提取占据该 bin 的值。例如,在 x=25 和 y=1.7 左右是根据颜色图具有最高计数的 bin。我想去那个计数最高的 bin,找到这个 bin 中的 x 值和 x 的数组索引,并根据它们的共享索引找到 k 值。或者你可能会说,我想会有一些看起来像

bin[z]=[x[index1],x[index2]....x[indexn]]

其中 z 是计数最高的 bin 的索引,以便我可以制作一个新 bin

newbin=[y[index1],y[index[2]...,y[indexn]]

由于这些数据与时间相关,这些指数会告诉我系统落入垃圾箱的时间范围,所以很高兴知道这一点。我在 Stack 上做了一些窥探。我发现这篇文章似乎很有帮助。获取 matplotlib 直方图函数中的 bin 信息

有没有办法可以访问我想要在这篇文章中的信息?

标签: pythonmatplotlibseabornhistogramjointplot

解决方案


Seaborn 不返回此类数据。但 hexplot 的工作原理类似于plt.hexbin. 两者都创建一个PolyCollection,您可以从中提取值和中心。

以下是如何提取(和显示)数据的示例:

import matplotlib.pyplot as plt
import seaborn as sns

penguins = sns.load_dataset('penguins')
g = sns.jointplot(data=penguins, x="bill_length_mm", y="bill_depth_mm",
                  kind='hex', cmap="gnuplot", ratio=4,
                  marginal_ticks=False, marginal_kws=dict(bins=25, fill=False))

values = g.ax_joint.collections[0].get_array()
ind_max = values.argmax()
xy_max = g.ax_joint.collections[0].get_offsets()[ind_max]
g.ax_joint.text(xy_max[0], xy_max[1], f" Max: {values[ind_max]:.0f}\n x={xy_max[0]:.2f}\n y={xy_max[1]:.2f}",
                color='lime', ha='left', va='bottom', fontsize=14, fontweight='bold')
g.ax_joint.axvline(xy_max[0], color='red')
g.ax_joint.axhline(xy_max[1], color='red')
plt.tight_layout()
plt.show()

print(f"The highest bin contains {values[ind_max]:.0f} values")
print(f"  and has as center: x={xy_max[0]:.2f}, y={xy_max[1]:.2f}")

最高的 bin 包含 18 个值
并以:x=45.85,y=14.78 为中心

使用 hexplot 从 sns.jointplot 中提取 bin 信息


推荐阅读