python - Python 在悬停/单击网格时显示相应的配置文件
问题描述
我有一个value_1
取决于lon
(经度)和lat
(纬度)的二维数组。现在,我可以使用pcolormesh
在一个数字上绘制值。
但是,我有另一个 3D 数组value_2
,它取决于lon
,lat
和pressure
(压力水平)。
如果我想显示配置文件(取决于value_2
and 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])
解决方案
我确信当将鼠标悬停在 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()
推荐阅读
- docker - 当后端脚本花费太长时间时,docker返回err_empty_response
- macos - 尝试使用我的 m1 mac 运行我的 Flutter 应用程序时出错
- javascript - 进入查找复选框的 .each 函数时遇到问题
- matlab - 使用 OpenMP 在 Matlab 的 Mex 函数(Fortran)中并行化循环
- mysql - Sql Query从另一个表中获取包含多个ID的项目
- c++ - C++ 我试图结束这个无限循环以找到 0 和用户输入值之间的偶数
- csv - Jitterbit:虽然选中了“不创建 emtpy 文件”,但仅使用标题创建目标 CSV 文件
- python - Mac pip install pyodbc 失败,找不到 -lodbc 的库
- uwp - PointerReleased 在 UWP 控制之外不起作用
- r - ggplot:直方图中的 xlim 和 scale_x_continuous