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

绘制温度范围直方图:X轴类别排序异常求助

温度直方图X轴排序修正方案

问题

我想要展示不同温度范围内的样本占比,但当前图表的X轴未按温度从低到高排序——最低的温度范围-5750--5000出现在X轴中间,需要调整到首位。

当前代码

fig,ax = plt.subplots(figsize=(20,10))
ax = sns.histplot(df,x='Temperature range (C)',stat='percent',ax=ax)
ax.set_yscale('log')
plt.ylabel('log(percentage samples)')
plt.gcf().autofmt_xdate()
plt.show()

异常效果

温度直方图X轴排序异常

原因与解决方法

问题出在Temperature range (C)列是字符串类型,Seaborn默认按字符串的字典序排序,而非温度数值的逻辑顺序。以下两种方法可以修复:

方法1:自动生成有序类别

通过提取温度范围的下限数值,自动排序并将列转为有序类别:

import pandas as pd

# 提取每个温度范围的起始值(如"-5750--5000"提取-5750)
df['temp_lower'] = df['Temperature range (C)'].apply(lambda x: float(x.split('--')[0]))
# 按起始温度升序获取正确的范围顺序
sorted_ranges = df.sort_values('temp_lower')['Temperature range (C)'].unique()
# 将列转为有序类别,确保绘图时按此顺序排列
df['Temperature range (C)'] = pd.Categorical(df['Temperature range (C)'], categories=sorted_ranges, ordered=True)

# 重新绘图
fig,ax = plt.subplots(figsize=(20,10))
ax = sns.histplot(df,x='Temperature range (C)',stat='percent',ax=ax)
ax.set_yscale('log')
plt.ylabel('log(percentage samples)')
plt.gcf().autofmt_xdate()
plt.show()

方法2:手动指定X轴顺序

如果温度范围是固定的,可直接手动定义排序后的列表,传给order参数:

# 按温度从低到高列出所有温度范围(替换为你的实际范围)
correct_order = ["-5750--5000", "-5000--4000", "-4000--3000", "-3000--2000", ...]

# 绘图时指定order参数
fig,ax = plt.subplots(figsize=(20,10))
ax = sns.histplot(df,x='Temperature range (C)',stat='percent',ax=ax, order=correct_order)
ax.set_yscale('log')
plt.ylabel('log(percentage samples)')
plt.gcf().autofmt_xdate()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:02:35