Example #1
0
class mch_animation(object):
    """docstring for MCH animation"""

    figsize = (8, 6)

    font_fixed = plt.matplotlib.font_manager.FontProperties()
    font_fixed.set_family('monospace')

    font_label_it = plt.matplotlib.font_manager.FontProperties()
    font_label_it.set_size(8)
    font_label_it.set_slant('oblique')

    font_label = plt.matplotlib.font_manager.FontProperties()
    font_label.set_size(8)

    def __init__(self, ncfile, framedir, grdfile=None):
        self.ncfile = ncfile
        self.nc = netCDF.Dataset(ncfile)
        self.framedir = framedir

        if grdfile is None:
            self.ncg = self.nc
        else:
            self.ncg = netCDF.Dataset(grdfile)

        self.dates = netCDF.num2date(self.nc.variables['ocean_time'][:],
                                    'seconds since 1970-01-01')
        self.basemap = Basemap(llcrnrlon=-95.1,
                                llcrnrlat=27.25,
                                urcrnrlon=-87.5,
                                urcrnrlat=30.95,
                                projection='lcc',
                                lat_0=30.0,
                                lon_0=-90.0,
                                resolution ='i',
                                area_thresh=0.)

        os.system('mkdir %s' % self.framedir)
        self.frame = 0

    def new_frame(self, n):
        """docstring for new_frame"""
        self.n = n

        # set up figure and axis
        self.fig = plt.figure(figsize=self.figsize)
        self.ax = self.fig.add_axes([-0.01, 0.27, 1.01, 0.73])

        self.basemap.drawcoastlines(linewidth=0.25, color='k')
        self.basemap.fillcontinents(color='0.7')
        self.basemap.drawmeridians(range(-97, -85, 1), labels=[0, 0, 0, 0],
                                  color='0.5', linewidth=0.25)
        self.basemap.drawparallels(range(25, 32, 1), labels=[0, 0, 0, 0],
                                  color='0.5', linewidth=0.25)

        # get and plot date
        #datestr = str(n)
        datestr = self.dates[self.n].strftime('%Y %b %d %H:%M GMT')
        plt.text(0.02, 0.24, datestr+' ',
                fontproperties=self.font_fixed,
                horizontalalignment='left',
                verticalalignment='top',
                transform=self.fig.transFigure,
                fontsize=12)

    def close_frame(self):

        self.ax.set_axis_off()
        plt.savefig('%s/frame_%04d.png' % (self.framedir, self.frame), dpi=100)
        print ' ... wrote frame ', self.frame
        self.frame += 1
        plt.close(self.fig)

    def plot_vector_surface(self):
        decimate_factor = 60

        if self.frame == 0:
            lon = self.ncg.variables['lon_psi'][:]
            lat = self.ncg.variables['lat_psi'][:]
            xv, yv = self.basemap(lon, lat)
            self.xv, self.yv = xv, yv
            maskv = self.ncg.variables['mask_psi'][:]
            self.anglev = shrink(self.ncg.variables['angle'][:], xv.shape)
            idx, idy = np.where(maskv == 1.0)
            idv = np.arange(len(idx))
            np.random.shuffle(idv)
            Nvec = len(idx) / decimate_factor
            idv = idv[:Nvec]
            self.idx = idx[idv]
            self.idy = idy[idv]
            # save the grid locations as JSON file
            out_grdfile = 'grd_locations.json'
            grd = {'lon': lon[self.idx, self.idy].tolist(),
                   'lat': lat[self.idx, self.idy].tolist()}
            write_vector(grd, out_grdfile)
 
        u = self.nc.variables['u'][self.n, -1, :, :]
        v = self.nc.variables['v'][self.n, -1, :, :]
        u, v = shrink(u, v)
        u, v = rot2d(u, v, self.anglev)

        self.q = self.ax.quiver(self.xv[self.idx, self.idy],
        self.yv[self.idx, self.idy],
                                u[self.idx, self.idy],
                                v[self.idx, self.idy],
                                scale=20.0, pivot='middle',
                                zorder=1e35, alpha=0.25,
                                width=0.003)

        self.ax.quiverkey(self.q, 0.8, 0.90,
                          0.5, r'0.5 m s$^{-1}$', zorder=1e35)
        self.basemap.set_axes_limits(ax=self.ax)

        datestr = self.dates[self.n].strftime('%Y %b %d %H:%M GMT')
        vector = {'date': self.dates[self.n].isoformat(),
                  'u': u[self.idx, self.idy].tolist(),
                  'v': v[self.idx, self.idy].tolist()}
        return vector

    def __del__(self):
        """docstring for __del__"""
        self.nc.close()
        self.ncg.close()
