def draw_map(intensity, city, save_file_path=None):
    # 切り出し
    intensity_city, lats_city, lons_city = crop_latlon(
        intensity, city, inifile.getint('area', 'd'))

    flat_lats_city = np.ravel(lats_city)
    flat_lons_city = np.ravel(lons_city)

    # 色指定
    # black指定 -> 海岸線白,背景黒  white指定 -> 海岸線黒,背景白
    base_color = inifile.get('image', 'base_color')
    coastline_color = 'white' if base_color == 'black' else 'black'
    zero_color = 0 if base_color == 'black' else 1

    # 色の変更
    cm = eval('plt.cm.' + inifile.get('image', 'color_map'))
    cm_list = cm(np.arange(cm.N))
    cm_list[0, :3] = zero_color  # カラースケール0番目の値の色を変更
    mycmap = ListedColormap(cm_list)

    # 描画矩形座標を指定
    m = Basemap(llcrnrlat=lats_city.min(), urcrnrlat=lats_city.max(), \
                llcrnrlon=lons_city.min(), urcrnrlon=lons_city.max(), \
                resolution=inifile.get('image', 'coastline_quality'))

    # 海岸線
    if inifile.getboolean('image', 'draw_coastline'):
        m.drawcoastlines(color=coastline_color)

    # 描画
    m.contourf(x=flat_lons_city, y=flat_lats_city, data=intensity_city, \
               levels=list(range(0,255)), latlon=True, tri=True, cmap=mycmap)

    # 枠を消す
    plt.gca().spines['right'].set_visible(False)
    plt.gca().spines['top'].set_visible(False)
    plt.gca().spines['left'].set_visible(False)
    plt.gca().spines['bottom'].set_visible(False)

    # カラーバー
    if inifile.getboolean('image', 'draw_colorbar'):
        plt.colorbar()

    # save
    plt.savefig(save_file_path, transparent=True, \
                bbox_inches = 'tight', pad_inches = 0, facecolor=base_color)  # 余白を消す

    plt.clf()
