首页 > 解决方案 > 如何绘制分类与分类图?

问题描述

我想用第二列中的类别计数来检查类别计数(在第一列中)。我有两列:1. Max_glu_serum 类别:无、标准、<200、<300。2. 重新录取类别:否,<30,>30。

我想要一个图,以便我可以检查 '<300' 和 '>30' 的计数是多少,即有多少患者有 max_glu_serum = >300 并在 '>30' 天内重新入院

我尝试了以下代码:

sns.catplot(y=train_data_wmis['max_glu_serum'], 
        hue=train_data_wmis['readmitted'], 
        kind="count", 
        palette="pastel", edgecolor=".6", dropna=True)

但它会引发以下错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-384-1be2c9032203> in <module>
----> 1 sns.catplot(y=train_data_wmis['max_glu_serum'], hue=train_data_wmis['readmitted'], kind="count", palette="pastel", edgecolor=".6", dropna=True)

F:\Anaconda3\lib\site-packages\seaborn\categorical.py in catplot(x, y, hue, data, row, col, col_wrap, estimator, ci, n_boot, units, order, hue_order, row_order, col_order, kind, height, aspect, orient, color, palette, legend, legend_out, sharex, sharey, margin_titles, facet_kws, **kwargs)
   3750 
   3751     # Initialize the facets
-> 3752     g = FacetGrid(**facet_kws)
   3753 
   3754     # Draw the plot onto the facets

F:\Anaconda3\lib\site-packages\seaborn\axisgrid.py in __init__(self, data, row, col, hue, col_wrap, sharex, sharey, height, aspect, palette, row_order, col_order, hue_order, hue_kws, dropna, legend_out, despine, margin_titles, xlim, ylim, subplot_kws, gridspec_kws, size)
    255         # Make a boolean mask that is True anywhere there is an NA
    256         # value in one of the faceting variables, but only if dropna is True
--> 257         none_na = np.zeros(len(data), np.bool)
    258         if dropna:
    259             row_na = none_na if row is None else data[row].isnull()

TypeError: object of type 'NoneType' has no len()

有人能帮助我吗!

标签: python-3.xpandasseaborncategorical-data

解决方案


我尝试了几件事,终于找到了解决上述问题的方法。定义了以下函数:

def plot_stack(column_1, column_2):
 plot_stck=pd.crosstab(index=column_1, columns=column_2)
 plot_stck.plot(kind='bar', figsize=(8,8), stacked=True)
 return

然后,

plot_stack(train_data_wmis['max_glu_serum'], train_data_wmis['readmitted'])

输出:

“max_glu_serum”和“重新录取”的堆积图

如果可以通过 Seaborn 获得更好的解决方案,请发表评论。谢谢


推荐阅读