Example #2
0
class map(object):

    def __init__(self, grid=None, llcrnrlon=-180, llcrnrlat=-40, urcrnrlon=180,
                 urcrnrlat=40, proj='lcc', resolution='c', figsize=(8., 6.),
                 dlat=1, dlon=2, fig=None, ax=None, fill_color="aqua"):
        """
        map class for abstracting the basemap methods for quick and easy creation
        of geographically referenced data figures


        Parameters
        ----------
        grid: seapy.model.grid or string, optional:
            grid to use to define boundaries
        llcrnrlon: float, optional
            longitude of lower, left corner
        llcrnrlat: float, optional
            latitude of lower, left corner
        urcrnrlon: float, optional
            longitude of upper, right corner
        urcrnrlat: float, optional
            latitude of upper, right corner
        proj: string, optional
            projection to use for map
        resolution: character
            resolution to use for coastline, etc. From Basemap:
            'c' (crude), 'l' (low), 'i' (intermediate),
            'h' (high), 'f' (full), or None
        figsize: list, optional
            dimensions to use for creation of figure
        dlat: float, optional
            interval to mark latitude lines (e.g., if dlat=0.5 every 0.5deg mark)
        dlon: float, optional
            interval to mark longitude lines (e.g., if dlon=0.5 every 0.5deg mark)
        fig: matplotlib.pyplot.figure object, optional
            If you want to plot on a pre-configured figure, pass the figure object
            along with the axis object.
        ax: matplotlib.pyplot.axis object, optional
            If you want to plot on a pre-configured figure, pass the axis object
            along with the figure object.
        fill_color: string, optional
            The color to use for the axis background

        Returns
        -------
        None

        """
        if grid is not None:
            grid = asgrid(grid)
            llcrnrlat = np.min(grid.lat_rho)
            urcrnrlat = np.max(grid.lat_rho)
            llcrnrlon = np.min(grid.lon_rho)
            urcrnrlon = np.max(grid.lon_rho)

        self.basemap = Basemap(llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat,
                               urcrnrlon=urcrnrlon, urcrnrlat=urcrnrlat,
                               projection=proj,
                               lat_0=urcrnrlat - (urcrnrlat - llcrnrlat) / 2.,
                               lon_0=urcrnrlon - (urcrnrlon - llcrnrlon) / 2.,
                               resolution=resolution, area_thresh=0.0, ax=ax)

        self.figsize = figsize
        self.dlon = dlon
        self.dlat = dlat
        self.fig = fig
        self.ax = ax
        self.fill_color = fill_color
        reset = True if fig is None else False
        self.new_figure(reset=reset)

    def new_figure(self, fill_color=None, reset=False):
        """
        Create or update a figure for plotting

        Parameters
        ----------
        fill_color: string, optional
           Color to fill the background of the axes with
        reset: bool, optional
           Reset the figure
        """
        if reset:
            if self.ax:
                self.ax.set_axis_off()
            if self.fig:
                plt.close(self.fig)

        if self.fig is None or self.ax is None:
            self.fig = plt.figure(figsize=self.figsize)
            self.ax = self.fig.add_axes([-0.01, 0.25, 1.01, 0.7])

        if fill_color is None:
            fill_color = self.fill_color

        self.basemap.drawmapboundary(fill_color=fill_color)
        # Create the longitude lines
        nticks = int((self.basemap.urcrnrlon - self.basemap.llcrnrlon) /
                     self.dlon)
        md = np.mod(self.basemap.llcrnrlon, self.dlon)
        if md:
            slon = self.basemap.llcrnrlon + self.dlon - md
        else:
            slon = self.basemap.llcrnrlon
            nticks += 1
        lon_lines = np.arange(nticks) * self.dlon + slon
        self.basemap.drawmeridians(lon_lines, color="0.5",
                                   linewidth=0.25, dashes=[1, 1, 0.1, 1],
                                   labels=[0, 0, 0, 1], fontsize=12)

        # Create the latitude lines
        nticks = int((self.basemap.urcrnrlat - self.basemap.llcrnrlat) /
                     self.dlat)
        md = np.mod(self.basemap.llcrnrlat, self.dlat)
        if md:
            slat = self.basemap.llcrnrlat + self.dlat - md
        else:
            slat = self.basemap.llcrnrlat
            nticks += 1
        lat_lines = np.arange(nticks) * self.dlat + slat
        self.basemap.drawparallels(lat_lines, color="0.5",
                                   linewidth=0.25, dashes=[1, 1, 0.1, 1],
                                   labels=[1, 0, 0, 0], fontsize=12)

    def land(self, color="black"):
        """
        Draw the land mask

        Parameters
        ----------
        color: string, optional
            color to draw the mask with
        """
        self.basemap.drawcoastlines()
        self.basemap.drawcountries()
        self.basemap.fillcontinents(color=color)

    def zoom(self, xrange, yrange):
        """
        zoom the figure to a specified lat, lon range

        Parameters
        ----------
        xrange: array
            minimum and maximum longitudes to display
        yrange: array
            minimum and maximum latitudes to display
        """
        x, y = self.basemap(xrange, yrange)
        self.ax.set_xlim(x)
        self.ax.set_ylim(y)
        self.fig.canvas.draw()

    def pcolormesh(self, lon, lat, data, **kwargs):
        """
        pcolormesh field data onto our geographic plot

        Parameters
        ----------
        lon: array
            Longitude field for data
        lat: array
            Latitude field for data
        data: array
            data to pcolor
        **kwargs: arguments, optional
            additional arguments to pass to pcolor
        """
        # Pcolor requires a modification to the locations to line up with
        # the geography
        dlon = lon * 0
        dlat = lat * 0
        dlon[:, 0:-1] = lon[:, 1:] - lon[:, 0:-1]
        dlat[0:-1, :] = lat[1:, :] - lat[0:-1, :]
        x, y = self.basemap(lon - dlon * 0.5, lat - dlat * 0.5)
        self.pc = self.ax.pcolormesh(x, y, data, **kwargs)

    def scatter(self, lon, lat, data, **kwargs):
        """
        scatter plot data onto our geographic plot

        Parameters
        ----------
        lon: array
            Longitude field for data
        lat: array
            Latitude field for data
        data: array
            data to pcolor
        **kwargs: arguments, optional
            additional arguments to pass to pcolor
        """
        x, y = self.basemap(lon, lat)
        self.pc = self.ax.scatter(x, y, c=data, **kwargs)

    def colorbar(self, label=None, cticks=None, **kwargs):
        """
        Display a colorbar on the figure

        Parameters
        ----------
        label: string, optional
            Colorbar label title
        cticks: array, optional
            Where to place the tick marks and values for the colorbar
        **kwargs: arguments, optional
            additional arguments to pass to colorbar
        """
        self.cax = self.fig.add_axes([0.25, 0.16, 0.5, 0.03])
        self.cb = plt.colorbar(self.pc, cax=self.cax, orientation="horizontal",
                               ticks=cticks, **kwargs)
        self.basemap.set_axes_limits(ax=self.ax)
        if label is not None:
            self.cb.set_label(label)