コード例 #2
0
ファイル: radar_horizontal.py プロジェクト: adlyons/AWOT
    def plot_cappi(self, field, cappi_height, plot_km=False,
                   mask_procedure=None, mask_tuple=None,
                   cminmax=(0., 60.), clevs=25, vmin=15., vmax=60.,
                   cmap='gist_ncar',  discrete_cmap_levels=None,
                   title=" ", title_size=20,
                   color_bar=True, clabel='dBZ', cb_pad="5%",
                   cb_loc='right', cb_tick_int=2, ax=None, fig=None,
                   save_kmz=False, kmz_filepath=None, kmz_filename=None):
        """
        Produce a CAPPI (constant altitude plan position indicator) plot
        using the Tail Doppler Radar data.

        Parameters
        ----------
        field : str
            3-D variable (e.g. Reflectivity [dBZ]) to use in plot.
        cappi_height : float
            Height in meters at which to plot the horizontal field.
        plot_km : boolean
            True to convert meters to kilometers for cappi_height. False
            retains meters information.
        mask_procedure : str
            String indicating how to apply mask via numpy, possibilities are:
            'less', 'less_equal', 'greater', 'greater_equal',
            'equal', 'inside', 'outside'.
        mask_tuple : (str, float[, float])
            Tuple containing the field name and value(s) below which to mask
            field prior to plotting, for example to mask all data where.
        cminmax : tuple
            (min,max) values for controur levels.
        clevs : int
            Number of contour levels.
        vmin : float
            Minimum contour value to display.
        vmax : float
            Maximum contour value to display.
        cmap : str
            Matplotlib color map to use.
        discrete_cmap_levels : array
            A list of levels to be used for display. If chosen discrete
            color will be used in the colorbar instead of a linear luminance
            mapping.
        title : str
            Plot title.
        title_size : int
            Font size of title to display.
        color_bar : boolean
            True to add colorbar, False does not.
        clabel : str
            Label for colorbar (e.g. units 'dBZ').
        cb_pad : str
            Pad to move colorbar, in the form "5%", pos is to
            right for righthand location.
        cb_loc : str
            Location of colorbar, default is 'right', also available:
            'bottom', 'top', 'left'.
        cb_tick_int : int
            Interval to use for colorbar tick labels,
            higher number "thins" labels.
        ax : Matplotlib axis instance
            Axis to plot.
            None will use the current axis.
        fig : Matplotlib figure instance
            Figure on which to add the plot.
            None will use the current figure.

        Notes
        -----
        Defaults are established during DYNAMO project analysis.
        """
        # parse parameters
        ax, fig = common._parse_ax_fig(ax, fig)

        # Grab the variable dictionary of interest to plot
        Var = self.fields[field]

        # Return masked or unmasked variable
        Var, Data = self._get_variable_dict_data(field)
        if mask_procedure is not None:
            Data = common.get_masked_data(Data, mask_procedure, mask_tuple)

        # Create contour level array
        clevels = np.linspace(cminmax[0], cminmax[1], clevs)

        # Find the closest vertical point
        Zind = common.find_nearest_indices(
                  self.height['data'][:], cappi_height)
        if plot_km:
            levelht = self.height['data'][Zind] / 1000.
        else:
            levelht = self.height['data'][Zind]
        print("Closest level: %4.1f" % levelht)

        # Convert lats/lons to 2D grid
        Lon2D, Lat2D = np.meshgrid(self.longitude['data'][:],
                                   self.latitude['data'][:])
        # Convert lats/lons to map projection coordinates
        x, y = self.basemap(Lon2D, Lat2D)

        # Get the colormap and calculate data spaced by number of levels
        norm = None
        if discrete_cmap_levels is not None:
            cm = plt.get_cmap(cmap)
            try:
                levpos = np.rint(np.squeeze(
                    [np.linspace(0, 255,
                                 len(discrete_cmap_levels))])).astype(int)
                # Convert levels to colormap values
                cmap, norm = from_levels_and_colors(
                    discrete_cmap_levels, cm(levpos), extend='max')
            except:
                print("Keyword error: 'discrete_cmap_levels' must "
                      "be a list of float or integer")

        # Plot the data
        cs = self.basemap.pcolormesh(x, y, Data[Zind, :, :],
                                     vmin=vmin, vmax=vmax,
                                     norm=norm, cmap=cmap)

        #NG Set a couple of keyword defaults for KMZ option
        show_legend, legend_label = False, ' '
        # Add Colorbar
        if color_bar:
            cbStr = "%s at %4.1f %s" % (Var['long_name'],
                                        self.height['data'][Zind],
                                        self.height['units'])
            cb = self.basemap.colorbar(
                cs, location=cb_loc, pad=cb_pad)  # ,ticks=clevels)
            cb.set_label(cbStr)
            # Set the number of ticks in the colorbar based upon
            # number of contours and the tick interval selected
            tick_locator = ticker.MaxNLocator(nbins=int(clevs / cb_tick_int))
            cb.locator = tick_locator
            cb.update_ticks()
            show_legend = True
            legend_label = cbStr

        # Save the KMZ file if requested
        if save_kmz:
            lonrange = (np.min(self.longitude['data'][:]),
                        np.max(self.longitude['data'][:]))
            latrange = (np.min(self.latitude['data'][:]),
                        np.max(self.latitude['data'][:]))
            times = None
            if kmz_filepath is None:
                kmz_filepath = os.getcwd()
            if kmz_filename is None:
                kmz_filename = ('awot_' + self.radar['platform'] + '_' +
                                self.radar['flight_number'] + '_altitude' +
                                '.kmz')
            util.write_kmz.write_kmz(fig, ax, cs, lonrange, latrange, times,
                                     file_path=kmz_filepath,
                                     file_name=kmz_filename,
                                     show_legend=show_legend,
                                     legend_label=legend_label)

        # Add title
        ax.set_title(title, fontsize=title_size)
        return
