如何绘制仅包含True值的变量?Seaborn绘图问题求助
绘制仅包含True值的多变量计数图解决方案
问题场景
你当前用Seaborn绘制多变量计数图时,希望只统计Foraging、Eating等变量中值为1(对应True情况)的数量,之前尝试将列转为布尔值df['Foraging']=df['Foraging']==1但未达到预期效果,以下是可行方案:
方法1:绘图时直接过滤数据(推荐,不修改原数据集)
无需改动原DataFrame,在每个countplot中传入仅保留对应变量为1的子集数据,这样绘图时只会统计符合条件的样本:
import matplotlib.pyplot as plt import seaborn as sns fig, ax = plt.subplots(1,5,figsize=(25,5)) # 仅保留Foraging为1的行绘图 sns.countplot(x='Foraging', data=df[df['Foraging'] == 1], palette='Pastel1', ax=ax[0]) sns.countplot(x='Eating', data=df[df['Eating'] == 1], palette='Pastel1', ax=ax[1]) sns.countplot(x='Climbing', data=df[df['Climbing'] == 1], palette='Pastel1', ax=ax[2]) sns.countplot(x='Chasing', data=df[df['Chasing'] == 1], palette='Pastel1', ax=ax[3]) sns.countplot(x='Running', data=df[df['Running'] == 1], palette='Pastel1', ax=ax[4]) # 给子图添加标题,提升可读性 ax[0].set_title('Foraging (仅True值)') ax[1].set_title('Eating (仅True值)') ax[2].set_title('Climbing (仅True值)') ax[3].set_title('Chasing (仅True值)') ax[4].set_title('Running (仅True值)') fig.tight_layout() fig.show()
方法2:修改数据集后指定显示类别
如果已经将列转为布尔值(df[cols] = df[cols] == 1),countplot默认会显示True和False两类,只需通过order参数指定只展示True类别即可:
cols = ['Foraging', 'Eating', 'Climbing', 'Chasing', 'Running'] # 将目标列转为布尔值 df[cols] = df[cols] == 1 fig, ax = plt.subplots(1,5,figsize=(25,5)) # 指定order仅显示True sns.countplot(x='Foraging', data=df, palette='Pastel1', ax=ax[0], order=[True]) sns.countplot(x='Eating', data=df, palette='Pastel1', ax=ax[1], order=[True]) sns.countplot(x='Climbing', data=df, palette='Pastel1', ax=ax[2], order=[True]) sns.countplot(x='Chasing', data=df, palette='Pastel1', ax=ax[3], order=[True]) sns.countplot(x='Running', data=df, palette='Pastel1', ax=ax[4], order=[True]) fig.tight_layout() fig.show()
方法3:简洁版:直接绘制True值计数柱状图
如果不需要分5个子图,而是希望在一张图中展示所有变量的True值数量,可先计算每个变量的True值总数,再用barplot绘制:
cols = ['Foraging', 'Eating', 'Climbing', 'Chasing', 'Running'] # 计算每个变量的True值数量 true_counts = df[cols].sum().reset_index() true_counts.columns = ['行为', 'True值数量'] plt.figure(figsize=(12,5)) sns.barplot(x='行为', y='True值数量', data=true_counts, palette='Pastel1') plt.title('各行为的True值计数') plt.show()
内容的提问来源于stack exchange,提问作者Rea101
相关产品推荐
相关产品推荐