Example #3
0
class mch_animation(object):
    """docstring for MCH animation"""

    figsize = (8, 6)

    font_fixed = plt.matplotlib.font_manager.FontProperties()
    font_fixed.set_family('monospace')

    font_label_it = plt.matplotlib.font_manager.FontProperties()
    font_label_it.set_size(8)
    font_label_it.set_slant('oblique')

    font_label = plt.matplotlib.font_manager.FontProperties()
    font_label.set_size(8)

    def __init__(self, ncfile, framedir, grdfile=None):
        self.ncfile = ncfile
        self.nc = netCDF.Dataset(ncfile)
        self.framedir = framedir

        if grdfile is None:
            self.ncg = self.nc
        else:
            self.ncg = netCDF.Dataset(grdfile)

        self.dates = netCDF.num2date(self.nc.variables['ocean_time'][:],
                                     'seconds since 1970-01-01')
        self.basemap = Basemap(llcrnrlon=-95.1,
                               llcrnrlat=27.25,
                               urcrnrlon=-87.5,
                               urcrnrlat=30.95,
                               projection='lcc',
                               lat_0=30.0,
                               lon_0=-90.0,
                               resolution='i',
                               area_thresh=0.)

        os.system('mkdir %s' % self.framedir)
        self.frame = 0

    def new_frame(self, n):
        """docstring for new_frame"""
        self.n = n

        # set up figure and axis
        self.fig = plt.figure(figsize=self.figsize)
        self.ax = self.fig.add_axes([-0.01, 0.27, 1.01, 0.73])

        self.basemap.drawcoastlines(linewidth=0.25, color='k')
        self.basemap.fillcontinents(color='0.7')
        self.basemap.drawmeridians(range(-97, -85, 1),
                                   labels=[0, 0, 0, 0],
                                   color='0.5',
                                   linewidth=0.25)
        self.basemap.drawparallels(range(25, 32, 1),
                                   labels=[0, 0, 0, 0],
                                   color='0.5',
                                   linewidth=0.25)

        # get and plot date
        #datestr = str(n)
        datestr = self.dates[self.n].strftime('%Y %b %d %H:%M GMT')
        plt.text(0.02,
                 0.24,
                 datestr + ' ',
                 fontproperties=self.font_fixed,
                 horizontalalignment='left',
                 verticalalignment='top',
                 transform=self.fig.transFigure,
                 fontsize=12)

    def close_frame(self):

        self.ax.set_axis_off()
        plt.savefig('%s/frame_%04d.png' % (self.framedir, self.frame), dpi=100)
        print ' ... wrote frame ', self.frame
        self.frame += 1
        plt.close(self.fig)

    def plot_vector_surface(self):
        decimate_factor = 60

        if self.frame == 0:
            lon = self.ncg.variables['lon_psi'][:]
            lat = self.ncg.variables['lat_psi'][:]
            xv, yv = self.basemap(lon, lat)
            self.xv, self.yv = xv, yv
            maskv = self.ncg.variables['mask_psi'][:]
            self.anglev = shrink(self.ncg.variables['angle'][:], xv.shape)
            idx, idy = np.where(maskv == 1.0)
            idv = np.arange(len(idx))
            np.random.shuffle(idv)
            Nvec = len(idx) / decimate_factor
            idv = idv[:Nvec]
            self.idx = idx[idv]
            self.idy = idy[idv]
            # save the grid locations as JSON file
            out_grdfile = 'grd_locations.json'
            grd = {
                'lon': lon[self.idx, self.idy].tolist(),
                'lat': lat[self.idx, self.idy].tolist()
            }
            write_vector(grd, out_grdfile)

        u = self.nc.variables['u'][self.n, -1, :, :]
        v = self.nc.variables['v'][self.n, -1, :, :]
        u, v = shrink(u, v)
        u, v = rot2d(u, v, self.anglev)

        self.q = self.ax.quiver(self.xv[self.idx, self.idy],
                                self.yv[self.idx, self.idy],
                                u[self.idx, self.idy],
                                v[self.idx, self.idy],
                                scale=20.0,
                                pivot='middle',
                                zorder=1e35,
                                alpha=0.25,
                                width=0.003)

        self.ax.quiverkey(self.q,
                          0.8,
                          0.90,
                          0.5,
                          r'0.5 m s$^{-1}$',
                          zorder=1e35)
        self.basemap.set_axes_limits(ax=self.ax)

        datestr = self.dates[self.n].strftime('%Y %b %d %H:%M GMT')
        vector = {
            'date': self.dates[self.n].isoformat(),
            'u': u[self.idx, self.idy].tolist(),
            'v': v[self.idx, self.idy].tolist()
        }
        return vector

    def __del__(self):
        """docstring for __del__"""
        self.nc.close()
        self.ncg.close()
