2017-06-11 45 views
2

我使用Python 3和Seaborn來製作分類條紋(請參閱下面的代碼和圖像)。Python matplotlib/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) 

我得到以下輸出enter image description here

不過,我想有一個線段連接男性和女性分。我希望這個數字看起來像這樣(見下圖)。但是,我手動繪製這些紅線,我想知道是否有一個簡單的方法來做到這一點瓦特/ Seaborn或matplotlib。謝謝! enter image description here

+0

你總是可以讓自己的包裝畫線。 – GWW

回答

3

可以使用pandas.dataframe.groupby創建FM對的列表,然後繪製對之間的段:

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