コード例 #3
0
ファイル: radar_horizontal.py プロジェクト: adlyons/AWOT
    def plot_lf(self, field=None, mask_procedure=None, mask_tuple=None,
                cminmax=(0., 60.), clevs=25, vmin=15., vmax=60.,
                cmap='gist_ncar', discrete_cmap_levels=None,
                title=" ", title_size=20,
                color_bar=True, clabel='dBZ',
                cb_pad="5%", cb_loc='right', cb_tick_int=2,
                ax=None, fig=None):
        """
        Produce a CAPPI (constant altitude plan position indicator) plot
        using the Tail Doppler Radar data.

        Parameters
        ----------
        field : str
            3-D variable (e.g. Reflectivity [dBZ]) to use in plot
        mask_procedure : str
            String indicating how to apply mask via numpy, possibilities are:
            'less', 'less_equal', 'greater', 'greater_equal',
            'equal', 'inside', 'outside'.
        mask_tuple : (str, float[, float])
            Tuple containing the field name and value(s) below which to mask
            field prior to plotting, for example to mask all data where.
        cminmax : tuple
            (min,max) values for controur levels
        clevs : int
            Number of contour levels.
        vmin : float
            Minimum contour value to display.
        vmax : float
            Maximum contour value to display.
        cmap : str
            Matplotlib color map to use.
        discrete_cmap_levels : array
            A list of levels to be used for display. If chosen discrete
            color will be used in the colorbar instead of a linear luminance
            mapping.
        title : str
            Plot title.
        title_size : int
            Font size of title to display.
        clabel : str
            Label for colorbar (e.g. units 'dBZ').
        color_bar : boolean
            True to add colorbar, False does not.
        cb_pad : str
            Pad to move colorbar, in the form "5%", pos is to right
            for righthand location.
        cb_loc : str
            Location of colorbar, default is 'right', also available:
            'bottom', 'top', 'left'.
        cb_tick_int : int
            Interval to use for colorbar tick labels,
            higher number "thins" labels.
        ax : Matplotlib axis instance
            Axis to plot. None will use the current axis.
        fig : Matplotlib figure instance
            Figure on which to add the plot. None will use the current figure.
        """
        # parse parameters
        ax, fig = common._parse_ax_fig(ax, fig)

        # Grab the variable dictionary of interest to plot
        if field is None:
            field = 'reflectivity'

        # Return masked or unmasked variable
        Var, Data = self._get_variable_dict_data(field)
        if mask_procedure is not None:
            Data = common.get_masked_data(Data, mask_procedure, mask_tuple)

        # Create contour level array
        clevels = np.linspace(cminmax[0], cminmax[1], clevs)

        # Convert lats/lons to 2D grid
        Lon2D, Lat2D = np.meshgrid(self.longitude['data'][
                                   :], self.latitude['data'][:])
        # Convert lats/lons to map projection coordinates
        x, y = self.basemap(Lon2D, Lat2D)

        # Get the colormap and calculate data spaced by number of levels
        norm = None
        if discrete_cmap_levels is not None:
            cm = plt.get_cmap(cmap)
            try:
                levpos = np.rint(np.squeeze(
                    [np.linspace(0, 255,
                                 len(discrete_cmap_levels))])).astype(int)
                # Convert levels to colormap values
                cmap, norm = from_levels_and_colors(
                    discrete_cmap_levels, cm(levpos), extend='max')
            except:
                print("Keyword error: 'discrete_cmap_levels' must "
                      "be a list of float or integer")

        p = self.basemap.pcolormesh(x, y, Data, vmin=vmin, vmax=vmax,
                                    norm=norm, cmap=cmap)

        # Add Colorbar
        if color_bar:
            cbStr = Var['long_name'] + ' ' + self.height['units']
            cb = self.basemap.colorbar(
                p, location=cb_loc, pad=cb_pad)  # ,ticks=clevels)
            cb.set_label(cbStr)
            # Set the number of ticks in the colorbar based upon number of
            # contours
            tick_locator = ticker.MaxNLocator(nbins=int(clevs / cb_tick_int))
            cb.locator = tick_locator
            cb.update_ticks()

        # Add title
        ax.set_title(title, fontsize=title_size)
