绘制有色线以连接两个swarmplot的各个数据点

时间:2018-07-03 13:05:08

标签: python matplotlib seaborn

我有:

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

The two random distributions plotted with seaborns swarmplot function

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

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

2 个答案:

答案 0 :(得分:1)

当然可以(但是您真的不想这么做)。

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

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

我建议您查看源代码(found here),然后从_PairedSwarmPlotter派生您自己的_SwarmPlotter,并根据需要更改draw_swarmplot方法。

答案 1 :(得分:1)

我尝试Paul Brodersen给出了很好的答案,尽管他这么说

疯狂就是这样

...实际上,我认为这很简单,并且会产生不错的结果:

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

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

# Put into dataframe
df = pd.DataFrame({'set1': set1, 'set2': set2})
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()

for i in range(locs1.shape[0]):
    x = [locs1[i, 0], locs2[i, 0]]
    y = [locs1[i, 1], locs2[i, 1]]
    ax.plot(x, y, color='black', alpha=0.1)

enter image description here