如何将Matplotlib中季节子图调整为时间先后顺序排列?
问题:调整Matplotlib子图的季节排列顺序
我有一个包含4个不同站点基于季节和年份的平均浓度的DataFrame,编写的代码为每个站点生成一张图,每个季节对应一个子图,年份为x轴、浓度为y轴。当前代码自动生成的子图排列顺序为:
- fall - spring
- summer - winter
希望将其调整为时间先后顺序:
- spring - summer
- fall - winter
以下是原代码:
import pandas as pd import matplotlib.pyplot as plt import numpy as np import statsmodels.formula.api as smf import scipy.stats main_dataframe = pd.read_csv('NOx_sznl.csv') main_dataframe.rename(columns={'NOx_3168':'Banning NOx', 'NOx_2199':'Palm Springs NOx', 'NOx_2551':'El Centro NOx', 'NOx_3135':'Calexico NOx'}, inplace=True) col = list(main_dataframe.columns) col.remove('Year') col.remove('Season') for ind,station in enumerate(col): df_new = main_dataframe[['Season', 'Year', col[ind]]] ###here I tried to reorder the seasons in the dataframe df_new = df_new.set_index('Season') df_new = df_new.loc[['Spring', 'Summer', 'Fall', 'Winter'], :] df_new = df_new.reset_index() ###but it didn't change the outcome df_new = df_new.set_index('Year') # df_new['Betty Jo Mcneece Receiving Home'].astype('float') df_new[col[ind]] = df_new[col[ind]] grouped = df_new.groupby('Season') rowlength = grouped.ngroups/2 # fix up if odd number of groups fig, axs = plt.subplots(figsize=(15,10), nrows=2, ncols=int(rowlength), # fix as above gridspec_kw=dict(hspace=0.4))#, sharex='col', sharey='row') # Much control of gridspec targets = zip(grouped.groups.keys(), axs.flatten()) for i, (key, ax) in enumerate(targets): ax.plot(grouped.get_group(key)[col[ind]], marker='o', color='orange') ax.set_ylim(0,) ax.set_yticks(ax.get_yticks(),size=12) #ax.set_xlim(2009,2020) ax.set_xticks(np.arange(2009,2020,1)) ax.set_xticklabels(ax.get_xticks(), rotation = 45, size=12) fig.suptitle("%s"%col[ind], fontsize=30) # ax.set_title('%s') plt.subplot(221) plt.gca().set_title('Fall', fontsize=20) plt.subplot(222) plt.gca().set_title('Spring', fontsize=20) plt.subplot(223) plt.gca().set_title('Summer', fontsize=20) plt.subplot(224) plt.gca().set_title('Winter', fontsize=20) plt.show()
解决方案
问题核心是groupby('Season')默认按字母顺序分组,且手动设置子图标题的逻辑和期望顺序不符。需主动指定季节的遍历顺序,替代默认排序逻辑。
关键修改点:
- 定义时间顺序的季节列表:
season_order = ['Spring', 'Summer', 'Fall', 'Winter'] - 将
Season列转为有序分类类型,确保数据分组和排序都遵循指定顺序 - 直接按自定义季节列表遍历,匹配子图并动态设置标题,避免手动指定标题的顺序错误
修改后的完整代码:
import pandas as pd import matplotlib.pyplot as plt import numpy as np import statsmodels.formula.api as smf import scipy.stats main_dataframe = pd.read_csv('NOx_sznl.csv') main_dataframe.rename(columns={'NOx_3168':'Banning NOx', 'NOx_2199':'Palm Springs NOx', 'NOx_2551':'El Centro NOx', 'NOx_3135':'Calexico NOx'}, inplace=True) col = list(main_dataframe.columns) col.remove('Year') col.remove('Season') # 定义时间顺序的季节列表 season_order = ['Spring', 'Summer', 'Fall', 'Winter'] for ind, station in enumerate(col): df_new = main_dataframe[['Season', 'Year', col[ind]]] # 将Season设为有序分类,确保分组和排序遵循指定顺序 df_new['Season'] = pd.Categorical(df_new['Season'], categories=season_order, ordered=True) df_new = df_new.sort_values('Season') df_new = df_new.set_index('Year') grouped = df_new.groupby('Season') rowlength = grouped.ngroups // 2 fig, axs = plt.subplots(figsize=(15,10), nrows=2, ncols=int(rowlength), gridspec_kw=dict(hspace=0.4)) # 按自定义季节顺序遍历,匹配子图并设置标题 for season, ax in zip(season_order, axs.flatten()): group_data = grouped.get_group(season)[col[ind]] ax.plot(group_data, marker='o', color='orange') ax.set_ylim(0,) ax.set_yticks(ax.get_yticks(), size=12) ax.set_xticks(np.arange(2009,2020,1)) ax.set_xticklabels(ax.get_xticks(), rotation=45, size=12) ax.set_title(season, fontsize=20) fig.suptitle(col[ind], fontsize=30) plt.show()
内容的提问来源于stack exchange,提问作者obscuredbyclouds
相关产品推荐
相关产品推荐

