Python matplotlib / Seaborn stripplot与点之间的连接

时间:2017-06-11 02:18:16

标签: python matplotlib plot seaborn

我使用Python 3和Seaborn制作绝对的stripplots(请参阅下面的代码和图片)。

每个stripplot都有2个数据点(每个性别一个)。

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


df = [["city2", "f", 300],
    ["city2", "m", 39],
    ["city1", "f", 95],
    ["city1", "m", 53]]

df = pd.DataFrame(df, columns = ["city", "gender", "variable"])

sns.stripplot(data=df,x='city',hue='gender',y='variable', size=10, linewidth=1)

我得到以下输出enter image description here

但是,我希望有一个连接男性和女性点的线段。我希望这个数字看起来像这样(见下图)。但是,我手动绘制了这些红线,我想知道是否有一种简单的方法可以使用Seaborn或matplotlib。谢谢! enter image description here

1 个答案:

答案 0 :(得分:3)

您可以使用pandas.dataframe.groupby创建一个f-m对列表,然后在对之间绘制段:

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


df = [["city2", "f", 300],
      ["city2", "m", 39],
      ["city1", "f", 95],
      ["city1", "m", 53],
      ["city4", "f", 200],
      ["city3", "f", 100],
      ["city4", "m", 236],
      ["city3", "m", 20],]


df = pd.DataFrame(df, columns = ["city", "gender", "variable"])


ax = sns.stripplot(data=df,x='city',hue='gender',y='variable', size=10, linewidth=1)

lines = ([[x, n] for n in group] for x, (_, group) in enumerate(df.groupby(['city'], sort = False)['variable']))
lc = mc.LineCollection(lines, colors='red', linewidths=2)    
ax.add_collection(lc)

sns.plt.show()

<强>输出:

enter image description here