2016-12-02 53 views
2

我想绘制使用条纹图的数据集。这里是头(有25列):绘制带有seaborn条纹的色调的宽矩阵

Labels Acidobacteria Actinobacteria Armatimonadetes Bacteroidetes 
0  0    0    495    NaN   27859 
1  1    0   1256    NaN   46582 
2  0    0   1081    NaN   23798 
3  1    0   2523    NaN   35088 
4  0    0   1383    NaN   19338 

我有这样的数据集存储在数据帧的大熊猫,并可以使用绘制它:

def plot(): 
    ax = sns.stripplot(data = df) 
    ax.set(xlabel='Bacteria',ylabel='Abundance') 
    plt.setp(ax.get_xticklabels(),rotation=45) 
    plt.show() 

为了生产this plot

我想设置色调以反映'Labels'列。当我尝试:

sns.stripplot(x=df.columns.values.tolist(),y=df,data=df,hue='Labels') 

我得到:

ValueError: cannot copy sequence with size 26 to array axis with dimension 830 

回答

3

所以我想通了。我不得不通过堆叠和重新索引重新安排我的数据:

cols = df.columns.values.tolist()[3:] 
stacked = df[cols].stack().reset_index() 
stacked.rename(columns={'level_0':'index','level_1':'Bacteria',0:'Abundance'},inplace=True) 

,输出:

  index   Bacteria Abundance 
0   0  Acidobacteria 0.000000 
1   0 Actinobacteria 0.005003 
2   0 Armatimonadetes 0.000000 
3   0  Bacteroidetes 0.281586 

接下来,我不得不创建一个新的列分配标签给每个数据点:

label_col = np.array([[label for _ in range(len(cols))] for label in df['Labels']]) 
label_col = label_col.flatten() 

stacked['Labels'] = label_col 

所以现在:

index   Bacteria Abundance Labels 
0  0 Acidobacteria 0.000000  0 
1  0 Actinobacteria 0.005003  0 
2  0 Armatimonadetes 0.000000  0 
3  0 Bacteroidetes 0.281586  0 
4  0  Chlamydiae 0.000000  0 

然后绘制:

def plot(): 
    ax = sns.stripplot(x='Bacteria',y='Abundance',data=stacked,hue='Labels',jitter=True) 
    ax.set(xlabel='Bacteria',ylabel='Abundance') 
    plt.setp(ax.get_xticklabels(),rotation=45) 
    plt.show() 
plot() 

生产this graph

感谢您的帮助!

+0

很好的回答!但是为了得到一个混合了色调颜色的宽矩阵矩阵,这需要很多工作......我希望Seaborn对广泛的图形有更多的支持。 –