You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何在Matplotlib中重新排序X轴标签?

解决X轴标签排序异常问题

问题描述

我编写了如下代码绘制图表,但X轴标签未按预期升序排列:28-37.99本该位于38-47.99之前,却显示顺序错误。

原代码

fig, axes = plt.subplots(nrows=2,figsize=(15, 15))
fig.tight_layout(pad=10)

newerdf = newdf.copy()
bins = [18,28,38,48,58]
names = ['<28','28-37.99','38-47.99','48-57.99','58+']
d = dict(enumerate(names, 1))
newerdf['age'] = np.digitize(newerdf['age'], bins)
newerdf['age'] = newerdf['age'].map(d)
Graph1 = sns.lineplot(data=newerdf,x="age", y="distance",errorbar ='se',err_style='bars',ax=axes[0])
Graph2 = sns.lineplot(data=newerdf,x="age", y="duration",errorbar ='se',err_style='bars',ax=axes[1])
Graph1.set_xlabel( "Age",labelpad = 10,weight='bold')
Graph2.set_xlabel( "Age",labelpad = 10,weight='bold')
Graph1.set_ylabel("Wayfinding Distance",labelpad = 10,weight='bold')
Graph2.set_ylabel("Wayfinding Duration",labelpad = 10,weight='bold')

图表异常截图

图表截图

问题原因

映射后age列被转为字符串类型,Seaborn默认按字符串字典序排序X轴,而非我们需要的逻辑年龄区间顺序。

解决方法

提供两种可靠的调整方式:

方法1:将age设为有序分类(推荐)

在映射后添加一行代码,把age列定义为有序分类,强制指定顺序:

newerdf['age'] = pd.Categorical(newerdf['age'], categories=names, ordered=True)

方法2:绘图时指定order参数

在sns.lineplot中直接通过order参数指定X轴标签顺序:

Graph1 = sns.lineplot(data=newerdf,x="age", y="distance",errorbar='se',err_style='bars',ax=axes[0], order=names)
Graph2 = sns.lineplot(data=newerdf,x="age", y="duration",errorbar='se',err_style='bars',ax=axes[1], order=names)

修改后的完整代码(方法1示例)

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

fig, axes = plt.subplots(nrows=2,figsize=(15, 15))
fig.tight_layout(pad=10)

newerdf = newdf.copy()
bins = [18,28,38,48,58]
names = ['<28','28-37.99','38-47.99','48-57.99','58+']
d = dict(enumerate(names, 1))
newerdf['age'] = np.digitize(newerdf['age'], bins)
newerdf['age'] = newerdf['age'].map(d)
# 设置为有序分类,强制按指定顺序排列
newerdf['age'] = pd.Categorical(newerdf['age'], categories=names, ordered=True)

Graph1 = sns.lineplot(data=newerdf,x="age", y="distance",errorbar='se',err_style='bars',ax=axes[0])
Graph2 = sns.lineplot(data=newerdf,x="age", y="duration",errorbar='se',err_style='bars',ax=axes[1])

Graph1.set_xlabel( "Age",labelpad = 10,weight='bold')
Graph2.set_xlabel( "Age",labelpad = 10,weight='bold')
Graph1.set_ylabel("Wayfinding Distance",labelpad = 10,weight='bold')
Graph2.set_ylabel("Wayfinding Duration",labelpad = 10,weight='bold')

内容的提问来源于stack exchange,提问作者Caledonian26

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 04:10:32