在Python中,按特定顺序对xaxis进行分组条形图排序

2024-05-15 04:26:20 发布

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

我希望我的坐标轴的顺序是[‘好或更好’、‘公平’、‘差’、‘非常差’] 有没有什么方法可以做到这一点,而不必对我当前的代码做太多更改

data.groupby('PAVEMENT CONDITIONS')['FISCAL YEAR'].value_counts().unstack().plot.bar()
plt.title("Total data section of different years for each pavement condition")
plt.xlabel('Pavement Condition')
plt.ylabel('Number of sections')
plt.xticks(rotation=0)
plt.show()

Current Plot


Tags: of方法代码data公平顺序valueplt
1条回答
网友
1楼 · 发布于 2024-05-15 04:26:20

最简单的方法是使用^{}

ax = (
    data.groupby('PAVEMENT CONDITIONS')['FISCAL YEAR']
        .value_counts()
        .unstack()
        .reindex(['Good or Better', 'Fair', 'Poor', 'Very Poor'])  # Specify order here
        .plot.bar()
)

或者创建一个CategoricalDType和order作为Categorical Data

# Establish Categories and order
cat_type = pd.CategoricalDtype(
    categories=['Good or Better', 'Fair', 'Poor', 'Very Poor'],
    ordered=True
)

# Change Type of PAVEMENT CONDITIONS to specified Categorical Type
data['PAVEMENT CONDITIONS'] = data['PAVEMENT CONDITIONS'].astype(cat_type)
ax = (
    data.groupby('PAVEMENT CONDITIONS')['FISCAL YEAR']
        .value_counts()
        .unstack()  # Uses categorical ordering
        .plot.bar()
)

两者都产生:

plt.title("Total data section of different years for each pavement condition")
plt.xlabel('Pavement Condition')
plt.ylabel('Number of sections')
plt.xticks(rotation=0)
plt.legend(title='FISCAL YEAR', bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout()
plt.show()

plot


使用的样本数据:

np.random.seed(5)
data = pd.DataFrame({
    'FISCAL YEAR': np.random.randint(2014, 2021, 1000),
    'PAVEMENT CONDITIONS': np.random.choice(
        ['Good or Better', 'Fair', 'Poor', 'Very Poor'], 1000)
})

data.head(10)

   FISCAL YEAR PAVEMENT CONDITIONS
0         2017           Very Poor
1         2020                Fair
2         2019                Fair
3         2020      Good or Better
4         2020                Poor
5         2014                Fair
6         2015                Poor
7         2014                Poor
8         2018                Poor
9         2020                Fair

相关问题 更多 >

    热门问题