4
votes

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 enter image description here 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
@mwaskom factorplot gives me an TypeError. The error is TypeError: object of type 'NoneType' has no len()A Gore
Hard to say what caused the error without knowing what you did.mwaskom
@mwaskom I think I got it to work using factorplot by using the code sns.factorplot(x='Marker1',col='Sex',hue='Marker2',palette='Set1',kind='count'). Thanks for your help! But, the question still remains as to why I wasn't able to use the command sns.FacetGrid().A Gore
Because FacetGrid just plots different hue layers on top of each other.mwaskom

1 Answers

5
votes

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()