在 seaborn 点图中加入每个类别中的配对点

Join paired points within each category in seaborn pointplot

我有一些数据,按类别(即“a”、“b”、“c”等)分组,我想在 内的每对点之间画线 每个类别。

基本上,每个类别都有一个“之前”和“之后”的值,所以我用 hue 将它分开。这是现在的情节,但最终我希望给定类别的每个“之前”和“之后”值用一条线连接(即 a_before 连接到 a_after,b_before 关节到 b_after,等等)。

sns.pointplot (x = ‘category’, y = ‘correlation’, 
    hue = ‘time’, linestyles = ‘’, dodge = .3, data = sample_data)

我将 linestyles 设置为 '' 因为否则它会连接所有的点,而不仅仅是成对的点 points.Is seaborn 有办法做到这一点吗?

谢谢!

编辑:我希望它看起来像这样:

(我将 linestyles 设置为 '' 因为否则它会连接所有的点,而不仅仅是配对的点。)

Matplotlib 将生成的点存储到 axlines 字段中。 sns.pointplot() 始终生成(可能为空)置信区间,这些置信区间也存储在行中。相同的位置也存储在 ax.collections.

您可以遍历 collections[0]collections[1] 以访问(闪避)点的确切位置。然后,你可以在它们之间划线:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

sample_data = pd.DataFrame({'category': ['a', 'a', 'b', 'b', 'c', 'c'],
                            'correlation': [0.33, 0.58, 0.51, 0.7, 0.49, 0.72],
                            'time': ['before', 'after', 'before', 'after', 'before', 'after']})
ax = sns.pointplot(x='category', y='correlation', hue='time', palette=['skyblue', 'dodgerblue'],
                   linestyles='', dodge=.3, data=sample_data)for (x0, y0), (x1, y1) in zip(ax.collections[0].get_offsets(), ax.collections[1].get_offsets()):
    ax.plot([x0, x1], [y0, y1], color='black', ls=':', zorder=0)
ax.axhline(0, color='black', ls='--')
ax.set_ylim(-1, 1)
plt.show()