2

我有:

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')

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

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

4

2 回答 2

3

编辑:感谢@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)

它打印:

   set1  set2
0     3    85
1    30     8
2    26    69
3    17    20
4    17     9

并且您可以看到数据在图中已相应链接。

在此处输入图像描述

于 2020-07-30T10:24:10.790 回答
2

当然,这是可能的(但你真的不想这样做)。

seaborn.swarmplot返回轴实例(此处为:)ax。您可以抓住孩子ax.get_children来获取所有情节元素。您将看到,对于每组点,都有一个 type 元素PathCollection。您可以使用该PathCollection.get_offsets()方法确定 x、y 坐标。

我不建议你这样做!疯狂就是这样。

我建议您查看源代码(在此处找到),并从中派生出您自己_PairedSwarmPlotter的代码_SwarmPlotter并将draw_swarmplot方法更改为您的需要。

于 2018-07-03T14:42:12.763 回答