gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:34:53 25 4
gpt4 key购买 nike

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

每个 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

最佳答案

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com