gpt4 book ai didi

python - 在 seaborn stripplot 中绘制带有色调的宽矩阵

转载 作者:行者123 更新时间:2023-11-28 22:32:25 28 4
gpt4 key购买 nike

我正在尝试使用 stripplot 绘制数据集。这是头部(有 25 列):

    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

我将这个数据集存储在 pandas DataFrame 中,可以使用以下方法绘制它:

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

生产this plot .

我想设置色调以反射(reflect) '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

最佳答案

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

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 .

感谢您的帮助!

关于python - 在 seaborn stripplot 中绘制带有色调的宽矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40935925/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com