コード例 #4
0
ファイル: radar_horizontal.py プロジェクト: joefinlon/AWOT
    def plot_cappi(self,
                   field,
                   cappi_height,
                   plot_km=False,
                   mask_procedure=None,
                   mask_tuple=None,
                   cminmax=(0., 60.),
                   clevs=25,
                   vmin=15.,
                   vmax=60.,
                   cmap='gist_ncar',
                   discrete_cmap_levels=None,
                   title=" ",
                   title_size=20,
                   color_bar=True,
                   clabel='dBZ',
                   cb_pad="5%",
                   cb_loc='right',
                   cb_tick_int=2,
                   ax=None,
                   fig=None,
                   save_kmz=False,
                   kmz_filepath=None,
                   kmz_filename=None):
        """
        Produce a CAPPI (constant altitude plan position indicator) plot
        using the Tail Doppler Radar data.

        Parameters
        ----------
        field : str
            3-D variable (e.g. Reflectivity [dBZ]) to use in plot.
        cappi_height : float
            Height in meters at which to plot the horizontal field.
        plot_km : boolean
            True to convert meters to kilometers for cappi_height. False
            retains meters information.
        mask_procedure : str
            String indicating how to apply mask via numpy, possibilities are:
            'less', 'less_equal', 'greater', 'greater_equal',
            'equal', 'inside', 'outside'.
        mask_tuple : (str, float[, float])
            Tuple containing the field name and value(s) below which to mask
            field prior to plotting, for example to mask all data where.
        cminmax : tuple
            (min,max) values for controur levels.
        clevs : int
            Number of contour levels.
        vmin : float
            Minimum contour value to display.
        vmax : float
            Maximum contour value to display.
        cmap : str
            Matplotlib color map to use.
        discrete_cmap_levels : array
            A list of levels to be used for display. If chosen discrete
            color will be used in the colorbar instead of a linear luminance
            mapping.
        title : str
            Plot title.
        title_size : int
            Font size of title to display.
        color_bar : boolean
            True to add colorbar, False does not.
        clabel : str
            Label for colorbar (e.g. units 'dBZ').
        cb_pad : str
            Pad to move colorbar, in the form "5%", pos is to
            right for righthand location.
        cb_loc : str
            Location of colorbar, default is 'right', also available:
            'bottom', 'top', 'left'.
        cb_tick_int : int
            Interval to use for colorbar tick labels,
            higher number "thins" labels.
        ax : Matplotlib axis instance
            Axis to plot.
            None will use the current axis.
        fig : Matplotlib figure instance
            Figure on which to add the plot.
            None will use the current figure.

        Notes
        -----
        Defaults are established during DYNAMO project analysis.
        """
        # parse parameters
        ax, fig = common._parse_ax_fig(ax, fig)

        # Grab the variable dictionary of interest to plot
        Var = self.fields[field]

        # Return masked or unmasked variable
        Var, Data = self._get_variable_dict_data(field)
        if mask_procedure is not None:
            Data = common.get_masked_data(Data, mask_procedure, mask_tuple)

        # Create contour level array
        clevels = np.linspace(cminmax[0], cminmax[1], clevs)

        # Find the closest vertical point
        Zind = common.find_nearest_indices(self.height['data'][:],
                                           cappi_height)
        if plot_km:
            levelht = self.height['data'][Zind] / 1000.
        else:
            levelht = self.height['data'][Zind]
        print("Closest level: %4.1f" % levelht)

        # Convert lats/lons to 2D grid
        Lon2D, Lat2D = np.meshgrid(self.longitude['data'][:],
                                   self.latitude['data'][:])
        # Convert lats/lons to map projection coordinates
        x, y = self.basemap(Lon2D, Lat2D)

        # Get the colormap and calculate data spaced by number of levels
        norm = None
        if discrete_cmap_levels is not None:
            cm = plt.get_cmap(cmap)
            try:
                levpos = np.rint(
                    np.squeeze(
                        [np.linspace(0, 255,
                                     len(discrete_cmap_levels))])).astype(int)
                # Convert levels to colormap values
                cmap, norm = from_levels_and_colors(discrete_cmap_levels,
                                                    cm(levpos),
                                                    extend='max')
            except:
                print("Keyword error: 'discrete_cmap_levels' must "
                      "be a list of float or integer")

        # Plot the data
        cs = self.basemap.pcolormesh(x,
                                     y,
                                     Data[Zind, :, :],
                                     vmin=vmin,
                                     vmax=vmax,
                                     norm=norm,
                                     cmap=cmap)

        #NG Set a couple of keyword defaults for KMZ option
        show_legend, legend_label = False, ' '
        # Add Colorbar
        if color_bar:
            cbStr = "%s at %4.1f %s" % (Var['long_name'],
                                        self.height['data'][Zind],
                                        self.height['units'])
            cb = self.basemap.colorbar(cs, location=cb_loc,
                                       pad=cb_pad)  # ,ticks=clevels)
            cb.set_label(cbStr)
            # Set the number of ticks in the colorbar based upon
            # number of contours and the tick interval selected
            tick_locator = ticker.MaxNLocator(nbins=int(clevs / cb_tick_int))
            cb.locator = tick_locator
            cb.update_ticks()
            show_legend = True
            legend_label = cbStr

        # Save the KMZ file if requested
        if save_kmz:
            lonrange = (np.min(self.longitude['data'][:]),
                        np.max(self.longitude['data'][:]))
            latrange = (np.min(self.latitude['data'][:]),
                        np.max(self.latitude['data'][:]))
            times = None
            if kmz_filepath is None:
                kmz_filepath = os.getcwd()
            if kmz_filename is None:
                kmz_filename = ('awot_' + self.radar['platform'] + '_' +
                                self.radar['flight_number'] + '_altitude' +
                                '.kmz')
            util.write_kmz.write_kmz(fig,
                                     ax,
                                     cs,
                                     lonrange,
                                     latrange,
                                     times,
                                     file_path=kmz_filepath,
                                     file_name=kmz_filename,
                                     show_legend=show_legend,
                                     legend_label=legend_label)

        # Add title
        ax.set_title(title, fontsize=title_size)
        return
