在pcolor图中使用matplotlib日期

f1tvaqid  于 2023-11-22  发布在  其他
关注(0)|答案(1)|浏览(116)

我正在生成某个变量的pcolor图,看看它在不同时间和高度上的行为。有数千个数据点,如果我们不对x轴做任何事情,它只是对它们进行编号,如下所示:


的数据
然后我继续添加以下代码行,将这些增量重新Map到时间戳(每个数据点都有一个与之关联的时间):

num_ticks = len(Windspeed_height_plot_data)
skip_every= 600 #only displays every 600th timestamp
ax.set_xticks(np.linspace(0, num_ticks , num_ticks +1)[::skip_every] , time_list[::skip_every], fontsize = 16)

字符串
制作的新情节看起来像这样,这是好得多:



我现在的问题是,我们如何使它以HH:00格式每4小时显示一次时间,而不是手动告诉它每第n次显示一次。
我尝试使用matplotlib date模块,代码如下:

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 #this is for the y axis labaels, all is fine
    #every_nth = 5 #decluters the y labels #this is for the y axis labaels, all is fine
    #ax.set_yticks(np.linspace(0, readings, readings+1)[::every_nth] , np.linspace(49+60, height , readings+1, dtype=int)[::every_nth],  fontsize = 16) #this is for the y axis labaels, all is fine
    
    num_ticks = len(Windspeed_height_plot_data)
    skip_every= 600 #only displays every 600th timestamp
    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)

yyhrrdl8

yyhrrdl81#

假设time_list由datetime组成,并且每分钟至少有一次数据,我们可以遍历它的元素并过滤这些occupational:


的数据

from datetime import datetime, timedelta

import numpy as np
from matplotlib import pyplot as plt
# generate random data and times
data = np.random.randn(900)
time_list = [datetime.now() + timedelta(minutes=i) for i in range(len(data))]
# define hour increment
delta_hours = 4

# find "delta-hour" indices and times 
filtered_indices = []
filtered_times = []
t_next = time_list[0]
for i, t in enumerate(time_list):
    if t > t_next and t.minute == 0:
        filtered_indices.append(i)
        filtered_times.append(t.strftime("%H:%M"))
        # jump to shortly before next delta_hour and find next index
        t_next = t + timedelta(hours=delta_hours) - timedelta(minutes=2)

# plot
plt.plot(data)
plt.gca().set_xticks(filtered_indices, filtered_times)
plt.show()

字符串

相关问题