首页 > 解决方案 > 在创建计数图 ( ) 时为分类数据设置顺序会导致错误的图

问题描述

我的数据框中有一列针对不同年龄组,其中包含 174 行数据。示例如下: 在此处输入图像描述

我打印此列的 countplot() 的代码如下:

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

sns.set(rc = {'figure.figsize':(15,8)})
sns.countplot(data = variable, x = 'Q2')
plt.title("Respondents as per age group")

结果输出为: 按年龄组划分的受访者人数

可以看出,x轴上的类别顺序不正确。

我使用以下代码设置顺序:

age_order = ['15-19','20-29','30-39','40-49','50-59','60 and above']
sns.countplot(x = 'Q2', data = variable, order = age_order)
plt.title("Respondents as per age group")

但结果是:

按年龄组划分的受访者人数

这显然是不正确的。

我不知道为什么会发生这种情况以及如何纠正这种情况。

标签: pythonseaborncategorical-data

解决方案


推荐阅读