Seaborn面网格计数图色调

5
我已经为这个问题创建了一个样本数据集。
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()

这段代码创建的图形是一个堆叠图。 enter image description here 我想创建一个dodge plot(来自R)。我如何修改此代码以便可以看到Marker2存在的并排比较?

@mwaskom 我使用factorplot时遇到了TypeError错误。错误信息为TypeError: object of type 'NoneType' has no len() - A Gore
不知道你做了什么,很难说是什么导致了错误。 - mwaskom
@mwaskom 我想我已经通过使用代码 sns.factorplot(x='Marker1',col='Sex',hue='Marker2',palette='Set1',kind='count') 成功解决了问题。感谢您的帮助!但是,问题仍然存在,为什么我不能使用命令 sns.FacetGrid() - A Gore
因为FacetGrid只是在彼此之上绘制不同的色调层。 - mwaskom
1个回答

5

我曾经遇到过同样的问题,这个方法对我有用。

你可以为sns.countplot调用编写一个包装函数,以使用FacetGrid命令。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接