首页 > 解决方案 > Python 在悬停/单击网格时显示相应的配置文件

问题描述

我有一个value_1取决于lon(经度)和lat(纬度)的二维数组。现在,我可以使用pcolormesh在一个数字上绘制值。

但是,我有另一个 3D 数组value_2,它取决于lon,latpressure(压力水平)。

如果我想显示配置文件(取决于value_2and 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])

伪彩色 轮廓

标签: pythonmatplotlib

解决方案


我确信当将鼠标悬停在 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()

在此处输入图像描述


推荐阅读