如何将睡眠时间箱线图的X轴设置为固定1小时间隔?
解决X轴固定1小时间隔的问题
要实现X轴刻度固定1小时间隔,核心是手动指定刻度位置,替代matplotlib默认的自动刻度生成逻辑。以下是修改后的完整代码:
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import matplotlib.ticker as ticker data = {'Au cours de la semaine': ['22:30:00', '21:30:00', '23:00:00', '23:30:00', '24:30:00', '21:45:00', '23:15:00', '22:30:00', '23:45:00', '20:30:00', '22:30:00', 'missing', '21:15:00', '22:30:00', '23:45:00', '21:30:00'], 'En weekend': ['24:30:00', '23:00:00', '24:30:00', '27:00:00', '25:30:00', '21:45:00', '24:15:00', '24:30:00', '24:30:00', '21:30:00', '24:00:00', 'missing', '21:00:00', '24:30:00', '26:30:00', '23:30:00'], 'Toute la semaine': ['23:30:00', '22:15:00', '23:45:00', '25:15:00', '25:00:00', '21:45:00', '23:45:00', '23:30:00', '24:07:30', '21:00:00', '23:15:00', 'missing', '21:07:30', '23:30:00', '25:07:30', '22:30:00']} df = pd.DataFrame(data).replace('missing', pd.NA).dropna() # Convert time data to minutes for column in df.columns: df[column] = df[column].apply(lambda x: int(x.split(':')[0])*60 + int(x.split(':')[1])) # Melt the DataFrame df_melt = pd.melt(df, var_name='Category', value_name='Time') # Create a function to format x-axis ticks def format_func(value, tick_number): # Convert minutes to hours and minutes hours = int(value // 60) minutes = int(value % 60) return f"{hours}:{minutes:02d}" # Create the boxplots fig, ax = plt.subplots(figsize=(10,6)) sns.boxplot(x="Time", y="Category", data=df_melt, orient='h', ax=ax, color='lightblue') # Add means as diamond markers sns.pointplot(x="Time", y="Category", data=df_melt, orient='h', ax=ax, color='darkred', markers='D', join=False, errorbar=None) # --- 关键修改部分 --- # 计算数据覆盖的小时范围,生成每小时对应的分钟刻度位置 min_hour = df_melt['Time'].min() // 60 max_hour = df_melt['Time'].max() // 60 + 1 # 加1确保包含最大刻度边界 tick_positions = [hour * 60 for hour in range(min_hour, max_hour + 1)] # 强制使用指定的刻度位置 ax.xaxis.set_major_locator(ticker.FixedLocator(tick_positions)) ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_func)) # Set the labels plt.xlabel("Time (HH:MM)") plt.title("Boxplots of Bedtime") # Display the plot plt.show()
修改说明:
- 先通过数据的最小/最大时间计算出覆盖的小时范围,生成每个小时对应的分钟数(比如20小时对应1200分钟),确保刻度间隔严格为60分钟(1小时)。
- 使用
FixedLocator强制matplotlib使用我们定义的刻度位置,彻底替代默认的自动刻度逻辑,保证X轴间隔固定为1小时。
内容的提问来源于stack exchange,提问作者Marouane Freeman
相关产品推荐
相关产品推荐

