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

Python matplotlib / Seaborn stripplot with connection between points

我正在使用 Python 3 和 Seaborn 制作分类条带图(请参见下面的代码和图像)。

每个条状图有 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)

我得到以下输出

但是,我想要一条连接公点和母点的线段。我希望这个数字看起来像这样(见下图)。但是,我手动绘制了那些红线,我想知道是否有一种简单的方法可以使用 Seaborn 或 matplotlib 来完成。谢谢!

您可以使用 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()

输出: