Я уверен, что есть более эффективный способ получить правильные индексы при наведении на pcolormesh, но это помогает:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gs
from math import floor
# coordination
lon = np.arange(-120, -110, 1)
lat = np.arange(20, 30, 1)
# shape of value_1: (lon,lat)
# pseudocolor plot
value_1 = np.random.rand(9, 9)
pressure = np.arange(1110, 500, -100)
mlon, mlat = np.meshgrid(lon, lat)
# shape of value_2: (lon,lat,pressure)
# profile plot
# Used to plot profile when mouse hovers on one grid
value_2 = np.random.rand(9, 9, pressure.shape[0])
# global variables to keep track of which values
# are currently plotted in ax2
current_lat, curret_lon = None, None
fig, (ax1, ax2) = plt.subplots(2,1)
m = ax1.pcolormesh(mlon, mlat, value_1)
fig.colorbar(m, ax=ax1)
fig.tight_layout()
def on_move(event):
global current_lat, current_lon
if event.inaxes is ax1:
event_lat = floor(event.ydata)
event_lon = floor(event.xdata)
# find the indices corresponding to lat,lon
id_lat = np.searchsorted(lat, event_lat)
id_lon = np.searchsorted(lon, event_lon)
# only plot if we have different values than the previous plot
if id_lat != current_lat or id_lon != current_lon:
current_lat = id_lat
current_lon = id_lon
ax2.cla()
ax2.plot(value_2[id_lat, id_lon, :], pressure)
ax2.set_title("lat: {:.0f}, lon: {:.0f}".format(event_lat, event_lon))
fig.canvas.draw_idle()
cid = fig.canvas.mpl_connect('motion_notify_event', on_move)
plt.show()
