绘制温度范围直方图: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()
异常效果

原因与解决方法
问题出在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
相关产品推荐
相关产品推荐