Example #4
0
class map(object):
    def __init__(self,
                 grid=None,
                 llcrnrlon=-180,
                 llcrnrlat=-40,
                 urcrnrlon=180,
                 urcrnrlat=40,
                 proj='lcc',
                 resolution='c',
                 figsize=(8., 6.),
                 dlat=1,
                 dlon=2,
                 fig=None,
                 ax=None,
                 fill_color="aqua"):
        """
        map class for abstracting the basemap methods for quick and easy creation
        of geographically referenced data figures


        Parameters
        ----------
        grid: seapy.model.grid or string, optional:
            grid to use to define boundaries
        llcrnrlon: float, optional
            longitude of lower, left corner
        llcrnrlat: float, optional
            latitude of lower, left corner
        urcrnrlon: float, optional
            longitude of upper, right corner
        urcrnrlat: float, optional
            latitude of upper, right corner
        proj: string, optional
            projection to use for map
        resolution: character
            resolution to use for coastline, etc. From Basemap:
            'c' (crude), 'l' (low), 'i' (intermediate),
            'h' (high), 'f' (full), or None
        figsize: list, optional
            dimensions to use for creation of figure
        dlat: float, optional
            interval to mark latitude lines (e.g., if dlat=0.5 every 0.5deg mark)
        dlon: float, optional
            interval to mark longitude lines (e.g., if dlon=0.5 every 0.5deg mark)
        fig: matplotlib.pyplot.figure object, optional
            If you want to plot on a pre-configured figure, pass the figure object
            along with the axis object.
        ax: matplotlib.pyplot.axis object, optional
            If you want to plot on a pre-configured figure, pass the axis object
            along with the figure object.
        fill_color: string, optional
            The color to use for the axis background

        Returns
        -------
        None

        """
        if grid is not None:
            grid = asgrid(grid)
            llcrnrlat = np.min(grid.lat_rho)
            urcrnrlat = np.max(grid.lat_rho)
            llcrnrlon = np.min(grid.lon_rho)
            urcrnrlon = np.max(grid.lon_rho)

        self.basemap = Basemap(llcrnrlon=llcrnrlon,
                               llcrnrlat=llcrnrlat,
                               urcrnrlon=urcrnrlon,
                               urcrnrlat=urcrnrlat,
                               projection=proj,
                               lat_0=urcrnrlat - (urcrnrlat - llcrnrlat) / 2.,
                               lon_0=urcrnrlon - (urcrnrlon - llcrnrlon) / 2.,
                               resolution=resolution,
                               area_thresh=0.0,
                               ax=ax)

        self.figsize = figsize
        self.dlon = dlon
        self.dlat = dlat
        self.fig = fig
        self.ax = ax
        self.fill_color = fill_color
        reset = True if fig is None else False
        self.new_figure(reset=reset)

    def new_figure(self, fill_color=None, reset=False, dpi=150):
        """
        Create or update a figure for plotting

        Parameters
        ----------
        fill_color: string, optional
           Color to fill the background of the axes with
        reset: bool, optional
           Reset the figure
        """
        if reset:
            if self.ax:
                self.ax.set_axis_off()
                self.ax = None
            if self.fig:
                self.fig.clf()
                self.fig = None

        if self.fig is None or self.ax is None:
            self.fig = plt.figure(figsize=self.figsize, dpi=dpi)
            self.ax = self.fig.add_axes([-0.01, 0.25, 1.01, 0.7])

        if fill_color is None:
            fill_color = self.fill_color

        self.basemap.drawmapboundary(fill_color=fill_color)
        # Create the longitude lines
        nticks = int(
            (self.basemap.urcrnrlon - self.basemap.llcrnrlon) / self.dlon)
        md = np.mod(self.basemap.llcrnrlon, self.dlon)
        if md:
            slon = self.basemap.llcrnrlon + self.dlon - md
        else:
            slon = self.basemap.llcrnrlon
            nticks += 1
        lon_lines = np.arange(nticks) * self.dlon + slon
        self.basemap.drawmeridians(lon_lines,
                                   color="0.5",
                                   linewidth=0.25,
                                   dashes=[1, 1, 0.1, 1],
                                   labels=[0, 0, 0, 1],
                                   fontsize=12)

        # Create the latitude lines
        nticks = int(
            (self.basemap.urcrnrlat - self.basemap.llcrnrlat) / self.dlat)
        md = np.mod(self.basemap.llcrnrlat, self.dlat)
        if md:
            slat = self.basemap.llcrnrlat + self.dlat - md
        else:
            slat = self.basemap.llcrnrlat
            nticks += 1
        lat_lines = np.arange(nticks) * self.dlat + slat
        self.basemap.drawparallels(lat_lines,
                                   color="0.5",
                                   linewidth=0.25,
                                   dashes=[1, 1, 0.1, 1],
                                   labels=[1, 0, 0, 0],
                                   fontsize=12)

    def land(self, color="black"):
        """
        Draw the land mask

        Parameters
        ----------
        color: string, optional
            color to draw the mask with
        """
        self.basemap.drawcoastlines()
        self.basemap.drawcountries()
        self.basemap.fillcontinents(color=color)

    def zoom(self, xrange, yrange):
        """
        zoom the figure to a specified lat, lon range

        Parameters
        ----------
        xrange: array
            minimum and maximum longitudes to display
        yrange: array
            minimum and maximum latitudes to display
        """
        x, y = self.basemap(xrange, yrange)
        self.ax.set_xlim(x)
        self.ax.set_ylim(y)
        self.fig.canvas.draw()

    def pcolormesh(self, lon, lat, data, **kwargs):
        """
        pcolormesh field data onto our geographic plot

        Parameters
        ----------
        lon: array
            Longitude field for data
        lat: array
            Latitude field for data
        data: array
            data to pcolor
        **kwargs: arguments, optional
            additional arguments to pass to pcolor
        """
        # Pcolor requires a modification to the locations to line up with
        # the geography
        dlon = lon * 0
        dlat = lat * 0
        dlon[:, 0:-1] = lon[:, 1:] - lon[:, 0:-1]
        dlat[0:-1, :] = lat[1:, :] - lat[0:-1, :]
        x, y = self.basemap(lon - dlon * 0.5, lat - dlat * 0.5)
        self.pc = self.ax.pcolormesh(x, y, data, **kwargs)

    def scatter(self, lon, lat, data, **kwargs):
        """
        scatter plot data onto our geographic plot

        Parameters
        ----------
        lon: array
            Longitude field for data
        lat: array
            Latitude field for data
        data: array
            data to pcolor
        **kwargs: arguments, optional
            additional arguments to pass to pcolor
        """
        x, y = self.basemap(lon, lat)
        self.pc = self.ax.scatter(x, y, c=data, **kwargs)

    def colorbar(self, label=None, cticks=None, **kwargs):
        """
        Display a colorbar on the figure

        Parameters
        ----------
        label: string, optional
            Colorbar label title
        cticks: array, optional
            Where to place the tick marks and values for the colorbar
        **kwargs: arguments, optional
            additional arguments to pass to colorbar
        """
        self.cax = self.fig.add_axes([0.25, 0.16, 0.5, 0.03])
        self.cb = plt.colorbar(self.pc,
                               cax=self.cax,
                               orientation="horizontal",
                               ticks=cticks,
                               **kwargs)
        self.basemap.set_axes_limits(ax=self.ax)
        if label is not None:
            self.cb.set_label(label)
Example #5
0
lons = np.linspace(-180, 180, Np + 1)
lats = np.linspace(0, 90, Nl + 1)

#Get histogram
H, xe, ye = np.histogram2d(phi[I], lam[I], bins=(lons, lats), normed=True)
lon2D, lat2D = np.meshgrid(lons, lats)

#Scale by surface area, ie cos(lat)
if (doScl):
    for i in range(Nl):
        lat = 0.5 * (lats[i] + lats[i + 1]) * np.pi / 180.0
        H[:, i] = H[:, i] / np.cos(lat)

H1 = np.random.rand(Nl, Np)
#m.drawcoastlines(linewidth=0.25,color='silver')
m.pcolormesh(lon2D, lat2D, H.T, latlon=True, norm=vNorm)
m.set_axes_limits()
cb = m.colorbar()

#Label latitudes
Ax = plt.gca()
for ml in np.arange(30, 90, da):
    mlStr = r"$%d\degree$" % (ml)
    xy = m(-60, ml)
    Ax.annotate(mlStr, xy=xy, xycoords='data', color='silver')
