绘制连接两个群图的各个数据点的彩色线

Mic*_*hlF 2 python matplotlib seaborn swarmplot

我有:

import numpy as np
import pandas as pd
import seaborn as sb
import matplotlib.pyplot as plt

# Generate random data
set1 = np.random.randint(0, 40, 24)
set2 = np.random.randint(0, 100, 24)

# Put into dataframe and plot
df = pd.DataFrame({'set1': set1, 'set2': set2})
data = pd.melt(df)
sb.swarmplot(data=data, x='variable', y='value')
Run Code Online (Sandbox Code Playgroud)

使用seaborn的swarmplot函数绘制的两个随机分布: 使用seaborns swarmplot 函数绘制的两个随机分布

我希望两个分布的各个图都用彩色线连接,以便数据框中第一个数据集的第一个数据点与第二个数据集的第一个数据点连接。我意识到如果没有seaborn,这可能会相对简单,但是我想保留各个数据点不重叠的功能。有什么方法可以访问seaborn swarmfunction 中的各个绘图坐标吗?

S.A*_*.A. 5

编辑:感谢@Mead,他在 2021 年 8 月 23 日之前指出了我的帖子中的一个错误(我忘记对先前版本中的位置进行排序)。

我尝试了保罗·布罗德森(Paul Brodersen)的精彩回答,尽管他这么说

疯狂就是这样

...我实际上认为这非常简单并且产生了很好的结果:

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

# Generate random data
rng = np.random.default_rng(42)
set1 = rng.integers(0, 40, 5)
set2 = rng.integers(0, 100, 5)

# Put into dataframe
df = pd.DataFrame({"set1": set1, "set2": set2})
print(df)
data = pd.melt(df)

# Plot
fig, ax = plt.subplots()
sns.swarmplot(data=data, x="variable", y="value", ax=ax)

# Now connect the dots
# Find idx0 and idx1 by inspecting the elements return from ax.get_children()
# ... or find a way to automate it
idx0 = 0
idx1 = 1
locs1 = ax.get_children()[idx0].get_offsets()
locs2 = ax.get_children()[idx1].get_offsets()

# before plotting, we need to sort so that the data points
# correspond to each other as they did in "set1" and "set2"
sort_idxs1 = np.argsort(set1)
sort_idxs2 = np.argsort(set2)

# revert "ascending sort" through sort_idxs2.argsort(),
# and then sort into order corresponding with set1
locs2_sorted = locs2[sort_idxs2.argsort()][sort_idxs1]

for i in range(locs1.shape[0]):
    x = [locs1[i, 0], locs2_sorted[i, 0]]
    y = [locs1[i, 1], locs2_sorted[i, 1]]
    ax.plot(x, y, color="black", alpha=0.1)
Run Code Online (Sandbox Code Playgroud)

它打印:

   set1  set2
0     3    85
1    30     8
2    26    69
3    17    20
4    17     9
Run Code Online (Sandbox Code Playgroud)

您可以看到数据在图中进行了相应链接。

在此输入图像描述

  • 这个解决方案不是只是将“set1”的最顶层点与“set2”的最顶层点连接起来吗?我不认为它成功地连接了原始数据框中占据同一行的点(这些点是随机的,因此我预计这些线会混乱)。 (2认同)
  • 现在已经修好了。非常感谢您检查它并通过评论让我/我们知道。 (2认同)