我有一个二维数组value_1
,它取决于lon
(经度)和lat
(纬度)。
现在,我可以使用pcolormesh
将值绘制在一个图形上。
但是,我还有另一个3D数组value_2
,它取决于lon
,lat
和pressure
(压力级别)。
如果我想显示配置文件(取决于value_2
和pressure
)并像这样进行协调:(-120,20)
,当鼠标悬停或单击一个网格(lon,lat)时,我该怎么做?
下面是绘制pseudocolor plot
和profile plot
的示例:
import numpy as np
import matplotlib.pyplot as plt
# 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)
lon,lat = np.meshgrid(lon,lat)
plt.pcolormesh(lon,lat,value_1)
plt.colorbar()
plt.show()
# 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])
答案 0 :(得分:2)
我确信将鼠标悬停在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()