cb.set_label("Probability Density")
plt.savefig(fname, dpi=dpiQ)
plt.close('all')
lfmv.trimFig(fname)
class mch_animation(object):
    """docstring for MCH animation"""

    figsize = (8, 6)

    font_fixed = plt.matplotlib.font_manager.FontProperties()
    font_fixed.set_family('monospace')

    font_label_it = plt.matplotlib.font_manager.FontProperties()
    font_label_it.set_size(8)
    font_label_it.set_slant('oblique')

    font_label = plt.matplotlib.font_manager.FontProperties()
    font_label.set_size(8)

    cdict = {
        'red': ((0.00, 0.4, 0.4), (0.35, 0.3, 0.3), (0.66, 1.0, 1.0),
                (0.85, 0.9, 0.9), (0.93, 0.75, 0.75), (1.00, 0.83, 0.83)),
        'green': ((0.00, 0.4, 0.4), (0.125, 0.3, 0.3), (0.375, 1.0, 1.0),
                  (0.64, 1.0, 1.0), (0.75, 0.5, 0.5), (0.93, 0.5,
                                                       0.5), (1.00, 0.8, 0.8)),
        'blue': ((0.00, 0.7, 0.7), (0.11, 1.0, 1.0), (0.34, 1.0, 1.0),
                 (0.65, 0.0, 0.0), (0.85, 0.6, 0.6), (1.00, 0.8, 0.8))
    }

    cmap = plt.matplotlib.colors.LinearSegmentedColormap('mod_jet', cdict, 256)

    def __init__(self, year, ncfile, framedir, grdfile=None):
        self.ncfile = ncfile
        self.nc = netCDF.MFDataset(ncfile)
        self.framedir = framedir

        if grdfile is None:
            grdfile = ncfile

        self.ncg = netCDF.Dataset(grdfile)

        self.zr = octant.roms.nc_depths(self.nc, grid='rho')
        self.zw = octant.roms.nc_depths(self.nc, grid='w')

        try:
            self.dates = np.load('/home/rob/Projects/mch/mch_dates.npy')
            print 'loaded mch_dates.npy'
        except:
            print 'loading dates from netcdf files'
            t = octant.cf.time(self.nc, name='ocean_time')
            self.dates = t.dates
            self.dates.dump('/home/rob/Projects/mch/mch_dates.npy')
            print 'saved mch_dates.npy'

        self.basemap = Basemap(llcrnrlon=-95.1,
                               llcrnrlat=27.25,
                               urcrnrlon=-87.5,
                               urcrnrlat=30.95,
                               projection='lcc',
                               lat_0=30.0,
                               lon_0=-90.0,
                               resolution='i',
                               area_thresh=0.)
        self.year = year
        os.system('mkdir %s_%d' % (self.framedir, year))
        self.frame = 0

        self.diff_t = diff_t(self.nc, bflux=1.0e-6)
        self.diff_t.dt = self.diff_t.dt * 10000.0

    def new_frame(self, n):
        """docstring for new_frame"""
        self.n = n

        # set up figure and axis
        self.fig = plt.figure(figsize=self.figsize)
        self.ax = self.fig.add_axes([-0.01, 0.27, 1.01, 0.73])

        self.basemap.drawcoastlines(linewidth=0.25, color='k')
        self.basemap.fillcontinents(color='0.7')
        self.basemap.drawmeridians(range(-97, -85, 1),
                                   labels=[0, 0, 0, 0],
                                   color='0.5',
                                   linewidth=0.25,
                                   dashes=[1, 0])
        self.basemap.drawparallels(range(25, 32, 1),
                                   labels=[0, 0, 0, 0],
                                   color='0.5',
                                   linewidth=0.25,
                                   dashes=[1, 0])

        # get and plot date
        datestr = self.dates[self.n].strftime('%Y %b %d %H:%M GMT')
        plt.text(0.02,
                 0.24,
                 datestr + ' ',
                 fontproperties=self.font_fixed,
                 horizontalalignment='left',
                 verticalalignment='top',
                 transform=self.fig.transFigure,
                 fontsize=12)

    def filled_timeseries(self, dates, value):
        """docstring for filled_timeseries"""

        dateo = self.dates[self.n]
        idx = np.where(np.abs(dates-dateo) == \
                        np.min(np.abs(dates-dateo)))[0]
        idx = np.min(idx)

        self.tsax = self.fig.add_axes([0, 0, 1.0, .25])
        self.tsax.set_axis_off()
        t = date2num(dates)
        t_fill = np.hstack((t[0], t[:idx + 1], t[idx]))
        v_fill = np.hstack((0, value[:idx + 1], 0))
        self.tsax.fill(t_fill, v_fill, alpha=0.5, fc='b', ec='k')
        self.tsax.plot(t, value, '-k')
        self.tsax.plot([t.min(), t.max()], [10000, 10000],
                       '-b',
                       lw=0.5,
                       alpha=0.5)
        self.tsax.plot([t.min(), t.max()], [20000, 20000],
                       '-b',
                       lw=0.5,
                       alpha=0.5)
        self.tsax.plot([t.min(), t.max()], [30000, 30000],
                       '-b',
                       lw=0.5,
                       alpha=0.5)

        self.tsax.text(t.max() - 45,
                       10000,
                       r'10,000',
                       ha='left',
                       va='bottom',
                       fontproperties=self.font_label_it)
        self.tsax.text(t.max() - 45,
                       20000,
                       r'20,000',
                       ha='left',
                       va='bottom',
                       fontproperties=self.font_label_it)
        self.tsax.text(t.max() - 45,
                       30000,
                       r'30,000 m$^3$ s$^{-1}$',
                       ha='left',
                       va='bottom',
                       fontproperties=self.font_label_it)
        self.tsax.text(t.max() - 50,
                       30000,
                       r'Mississippi River Discharge',
                       ha='right',
                       va='bottom',
                       fontproperties=self.font_label_it)

        self.tsax.set_xlim(t.min(), t.max())
        self.tsax.set_ylim(0, 40000)

    def add_wind_arrow(self, dates, Uwind, Vwind):

        dateo = self.dates[self.n]
        idx = np.where(np.abs(dates-dateo) == \
                        np.min(np.abs(dates-dateo)))[0]
        idx = np.min(idx)

        idx_month = np.where((dates > dateo - timedelta(days=7))
                             & (dates < dateo))[0]

        xo, yo = (650000, 60000.0)

        self.ax.quiver((xo, ), (yo, ), (Uwind[idx], ), (Vwind[idx], ),
                       scale=100.0,
                       pivot='middle',
                       zorder=1e35,
                       width=0.01,
                       headlength=3,
                       headaxislength=2.7,
                       color=(0.0, 0.5, 1.0),
                       clip_on=False)

        Uwind_offset = Uwind[idx_month] * 3500.0
        Vwind_offset = Vwind[idx_month] * 3500.0

        self.ax.plot(xo + Uwind_offset,
                     yo + Vwind_offset,
                     'o',
                     color=(0.5, 0.5, 1.0),
                     alpha=0.01,
                     mec=None)

        for radius in [5, 10, 15]:
            circ = plt.Circle((xo, yo),
                              radius * 3500.0,
                              ec=(0.8, 0.8, 1.0),
                              fc='None')
            self.ax.add_artist(circ)

        self.ax.text(xo,
                     yo + 5.5 * 3500.0,
                     r'5',
                     ha='left',
                     va='bottom',
                     fontproperties=self.font_label_it)
        self.ax.text(xo,
                     yo + 10.5 * 3500.0,
                     r'10',
                     ha='left',
                     va='bottom',
                     fontproperties=self.font_label_it)
        self.ax.text(xo,
                     yo + 15.5 * 3500.0,
                     r'15  m s$^{-1}$',
                     ha='left',
                     va='bottom',
                     fontproperties=self.font_label_it)
        self.ax.text(xo,
                     yo + 20.0 * 3500.0,
                     r'Wind Speed',
                     ha='left',
                     va='bottom',
                     fontproperties=self.font_label_it)

    def close_frame(self):
        # plt.text(0.95, 0.08, self.title,
        #          horizontalalignment='right',
        #          verticalalignment='top',
        #          transform=self.fig.transFigure,
        #          fontsize=16)

        self.ax.set_axis_off()
        plt.savefig('%s_%d/frame_%04d.png' %
                    (self.framedir, self.year, self.frame),
                    dpi=100)
        print ' ... wrote frame ', self.frame
        self.frame += 1
        plt.close(self.fig)

    def plot_property_surface(self, propname, clabel, clim, cticks):

        h = self.ncg.variables['h'][:]
        lon = self.ncg.variables['lon_rho'][:]
        lat = self.ncg.variables['lat_rho'][:]
        x, y = self.basemap(lon, lat)

        mask = self.ncg.variables['mask_rho'][:]

        h = np.ma.masked_where(mask == 0, h)
        plt.contour(x,
                    y,
                    h, [10, 20, 50, 100, 200],
                    colors='0.5',
                    linewidths=0.5)

        print 'property ', propname, self.n
        prop = self.nc.variables[propname][self.n][-1]
        prop = np.ma.masked_where(mask == 0, prop)
        self.pc = self.ax.pcolor(x,
                                 y,
                                 prop,
                                 vmin=min(clim),
                                 vmax=max(clim),
                                 cmap=self.cmap)

        self.cax = self.fig.add_axes([0.05, 0.92, 0.5, 0.03])
        cb = plt.colorbar(self.pc,
                          cax=self.cax,
                          orientation='horizontal',
                          ticks=cticks)
        cb.set_label(clabel)

        self.basemap.set_axes_limits(ax=self.ax)

    def plot_property_bottom(self, propname, clabel, clim, cticks):

        h = self.ncg.variables['h'][:]
        lon = self.ncg.variables['lon_rho'][:]
        lat = self.ncg.variables['lat_rho'][:]
        x, y = self.basemap(lon, lat)

        mask = self.ncg.variables['mask_rho'][:]

        h = np.ma.masked_where(mask == 0, h)
        plt.contour(x,
                    y,
                    h, [10, 20, 50, 100, 200],
                    colors='0.5',
                    linewidths=0.5)

        prop = self.nc.variables[propname][self.n, 0, :]
        prop = np.ma.masked_where(mask == 0, prop)
        self.pc = self.ax.pcolor(x,
                                 y,
                                 prop,
                                 vmin=min(clim),
                                 vmax=max(clim),
                                 cmap=self.cmap)

        self.cax = self.fig.add_axes([0.05, 0.92, 0.5, 0.03])
        cb = plt.colorbar(self.pc,
                          cax=self.cax,
                          orientation='horizontal',
                          ticks=cticks)
        cb.set_label(clabel)

        self.basemap.set_axes_limits(ax=self.ax)

    def plot_hypoxia_timescales(self):

        h = self.ncg.variables['h'][:]
        sss = self.nc.variables['salt'][self.n, -1]
        lon = self.ncg.variables['lon_rho'][:]
        lat = self.ncg.variables['lat_rho'][:]
        x, y = self.basemap(lon, lat)

        mask = self.ncg.variables['mask_rho'][:]

        h = np.ma.masked_where(mask == 0, h)
        plt.contour(x,
                    y,
                    h, [10, 20, 50, 100, 200],
                    colors='0.5',
                    linewidths=0.5)
        plt.contour(x,
                    y,
                    sss,
                    range(5, 36),
                    cmap=self.cmap,
                    vmin=5.0,
                    vmax=35.0,
                    linewidths=0.25,
                    alpha=0.5)

        z = self.zw[self.n, 1:-1] - self.zw[self.n, 0]
        dz = np.diff(self.zr[self.n], axis=0)
        AKt = self.nc.variables['AKt'][self.n, 1:-1]

        temp = self.nc.variables['temp'][self.n, 0]
        salt = self.nc.variables['salt'][self.n, 0]

        o2_sat = octant.ocean.o2_sat(temp, salt)

        tflux = 0.5 * AKt * o2_sat / dz
        bflux = bottom_o2_flux(temp)

        T = z * o2_sat / (bflux - tflux) / 86400.0
        T = np.ma.masked_where(T <= 0.0, T)
        To = z * o2_sat / (bflux) / 86400.0

        lon = self.ncg.variables['lon_psi'][:]
        lat = self.ncg.variables['lat_psi'][:]
        x, y = self.basemap(lon, lat)

        plot_type = 'bbl'
        if plot_type == 'timescale':
            plt.cm.Reds_r.set_under('0.90')
            self.pc = self.ax.pcolor(x,
                                     y,
                                     T[:, 1:-1,
                                       1:-1].min(axis=0).filled(-999.0),
                                     vmin=0.0,
                                     vmax=90.0,
                                     cmap=plt.cm.Reds_r)
            self.cax = self.fig.add_axes([0.05, 0.92, 0.5, 0.03])
            cb = plt.colorbar(self.pc, cax=self.cax, orientation='horizontal')
            cb.set_label('Hypoxia timescale [days]')
        else:
            bbl = np.choose(T.argmin(axis=0), z)
            plt.cm.jet.set_under('0.90')
            bbl[T.min(axis=0).filled(-999.0) < 0.0] = -999.0
            bbl[T.min(axis=0) > 60.0] = -999.0
            self.pc = self.ax.pcolor(x,
                                     y,
                                     bbl[1:-1, 1:-1],
                                     vmin=0.0,
                                     vmax=5.0,
                                     cmap=plt.cm.jet)
            self.cax = self.fig.add_axes([0.05, 0.92, 0.5, 0.03])
            cb = plt.colorbar(self.pc, cax=self.cax, orientation='horizontal')
            cb.set_label('Bottom boundary layer thickness [m]')

        self.basemap.set_axes_limits(ax=self.ax)

    def plot_max_N2(self):

        h = self.ncg.variables['h'][:]
        lon = self.ncg.variables['lon_rho'][:]
        lat = self.ncg.variables['lat_rho'][:]
        x, y = self.basemap(lon, lat)

        mask = self.ncg.variables['mask_rho'][:]

        h = np.ma.masked_where(mask == 0, h)
        plt.contour(x,
                    y,
                    h, [10, 20, 50, 100, 200],
                    colors='0.5',
                    linewidths=0.5)

        rho = self.nc.variables['rho'][self.n]
        zr = octant.roms.nc_depths(self.nc, grid='rho')[self.n]
        drdz = np.diff(rho, axis=0) / np.diff(zr, axis=0)
        prop = (-9.8 * drdz / 1000.0).max(axis=0)
        prop = np.ma.masked_where(prop <= 0, prop)
        self.pc = self.ax.pcolor(x,
                                 y,
                                 np.log10(prop),
                                 vmin=-5.0,
                                 vmax=-1.0,
                                 cmap=plt.cm.Reds)

        self.cax = self.fig.add_axes([0.05, 0.92, 0.5, 0.03])
        cb = plt.colorbar(self.pc,
                          cax=self.cax,
                          orientation='horizontal',
                          ticks=[-1.5, -2.5, -3.5, -4.5])
        cb.set_label(r'maximum log$_{10}(N^2)$')

        self.basemap.set_axes_limits(ax=self.ax)

    def plot_vector_surface(self):
        lon = self.ncg.variables['lon_psi'][:]
        lat = self.ncg.variables['lat_psi'][:]
        xv, yv = self.basemap(lon, lat)

        maskv = self.ncg.variables['mask_psi'][:]
        anglev = octant.tools.shrink(self.ncg.variables['angle'][:], xv.shape)

        u = self.nc.variables['u'][self.n][-1]
        v = self.nc.variables['v'][self.n][-1]
        u, v = octant.tools.shrink(u, v)
        u, v = octant.tools.rot2d(u, v, anglev)

        if self.frame == 0:
            idx, idy = np.where(maskv == 1.0)
            idv = np.arange(len(idx))
            np.random.shuffle(idv)
            Nvec = len(idx) / 15
            idv = idv[:Nvec]
            self.idx = idx[idv]
            self.idy = idy[idv]

        self.q = self.ax.quiver(xv[self.idx, self.idy],
                                yv[self.idx, self.idy],
                                u[self.idx, self.idy],
                                v[self.idx, self.idy],
                                scale=20.0,
                                pivot='middle',
                                zorder=1e35,
                                alpha=0.25,
                                width=0.003)

        self.ax.quiverkey(self.q,
                          0.8,
                          0.90,
                          0.5,
                          r'0.5 m s$^{-1}$',
                          zorder=1e35)

        self.basemap.set_axes_limits(ax=self.ax)

    def plot_vector_bottom(self):
        lon = self.ncg.variables['lon_psi'][:]
        lat = self.ncg.variables['lat_psi'][:]
        xv, yv = self.basemap(lon, lat)

        maskv = self.ncg.variables['mask_psi'][:]
        anglev = octant.tools.shrink(self.ncg.variables['angle'][:], xv.shape)

        u = self.nc.variables['u'][self.n, 1, :]
        v = self.nc.variables['v'][self.n, 1, :]
        u, v = octant.tools.shrink(u, v)
        u, v = octant.tools.rot2d(u, v, anglev)

        if self.frame == 0:
            idx, idy = np.where(maskv == 1.0)
            idv = np.arange(len(idx))
            np.random.shuffle(idv)
            Nvec = len(idx) / 15
            idv = idv[:Nvec]
            self.idx = idx[idv]
            self.idy = idy[idv]

        self.q = self.ax.quiver(xv[self.idx, self.idy],
                                yv[self.idx, self.idy],
                                u[self.idx, self.idy],
                                v[self.idx, self.idy],
                                scale=4.0,
                                pivot='middle',
                                zorder=1e35,
                                alpha=0.25,
                                width=0.003)

        self.ax.quiverkey(self.q,
                          0.8,
                          0.90,
                          0.1,
                          r'0.1 m s$^{-1}$',
                          zorder=1e35)

        self.basemap.set_axes_limits(ax=self.ax)

    def plot_property_zslice(self, propname, zlevel, clabel, clim, cticks):
        'plot 100 m currents over 500 m salinity'

        self.zlevel = zlevel

        self.ax.set_axis_bgcolor('0.6')

        h = self.ncg.variables['h'][:]

        lon = self.ncg.variables['lon_rho'][:]
        lat = self.ncg.variables['lat_rho'][:]
        x, y = self.basemap(lon, lat)

        mask = self.ncg.variables['mask_rho'][:]

        z = octant.roms.nc_depths(self.nc)[self.n]

        h = np.ma.masked_where(mask == 0, h)
        plt.contour(x,
                    y,
                    h, [50, 100, 200, 500, 1000, 2000],
                    colors='0.5',
                    linewidths=0.5)

        prop = self.nc.variables[propname][self.n, :]
        prop = octant.tools.surface(prop, z, self.zlevel)
        self.pc = self.ax.pcolor(x, y, prop, vmin=min(clim), vmax=max(clim))

        self.basemap.set_axes_limits(ax=self.ax)

        self.cax = self.fig.add_axes([0.5, 0.85, 0.3, 0.03])
        cb = plt.colorbar(self.pc,
                          cax=self.cax,
                          orientation='horizontal',
                          ticks=cticks)
        cb.set_label(clabel)

    def plot_attribution(self):
        self.ax.text(0.99,
                     0.0,
                     'Robert Hetland, TAMU\nMechanisms Controlling Hypoxia',
                     horizontalalignment='right',
                     verticalalignment='top',
                     transform=self.ax.transAxes,
                     fontproperties=self.font_label)

    def plot_vector_zslice(self, zlevel=None):

        if zlevel is None:
            zlevel = self.zlevel

        lon = self.ncg.variables['lon_psi'][:]
        lat = self.ncg.variables['lat_psi'][:]
        xv, yv = self.basemap(lon, lat)

        maskv = self.ncg.variables['mask_psi'][:]
        anglev = octant.tools.shrink(self.ncg.variables['angle'][:], xv.shape)

        z = octant.roms.nc_depths(self.nc)[self.n]
        zv = octant.tools.shrink(z, (30, ) + xv.shape)

        u = self.nc.variables['u'][self.n, :]
        v = self.nc.variables['v'][self.n, :]

        u = octant.tools.shrink(u, (30, ) + xv.shape)
        v = octant.tools.shrink(v, (30, ) + xv.shape)

        u = octant.tools.surface(u, zv, zlevel)
        v = octant.tools.surface(v, zv, zlevel)

        u, v = octant.tools.rot2d(u, v, anglev)

        if self.frame == 0:
            idx, idy = np.where(~np.isnan(u.copy()))
            idx = idx[~idx.mask].data
            idy = idy[~idy.mask].data
            idv = np.arange(len(idx))
            np.random.shuffle(idv)
            Nvec = len(idx) / 20
            idv = idv[:Nvec]
            self.idx = idx[idv]
            self.idy = idy[idv]

        self.q = self.ax.quiver(xv[self.idx, self.idy],
                                yv[self.idx, self.idy],
                                u[self.idx, self.idy],
                                v[self.idx, self.idy],
                                scale=3.0,
                                pivot='middle',
                                zorder=1e35)

        self.ax.quiverkey(self.q, 0.33, 0.48, 0.1, '10 cm/s', zorder=1e35)

        self.basemap.set_axes_limits(ax=self.ax)

    def __del__(self):
        """docstring for __del__"""
        self.nc.close()
        self.ncg.close()
