matplotlib:如何在单击时动态更新pcolormap图

时间:2014-02-27 11:52:10

标签: python matplotlib plot

我有一个表示陆地/海洋掩模的整数数组。 我正在使用pcolormesh绘制此数组并使用Basemap覆盖海岸线。

我已经设置了一个button_press_event来捕捉图上的按钮点击次数。当使用单击按钮时,我想将原始数组中的值更改为零并更新绘图。

第一部分很简单 - 我只计算基础数据的x,y索引并更改值。但是,我无法更新pcolormesh图。这可能吗?我暂时只是简单地过度交叉,所以我可以看到底层数据的变化。

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

class ModelGrid(object):
    # Grid definition
    nx=900
    ny=412
    dx=24.00/60.00
    dy=20.00/60.00
    x0=0.00
    y0=-65.0000
    x=np.arange(nx)*dx + x0
    y=np.arange(ny)*dy + y0

    map = None

    def readgrid(self, file, dtype=np.int):
        """ Read in the mask file """
        return np.fromfile(file, dtype=dtype, sep=' ', count=nx*ny).reshape(ny,nx)

    def plot(self, fld):
        """ Plot the mask file and allow editing of points """

        print " + Loading basemap"
        if self.map is None:
            self.map = Basemap(projection='merc', resolution='l', llcrnrlat=33, llcrnrlon=42,
                        urcrnrlat=51, urcrnrlon=60, lat_ts=40)

        print " + Drawing coastlines"
        self.map.drawcoastlines()

        print " + Plotting mesh"
        mx,my = np.meshgrid(self.x, self.y)
        mx,my = self.map(mx,my)
        self.c = plt.pcolormesh(mx,my,fld)
        plt.colorbar(self.c)

        def onclick(event):
            btn = event.button

            # get location of click and turn into data indices:
            x,y = self.map(event.xdata, event.ydata, inverse=True)
            ix = int((x - self.x0) / self.dx)
            iy = int((y - self.y0) / self.dy)
            if btn == 1:
                # left button
                fld[iy,ix] = 0 # update original data array - I want this to update the pcolormesh too

                # plot a point to show where we clicked:
                px, py = self.map(self.x0 + (ix + 0.5) * self.dx, self.y0 + (iy + 0.5) * self.dy)
                self.map.plot(px, py, 'rx') 

                self.c.changed()    # I hoped this would update the pcolormesh....but no..
                event.canvas.draw() # this doesn't help either.

        # connect click singal
        cid = plt.gcf().canvas.mpl_connect("button_press_event", onclick)
        plt.show()

        return fld

0 个答案:

没有答案