Matplotlib自定义X轴刻度异常:刻度挤向左侧如何均匀分布?
解决Matplotlib自定义刻度拥挤问题
你的问题出在自定义刻度值和当前x轴范围不匹配:默认情况下plt.plot(df["available"])会用DataFrame的索引作为x轴(比如示例数据只有5条,x轴范围是0-4),但你设置的刻度是0-23,这些数值远大于当前x轴的最大范围,所以所有刻度都挤在左侧可见区域。
下面提供两种针对性解决方法:
方法1:按小时聚合数据(推荐,更贴合业务逻辑)
如果你的数据是分钟级的全天数据,先提取时间中的小时信息,按小时聚合后再绘图,这样x轴天然对应0-23的小时刻度:
import pandas as pd import matplotlib.pyplot as plt # 转换timestamp为时间格式,提取小时 df['timestamp'] = pd.to_datetime(df['timestamp']) df['hour'] = df['timestamp'].dt.hour # 按小时聚合(这里取每个小时的可用物品平均值,也可根据需求用sum/last等) hourly_available = df.groupby('hour')['available'].mean() # 绘图,x轴直接对应0-23的小时 plt.plot(hourly_available.index, hourly_available.values) plt.xlabel('Time (Hour)') plt.ylabel('# of available items') plt.xticks(range(24)) plt.show()
方法2:保留原始分钟数据,映射刻度位置到数据范围
如果需要保留所有原始数据点,仅在x轴显示0-23的小时标签,需要把刻度位置映射到数据的索引范围上:
import matplotlib.pyplot as plt total_points = len(df) # 计算24个刻度在数据索引中的均匀分布位置 tick_positions = [i * total_points / 24 for i in range(24)] plt.plot(df["available"]) plt.xlabel('Time (Hour)') plt.ylabel('# of available items') # 设置刻度位置为映射后的索引,标签为0-23 plt.xticks(tick_positions, range(24)) # 确保x轴覆盖所有数据点 plt.xlim(0, total_points - 1) plt.show()
内容的提问来源于stack exchange,提问作者usoysal
相关产品推荐
相关产品推荐