Example #7
0
map.drawlsmask(land_color="#ddaa66", ocean_color="#7777ff", resolution='c')

x1, y1 = map(-60, -30)
x2, y2 = map(0, 0)
x3, y3 = map(45, 45)

plt.plot([x1, x2, x3], [y1, y2, y3], color='k', linestyle='-', linewidth=2)

ax1 = fig.add_axes([0.1, 0., 0.15, 0.15])
ax1.set_xticks([])
ax1.set_yticks([])

ax1.plot([x1, x2, x3], [y1, y2, y3], color='k', linestyle='-', linewidth=2)

map.set_axes_limits(ax=ax1)

ax2 = fig.add_axes([0.3, 0., 0.15, 0.15])
ax2.set_xticks([])
ax2.set_yticks([])

ax2.plot([x1, x2, x3], [y1, y2, y3], color='k', linestyle='-', linewidth=2)

ax3 = fig.add_axes([0.5, 0., 0.15, 0.15])
ax3.set_xticks([])
ax3.set_yticks([])

map.plot([x1, x2, x3], [y1, y2, y3],
         color='k',
         linestyle='-',
         linewidth=2,
Example #8
0
               resolution = 'c')


x1, y1 = map(-60, -30)
x2, y2 = map(0, 0)
x3, y3 = map(45, 45)

