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

如何在Matplotlib的pcolor图中设置4小时间隔的HH:00格式时间刻度

自动设置pcolor图的x轴4小时时间刻度

我正在绘制某变量随时间和高度变化的pcolor图,数据点多达数千个。初始x轴仅显示数字序号:

未修改x轴刻度的图

之后我通过手动指定间隔的方式,把刻度映射为时间戳(每个数据点对应一个时间),代码如下:

num_ticks = len(Windspeed_height_plot_data)
skip_every= 600 #仅显示每第600个时间戳
ax.set_xticks(np.linspace(0, num_ticks , num_ticks +1)[::skip_every] , time_list[::skip_every], fontsize = 16)

生成的图效果有所改善:

带时间戳的图

现在我希望无需手动指定间隔数,自动让x轴每隔4小时显示HH:00格式的时间刻度。尝试了matplotlib日期模块的代码但没成功:

hours = mdates.HourLocator(interval = 1)
h_fmt = mdates.DateFormatter('%H:%M')
ax.xaxis.set_major_locator(hours)
ax.xaxis.set_major_formatter(h_fmt)
fig.autofmt_xdate()

我的完整绘图代码如下:

def time_plot(data, title, Vrange = 28, Vmin = 0):

    fig, ax = plt.subplots(figsize=(16, 4), dpi = 300)
    readings = np.shape(Windspeed_height_plot_data)[1]


    #height = readings*30+49 + 60 #y轴标签相关,无问题
    #every_nth = 5 #简化y轴标签 #y轴标签相关,无问题
    #ax.set_yticks(np.linspace(0, readings, readings+1)[::every_nth] , np.linspace(49+60, height , readings+1, dtype=int)[::every_nth],  fontsize = 16) #y轴标签相关,无问题
    
    num_ticks = len(Windspeed_height_plot_data)
    skip_every= 600 #仅显示每第600个时间戳
    ax.set_xticks(np.linspace(0, num_ticks , num_ticks +1)[::skip_every] , time_list[::skip_every], fontsize = 16)

    
    h = ax.pcolor(data, vmin = Vmin, vmax = Vrange, cmap = 'rainbow')
    plt.title(title, fontsize = 20)
    plt.xlabel("Time EST (hh:mm)", fontsize = 20)
    plt.ylabel("Height (m)", fontsize=20)
    plt.colorbar(h)
    ax.xaxis.get_offset_text().set_fontsize(18)

解决方法

之前尝试无效的核心原因:当前x轴用的是数字索引,不是matplotlib可识别的日期时间对象。要实现自动按4小时刻度显示,需把x轴数值替换为时间戳对象,再配合日期定位器和格式化器:

步骤1:将time_list转为datetime类型

先确保时间列表是matplotlib能识别的datetime对象(如果原数据是字符串格式):

# 方式1:用pandas转换
import pandas as pd
time_list = pd.to_datetime(time_list)

# 方式2:用datetime模块转换(需匹配你的时间字符串格式)
from datetime import datetime
time_list = [datetime.strptime(t, '%Y-%m-%d %H:%M') for t in time_list]

步骤2:修改绘图代码,使用日期轴

删除手动设置set_xticks的代码,改用自动日期刻度管理:

def time_plot(data, title, time_list, Vrange = 28, Vmin = 0):
    import matplotlib.dates as mdates
    
    fig, ax = plt.subplots(figsize=(16, 4), dpi = 300)
    readings = np.shape(data)[1]

    # 绘制pcolor时,指定x轴为时间对象
    h = ax.pcolor(time_list, np.arange(readings), data, vmin=Vmin, vmax=Vrange, cmap='rainbow')
    
    # 设置x轴主刻度:每隔4小时,仅显示整点
    ax.xaxis.set_major_locator(mdates.HourLocator(interval=4, byhour=[0,4,8,12,16,20]))
    # 设置刻度格式为HH:00
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
    
    # 自动旋转x轴标签避免重叠
    fig.autofmt_xdate(rotation=45, ha='right')

    plt.title(title, fontsize=20)
    plt.xlabel("Time EST (hh:mm)", fontsize=20)
    plt.ylabel("Height (m)", fontsize=20)
    plt.colorbar(h)
    ax.xaxis.get_offset_text().set_fontsize(18)

关键说明

  • 调用pcolor时传入x=time_list,让matplotlib识别x轴为日期数据,替代默认的数字索引。
  • HourLocator(interval=4, byhour=[0,4,8,12,16,20])确保只显示4小时间隔的整点,完美匹配HH:00格式需求。
  • 移除手动设置xticks的逻辑,让matplotlib自动管理刻度位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 08:03:17