在seaborn箱线图中隐藏未观察到的类别

2024-06-07 06:00:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在进行数据分析,希望通过seaborn箱线图显示一些数据分布

我有一个分类数据“seg1”,它可以在我的数据集中取3个值(“Z1”、“Z3”、“Z4”)。然而,组“Z4”中的数据对我来说太离奇了,所以我想制作只显示类别“Z1”和“Z3”的箱线图

过滤绘图的数据源不起作用,因为类别“Z4”仍然显示,没有数据点

除了必须创建一个新的CategoricalDtype并且只使用('Z1','Z3')并将我的数据投射回这个新类别之外,还有其他解决方案吗

我只想隐藏'Z4'类别

我使用的是seaborn 0.10.1和matplotlib 3.3.1

提前感谢您的回答

下面是我的尝试,还有一些数据需要复制

虚拟数据

dummy_cat = pd.CategoricalDtype(['a', 'b', 'c'])
df = pd.DataFrame({'col1': ['a', 'b', 'a', 'b'], 'col2': [12., 5., 3., 2]})
df.col1 = df.col1.astype(dummy_cat)
sns.boxplot(data=df, x='col1', y='col2')

dummy data

不应用过滤器

fig, axs = plt.subplots(figsize=(8, 25), nrows=len(indicators2), squeeze=False)
for j, indicator in enumerate(indicators2):
    sns.boxplot(data=orders, y=indicator, x='seg1', hue='origin2', ax=axs[j, 0], showfliers=False)

产生:

Non filtered data

筛选数据源

mask_filter = orders.seg1.isin(['Z1', 'Z3'])

fig, axs = plt.subplots(figsize=(8, 25), nrows=len(indicators2), squeeze=False)
for j, indicator in enumerate(indicators2):
    sns.boxplot(data=orders.loc[mask_filter], y=indicator, x='seg1', hue='origin2', ax=axs[j, 0], showfliers=False)

产生:

Filter data source


Tags: 数据falsedfdata类别indicatorcol1sns
1条回答
网友
1楼 · 发布于 2024-06-07 06:00:50

要切断最后一个(或第一个)x值,可以使用set_xlim(),例如ax.set_xlim(-0.5, 1.5)

另一个选项是使用seaborn的order=参数,只在该列表中添加所需的值。(可选)可以通过编程方式创建:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

dummy_cat = pd.CategoricalDtype(['a', 'b', 'c'])
df = pd.DataFrame({'col1': ['a', 'b', 'a', 'b'], 'col2': [12., 5., 3., 2]})
df.col1 = df.col1.astype(dummy_cat)
order = [cat for cat in dummy_cat.categories if df['col1'].str.contains(cat).any()]
sns.boxplot(data=df, x='col1', y='col2', order=order)
plt.show()

example plot

相关问题 更多 >