plt.plot([x1, x2, x3], [y1, y2, y3], color='k', linestyle='-', linewidth=2)

ax1 = fig.add_axes([0.1, 0., 0.15, 0.15])
ax1.set_xticks([])
ax1.set_yticks([])

ax1.plot([x1, x2, x3], [y1, y2, y3], color='k', linestyle='-', linewidth=2)

map.set_axes_limits(ax=ax1)

ax2 = fig.add_axes([0.3, 0., 0.15, 0.15])
ax2.set_xticks([])
ax2.set_yticks([])

ax2.plot([x1, x2, x3], [y1, y2, y3], color='k', linestyle='-', linewidth=2)

ax3 = fig.add_axes([0.5, 0., 0.15, 0.15])
ax3.set_xticks([])
ax3.set_yticks([])

map.plot([x1, x2, x3], [y1, y2, y3], color='k', linestyle='-', linewidth=2, ax=ax3)

plt.show()
Example #9
0
geoms = [ "ST_Simplify(ST_Buffer(ST_Buffer(\ngeom, -0.01),0.01),0.0025)",
         "ST_Simplify(ST_Buffer(ST_Buffer(\ngeom, -0.001),0.001),0.00025)",
         "geom", "ST_Simplify(geom,0.1)", "ST_Simplify(geom,0.01)"
         , "ST_Simplify(geom,0.001)"]

