Seaborn Facetgrid countplot hue

烂漫一生 提交于 2020-04-14 08:22:10

问题


I have created a sample data set for this quesition

import pandas as pd
from pandas import DataFrame
import seaborn as sns
import numpy as np


sex = np.array(['Male','Female'])
marker1 = np.array(['Absent','Present'])
marker2 = np.array(['Absent','Present'])

sample1 = np.random.randint(0,2,100)
sample2 = np.random.randint(0,2,100)
sample3 = np.random.randint(0,2,100)

df=pd.concat([pd.Series(sex.take(sample1),dtype='category'),pd.Series(marker1.take(sample2),dtype='category'),pd.Series(marker2.take(sample3),dtype='category')],axis=1)

df.rename(columns={0:'Sex',1:'Marker1',2:'Marker2'},inplace=True)

fig =sns.FacetGrid(data=df,col='Sex',hue='Marker2',palette='Set1',size=4,aspect=1).map(sns.countplot,'Marker1',order=df.Marker1.unique()).add_legend()

The plot this code creates is a stacked plot What I want to create is a dodge plot (from R). How can I modify this code so that I can see a side by side comparison of Marker2 presence?


回答1:


I had the same problem and this worked for me.

You can just write a wrapper function for your sns.countplot call to use the FacetGrid command.

def countplot(x, hue, **kwargs):
    sns.countplot(x=x, hue=hue, **kwargs)

grid = sns.FacetGrid(data=df,col='Sex',size=4,aspect=1)
fig = grid.map(countplot,'Marker1','Marker2',palette='Set1',order=df.Marker1.unique())
fig.add_legend()


来源:https://stackoverflow.com/questions/37331937/seaborn-facetgrid-countplot-hue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!