コード例 #5
0
ファイル: radar_horizontal.py プロジェクト: joefinlon/AWOT
    def plot_lf(self,
                field=None,
                mask_procedure=None,
                mask_tuple=None,
                cminmax=(0., 60.),
                clevs=25,
                vmin=15.,
                vmax=60.,
                cmap='gist_ncar',
                discrete_cmap_levels=None,
                title=" ",
                title_size=20,
                color_bar=True,
                clabel='dBZ',
                cb_pad="5%",
                cb_loc='right',
                cb_tick_int=2,
                ax=None,
                fig=None):
        """
        Produce a CAPPI (constant altitude plan position indicator) plot
        using the Tail Doppler Radar data.

        Parameters
        ----------
        field : str
            3-D variable (e.g. Reflectivity [dBZ]) to use in plot
        mask_procedure : str
            String indicating how to apply mask via numpy, possibilities are:
            'less', 'less_equal', 'greater', 'greater_equal',
            'equal', 'inside', 'outside'.
        mask_tuple : (str, float[, float])
            Tuple containing the field name and value(s) below which to mask
            field prior to plotting, for example to mask all data where.
        cminmax : tuple
            (min,max) values for controur levels
        clevs : int
            Number of contour levels.
        vmin : float
            Minimum contour value to display.
        vmax : float
            Maximum contour value to display.
        cmap : str
            Matplotlib color map to use.
        discrete_cmap_levels : array
            A list of levels to be used for display. If chosen discrete
            color will be used in the colorbar instead of a linear luminance
            mapping.
        title : str
            Plot title.
        title_size : int
            Font size of title to display.
        clabel : str
            Label for colorbar (e.g. units 'dBZ').
        color_bar : boolean
            True to add colorbar, False does not.
        cb_pad : str
            Pad to move colorbar, in the form "5%", pos is to right
            for righthand location.
        cb_loc : str
            Location of colorbar, default is 'right', also available:
            'bottom', 'top', 'left'.
        cb_tick_int : int
            Interval to use for colorbar tick labels,
            higher number "thins" labels.
        ax : Matplotlib axis instance
            Axis to plot. None will use the current axis.
        fig : Matplotlib figure instance
            Figure on which to add the plot. None will use the current figure.
        """
        # parse parameters
        ax, fig = common._parse_ax_fig(ax, fig)

        # Grab the variable dictionary of interest to plot
        if field is None:
            field = 'reflectivity'

        # Return masked or unmasked variable
        Var, Data = self._get_variable_dict_data(field)
        if mask_procedure is not None:
            Data = common.get_masked_data(Data, mask_procedure, mask_tuple)

        # Create contour level array
        clevels = np.linspace(cminmax[0], cminmax[1], clevs)

        # Convert lats/lons to 2D grid
        Lon2D, Lat2D = np.meshgrid(self.longitude['data'][:],
                                   self.latitude['data'][:])
        # Convert lats/lons to map projection coordinates
        x, y = self.basemap(Lon2D, Lat2D)

        # Get the colormap and calculate data spaced by number of levels
        norm = None
        if discrete_cmap_levels is not None:
            cm = plt.get_cmap(cmap)
            try:
                levpos = np.rint(
                    np.squeeze(
                        [np.linspace(0, 255,
                                     len(discrete_cmap_levels))])).astype(int)
                # Convert levels to colormap values
                cmap, norm = from_levels_and_colors(discrete_cmap_levels,
                                                    cm(levpos),
                                                    extend='max')
            except:
                print("Keyword error: 'discrete_cmap_levels' must "
                      "be a list of float or integer")

        p = self.basemap.pcolormesh(x,
                                    y,
                                    Data,
                                    vmin=vmin,
                                    vmax=vmax,
                                    norm=norm,
                                    cmap=cmap)

        # Add Colorbar
        if color_bar:
            cbStr = Var['long_name'] + ' ' + self.height['units']
            cb = self.basemap.colorbar(p, location=cb_loc,
                                       pad=cb_pad)  # ,ticks=clevels)
            cb.set_label(cbStr)
            # Set the number of ticks in the colorbar based upon number of
            # contours
            tick_locator = ticker.MaxNLocator(nbins=int(clevs / cb_tick_int))
            cb.locator = tick_locator
            cb.update_ticks()

        # Add title
        ax.set_title(title, fontsize=title_size)
コード例 #6
0
ファイル: NPLplot.py プロジェクト: ferdavid1/Sensei
        dens = [x.replace(',', '') for x in dens]
        dens = [float(x) for x in dens]
        color = [x / max(dens) for x in dens]
        for a, b in enumerate(stateDens):
            stateDens[a].append(color[a])

        for shape_dict in m.states_info:
            states_names.append(shape_dict['NAME'])

        # get Texas and draw the filled polygon
        for state in states_names:
            stateD = [x for x in stateDens if x[0] == state]
            if stateD:
                stateD = stateD[0]
                seg = m.states[states_names.index(state)]
                poly = Polygon(seg, facecolor=cm(stateD[-1]), zorder=0)
                ax.add_patch(poly)

        lats = [i[0] for i in NPL]
        lons = [i[1] for i in NPL]
        m.scatter(lons,
                  lats,
                  latlon=True,
                  zorder=2,
                  s=1,
                  color="black",
                  picker=True)
        print(ind)

        #print(lats, lons)
        def onclick(event):