matplotlib等高线图插值z值

时间:2017-06-29 16:02:59

标签: python matplotlib

我使用matplotlib创建cs = ax.contour(x, y, z)等高线图,返回QuadContourSet个对象。我使用motion_notify_event截取鼠标事件,这样可以获得x - 值和y - 值event.xdataevent.ydata。鼠标光标的xy坐标是否也可以获得与轮廓图对应的插值z - 值(来自返回的QuadContourSet对象)?我已经搜索过了,但QuadContourSet可用的文档不多。或者我是否必须以原始的z值数组手动计算它?我认为在一般情况下这可能不是很容易,例如对数缩放轴等。或者是否有任何可以帮助我的提示?

1 个答案:

答案 0 :(得分:0)

最后,我必须自己插值。就我使用线性轴而言,即使对于非常稀疏的网格,这也非常有效。请注意,下面是我对双线性插值的天真尝试,如果你碰巧有更好的算法(请不要像scipy等其他依赖),请发布它。我还没有在对数轴上测试过这个...

# note that z-data are indexed with pair (y, x) rather than (x, y)
pos = event.inaxes.transAxes.inverted().transform([event.x, event.y])
# relative coordinates in <0, 1>
rx = pos[0] * (self.__data.shape[1] - 1)
ry = pos[1] * (self.__data.shape[0] - 1)
# calculate the corner coordinates
rxLow, rxHigh = math.floor(rx), math.ceil(rx)
ryLow, ryHigh = math.floor(ry), math.ceil(ry)
# weights based on the distance
wxLow, wyLow = 1.0 - rx + rxLow, 1.0 - ry + ryLow
wxHigh, wyHigh = 1.0 - rxHigh + rx, 1.0 - ryHigh + ry
# adjust in case rxLow == rxHigh or ryLow == ryHigh
wx = wxLow + wxHigh
wy = wyLow + wyHigh
wxLow /= wx
wxHigh /= wx
wyLow /= wy
wyHigh /= wy
# get the corner data
z00 = self.__data[ryLow, rxLow]
z01 = self.__data[ryHigh, rxLow]
z10 = self.__data[ryLow, rxHigh]
z11 = self.__data[ryHigh, rxHigh]
# interpolate
zxLow = z00 * wyLow + z01 * wyHigh
zxHigh = z10 * wyLow + z11 * wyHigh
z = zxLow * wxLow + zxHigh * wxHigh  # the interpolated value