for row in range(2):
    for col in range(3):
        ax = axes[row,col]
        m = Basemap(projection='lcc', 
            urcrnrlat=ymax, llcrnrlat=ymin, 
            urcrnrlon=xmax, llcrnrlon=xmin, 
            lon_0=(xmax+xmin)/2., 
        lat_0=(ymax+ymin)/2.-5, lat_1=(ymax+ymin)/2., lat_2=(ymax+ymin)/2.+5,
        resolution='l', fix_aspect=True, ax=ax)
        #m.fillcontinents(color='b',zorder=0)
        m.set_axes_limits(ax=ax)
        g = geoms.pop()
        source = ogr.Open("PG:host=iemdb dbname=postgis")
        data = source.ExecuteSQL("select %s from nws_ugc where ugc = '%s'" % (g,
                                                                        UGC))

        patches = []
        while 1:
            feature = data.GetNextFeature()
            if not feature:
                break
            bindata = feature.GetGeometryRef().ExportToWkb()
            geom = loads(bindata)
            for polygon in geom:
                a = asarray(polygon.exterior)
                x,y = m(a[:,0], a[:,1])
Example #10
0
        )
        cx = 1 / (6 * area) * sum(
            (xy[i][0] + xy[i + 1][0]) * ((xy[i][0] * xy[i + 1][1]) - (xy[i + 1][0] * xy[i][1]))
            for i in range(len(xy) - 1)
        )
        cy = 1 / (6 * area) * sum(
            (xy[i][1] + xy[i + 1][1]) * ((xy[i][0] * xy[i + 1][1]) - (xy[i + 1][0] * xy[i][1]))
            for i in range(len(xy) - 1)
        )
        patches.append(matplotlib.patches.Polygon(xy))
        counts.append(count[name])
        # plt.text(cx, cy, name,
        #          horizontalalignment="center",
        #          verticalalignment="center")

m.set_axes_limits()

x, y = m(positions[1], positions[0])
plt.scatter(x, y, values, "k")

p = matplotlib.collections.PatchCollection(patches, cmap=colors, norm=normalize, alpha=0.7)
p.set_array(np.array(counts))
ax.add_collection(p)
plt.colorbar(p,
             spacing="proportional",
             ticks=range(max(counts) + 1),
             boundaries=range(max(counts) + 1))

plt.title("Anzahl der Schulen")
# plt.title(u"Anzahl der Grünflächen")
Example #11
0
    for col in range(3):
        ax = axes[row, col]
        m = Basemap(projection='lcc',
                    urcrnrlat=ymax,
                    llcrnrlat=ymin,
                    urcrnrlon=xmax,
                    llcrnrlon=xmin,
                    lon_0=(xmax + xmin) / 2.,
                    lat_0=(ymax + ymin) / 2. - 5,
                    lat_1=(ymax + ymin) / 2.,
                    lat_2=(ymax + ymin) / 2. + 5,
                    resolution='l',
                    fix_aspect=True,
                    ax=ax)
        #m.fillcontinents(color='b',zorder=0)
        m.set_axes_limits(ax=ax)
        g = geoms.pop()
        source = ogr.Open("PG:host=iemdb dbname=postgis")
        data = source.ExecuteSQL("select %s from nws_ugc where ugc = '%s'" %
                                 (g, UGC))

        patches = []
        while 1:
            feature = data.GetNextFeature()
            if not feature:
                break
            bindata = feature.GetGeometryRef().ExportToWkb()
            geom = loads(bindata)
            for polygon in geom:
                a = asarray(polygon.exterior)
                x, y = m(a[:, 0], a[:, 1])