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

标签 python matplotlib plot seaborn

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

每个 strip 图都有 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

最佳答案

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

关于Python matplotlib/Seaborn stripplot 与点之间的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44479802/

相关文章:

python - 有没有办法分离 matplotlib 图以便计算可以继续?

matlab - 在 MATLAB 中平滑 2D 图

python - 在 Python : delegating __contains__ to contained-object correctly 中模拟成员资格测试

python - 当Python中有25个单词时,如何读取文件并插入新行

python - 如何在 python 中增加查询值?

python - 在 Python 中计算时间(datetime.timedelta?)

python - 如何在 Python 上绘制数学方程式

python - 如何选择对数图中 n 个位置的刻度?

matlab - 如何在 MATLAB 中保存带有封闭框区域的图?

r - 如何删除图的轴和R中的图内容之间的图边距?