在海洋箱图中隐藏未观察到的类别

时间:2020-09-01 09:27:45

标签: python pandas seaborn boxplot categorical-data

我目前正在进行数据分析,并希望通过海洋箱形图显示一些数据分布。

我有一个分类数据“ seg1”,它在我的数据集中可以取3个值(“ Z1”,“ Z3”,“ Z4”)。但是,“ Z4”组中的数据太陌生,无法为我报告,我想生成仅显示“ Z1”和“ Z3”类别的箱形图。

由于没有显示数据点,仍然显示类别“ Z4”,因此无法过滤图的数据源。

除了仅创建('Z1','Z3')新的CategoricalDtype并将数据投射/投影到这个新类别上,还有其他解决方案吗?

我只想隐藏“ 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

1 个答案:

答案 0 :(得分:1)

要切断最后一个(或第一个)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