def make_plot(crime_counts, crime, hood_map, df, title, label, filename):
    print "Making plot for " + str(crime) + " in Chicago 2016"
    number_of_crime = get_list_of_crime_counts(crime_counts, hood_map, crime)
    fig = plt.figure()
    fig.set_size_inches(18.5, 10.5, forward=True)
    ax = fig.add_subplot(111)
    mymap = getMap(df.crimes)
    mymap.drawmapboundary(fill_color='#46bcec')
    mymap.fillcontinents(color='#f2f2f2', lake_color='#46bcec')
    mymap.drawcoastlines()
    ax.set_title(title)
    cax = fig.add_axes([0.73, 0.1, 0.04, 0.8])
    cmap = cm.get_cmap('YlOrRd')
    norm = Normalize(vmin=0,
                     vmax=max(number_of_crime) + 0.15 * max(number_of_crime))
    cb = ColorbarBase(cax, cmap=cmap, norm=norm)
    drawNeighborhoods(mymap, ax, hood_map, crime_counts, crime, cmap, norm)
    cb.set_label(label)
    oname = filename + ".png"
    onameref = filename + "_RefTowns.png"
    fig.savefig(oname, dpi=200)
    plt.sca(ax)
    drawRefPoints(mymap, refpoints)
    fig.savefig(onameref, dpi=200)
    print "Made " + oname
    print "Made " + onameref
Exemplo n.º 2
0
def plot_colorbar(cax,
                  cmap,
                  hue_norm,
                  cnorm=None,
                  label=None,
                  orientation='vertical',
                  labelsize=4,
                  linewidth=0.5):
    if isinstance(cmap, str):
        cmap = copy.copy(get_cmap(cmap))
    if cnorm is None:
        cnorm = Normalize(vmin=hue_norm[0], vmax=hue_norm[1])
    from .utilities import smart_number_format

    colorbar = ColorbarBase(cax,
                            cmap=cmap,
                            norm=cnorm,
                            format=ticker.FuncFormatter(smart_number_format),
                            orientation=orientation,
                            extend='both')
    colorbar.locator = ticker.MaxNLocator(nbins=3)
    colorbar.update_ticks()

    colorbar.set_label(label, fontsize=labelsize)
    colorbar.outline.set_linewidth(linewidth)
    colorbar.ax.tick_params(size=labelsize,
                            labelsize=labelsize,
                            width=linewidth)
    return cax
Exemplo n.º 3
0
    def get_colorbar(self, title, label, min, max):
        '''Create a colorbar from given data.  Returns a png image as a string.'''

        fig = pylab.figure(figsize=(2, 5))
        ax = fig.add_axes([0.35, 0.03, 0.1, 0.9])
        norm = self.get_norm(min, max)
        formatter = self.get_formatter()
        if formatter:
            cb1 = ColorbarBase(ax,
                               norm=norm,
                               format=formatter,
                               spacing='proportional',
                               orientation='vertical')
        else:
            cb1 = ColorbarBase(ax,
                               norm=norm,
                               spacing='proportional',
                               orientation='vertical')
        cb1.set_label(label, color='1')
        ax.set_title(title, color='1')
        for tl in ax.get_yticklabels():
            tl.set_color('1')
        im = cStringIO.StringIO()
        fig.savefig(im, dpi=300, format='png', transparent=True)
        pylab.close(fig)
        s = im.getvalue()
        im.close()
        return s
Exemplo n.º 4
0
    def error_plot(self, ax_lb, ax_ub, cax, cborientation='vertical'):
        # plot the error map
        ttP_lb = np.zeros((self.dims[1::]))
        ttP_ub = ttP_lb.copy()
        for _i1 in xrange(self.dims[1]):
            for _i2 in xrange(self.dims[2]):
                for _i3 in xrange(self.dims[3]):
                    ttP_lb[_i1, _i2, _i3] = scoreatpercentile(self.ttP[:, _i1, _i2, _i3], 16)
                    ttP_ub[_i1, _i2, _i3] = scoreatpercentile(self.ttP[:, _i1, _i2, _i3], 84)

        mlb = copy(self.m)
        mlb.ax = ax_lb
        mub = copy(self.m)
        mub.ax = ax_ub

        cmap = cm.get_cmap(self.cmapname)
        cmap.set_over('grey')

        mlb.contourf(self.x, self.y, ttP_lb[:, :, 0], cmap=cmap,
                     levels=np.arange(self.vmin, self.vmax + 0.5, 0.5),
                     norm=Normalize(vmin=self.vmin, vmax=self.vmax),
                     extend=self.extend)
        mub.contourf(self.x, self.y, ttP_ub[:, :, 0], cmap=cmap,
                     levels=np.arange(self.vmin, self.vmax + 0.5, 0.5),
                     norm=Normalize(vmin=self.vmin, vmax=self.vmax),
                     extend=self.extend)
        mlb.drawcoastlines(zorder=2)
        mlb.drawcountries(linewidth=1.0, zorder=2)
        mub.drawcoastlines(zorder=2)
        mub.drawcountries(linewidth=1.0, zorder=2)
        cb = ColorbarBase(cax, cmap=cmap, norm=Normalize(vmin=self.vmin,
                                                         vmax=self.vmax),
                         orientation=cborientation, extend=self.extend)
        cb.set_label(self.cb_label)
        return mlb, mub
def scale(args):
    """
    Draws the variable scale that is placed over the map.
    Returns a BytesIO object.
    """

    dataset_name = args.get("dataset")
    config = DatasetConfig(dataset_name)
    scale = args.get("scale")
    scale = [float(component) for component in scale.split(",")]

    variable = args.get("variable")
    variable = variable.split(",")

    if len(variable) > 1:
        variable_unit = config.variable[",".join(variable)].unit
        variable_name = config.variable[",".join(variable)].name
    else:
        variable_unit = config.variable[variable[0]].unit
        variable_name = config.variable[variable[0]].name

    cmap = colormap.find_colormap(variable_name)

    if len(variable) == 2:
        cmap = colormap.colormaps.get("speed")

    fig = plt.figure(figsize=(2, 5), dpi=75)
    ax = fig.add_axes([0.05, 0.05, 0.25, 0.9])
    norm = matplotlib.colors.Normalize(vmin=scale[0], vmax=scale[1])

    formatter = ScalarFormatter()
    formatter.set_powerlimits((-3, 4))
    bar = ColorbarBase(ax,
                       cmap=cmap,
                       norm=norm,
                       orientation="vertical",
                       format=formatter)
    if variable_name == "Potential Sub Surface Channel":
        bar.set_ticks([0, 1], True)

    bar.set_label("%s (%s)" %
                  (variable_name.title(), utils.mathtext(variable_unit)),
                  fontsize=12)
    # Increase tick font size
    bar.ax.tick_params(labelsize=12)

    buf = BytesIO()
    plt.savefig(
        buf,
        format="png",
        dpi="figure",
        transparent=False,
        bbox_inches="tight",
        pad_inches=0.05,
    )
    plt.close(fig)

    buf.seek(0)  # Move buffer back to beginning
    return buf
Exemplo n.º 6
0
def display_displacements(simulation_folder, lower_percentile=70, upper_percentile=99.7, save_plot = True, arrow_factor=4):
    """
    show the total displacement field or the masked range of displacements by size
    simulation_folder: path to simulation folder
    lower_percentile and upper_percentile give range of deformationsize which is used
    as a mask 
    save_plot: option to save the plot to the simulation folder
    arrow_factor: scales the arrow length in the plot
    To increase plotting speed you might increase the lower percentile (e.g 30 instead 0)
    """
    # load in deformations and coordinates
    r =  np.genfromtxt(os.path.join(simulation_folder, "R.dat"))       # positions
    u =  np.genfromtxt(os.path.join(simulation_folder, "Ufound.dat"))     #deformations  
    uabs = np.sqrt(np.sum(u ** 2., axis=1))   # absolute values for filtering
   
    # filter displacements by absolute size
    mask = (uabs > np.percentile(uabs, lower_percentile)) & (uabs < np.percentile(uabs, upper_percentile))
    r2 = r[mask]
    u2 = u[mask]
    uabs2 = uabs[mask]
    
    # plot the masked deformation
    fig = plt.figure()
    ax1 = fig.gca(projection='3d', label='fitted-displ', rasterized=True)

    color_bounds1 =  np.array([np.percentile(uabs2, 0), np.percentile(uabs2, 99.8)]) * 10 ** 6  

    np.random.seed(1234)
    for r2i, u2i, uabs2i in tqdm(zip(r2 * 10 ** 6, u2 * 10 ** 6, uabs2 * (10 ** 6))):
        # if np.random.uniform(0, 1) < 0.2:  # uabs2i/u_upper:
        color = plt.cm.jet(((uabs2i - color_bounds1[0]) / (color_bounds1[1] - color_bounds1[0])))
        alpha = 1. - (r2i[0] - r2i[1]) / (270. * 0.5)
    
        if alpha > 1:
            alpha = 1.
        if alpha < 0:
            alpha = 0.
    
        plt.quiver(r2i[0], r2i[1], r2i[2], u2i[0], u2i[1], u2i[2], length=uabs2i * arrow_factor ,
                   color=color, arrow_length_ratio=0, alpha=alpha, pivot='tip', linewidth=0.5)
   
    # plot colorbar   ---------------------------------------------------------
    cbaxes = fig.add_axes([0.15, 0.1, 0.125, 0.010])
    cmap = plt.cm.jet
    norm = plt.Normalize(vmin=color_bounds1[0], vmax=color_bounds1[1])
    cb1 = ColorbarBase(cbaxes, cmap=cmap, norm=norm, orientation='horizontal')
    cb1.set_label('Displacements [µm]')
    tick_locator = ticker.MaxNLocator(nbins=3)
    cb1.locator = tick_locator
    cb1.update_ticks()

    ax1.w_xaxis.set_pane_color((0.2, 0.2, 0.2, 1.0))
    ax1.w_yaxis.set_pane_color((0.2, 0.2, 0.2, 1.0))
    ax1.w_zaxis.set_pane_color((0.2, 0.2, 0.2, 1.0))
    
    if save_plot:
        plt.savefig( os.path.join(simulation_folder,'deformations_plot_lower_{}_upper_{}.png'.format(lower_percentile, upper_percentile)), dpi=500, bbox_inches="tight", pad_inches=0)
         
    return
Exemplo n.º 7
0
def plotter(fdict):
    """ Go """
    ctx = get_autoplot_context(fdict, get_description())
    station = ctx['station']
    days = ctx['days']
    varname = ctx['var']
    df = get_data(ctx)
    if df.empty:
        raise NoDataFound('Error, no results returned!')

    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_axes([0.1, 0.3, 0.75, 0.6])
    lax = fig.add_axes([0.1, 0.1, 0.75, 0.2])
    cax = fig.add_axes([0.87, 0.3, 0.03, 0.6])
    title = PDICT.get(varname)
    if days == 1:
        title = title.replace("Average ", "")
    ax.set_title(("%s [%s]\n%i Day Period with %s"
                  ) % (ctx['_nt'].sts[station]['name'], station, days, title))
    cmap = plt.get_cmap(ctx['cmap'])
    minval = df[XREF[varname]].min() - 1.
    if varname == 'wettest' and minval < 0:
        minval = 0
    maxval = df[XREF[varname]].max() + 1.
    ramp = np.linspace(minval, maxval, min([int(maxval - minval), 10]),
                       dtype='i')
    norm = mpcolors.BoundaryNorm(ramp, cmap.N)
    cb = ColorbarBase(cax, norm=norm, cmap=cmap)
    cb.set_label("inch" if varname == 'wettest' else r"$^\circ$F")
    ax.barh(df.index.values, [days]*len(df.index), left=df['doy'].values,
            color=cmap(norm(df[XREF[varname]].values)))
    ax.grid(True)
    lax.grid(True)
    xticks = []
    xticklabels = []
    for i in np.arange(df['doy'].min() - 5, df['doy'].max() + 5, 1):
        ts = datetime.datetime(2000, 1, 1) + datetime.timedelta(days=int(i))
        if ts.day == 1:
            xticks.append(i)
            xticklabels.append(ts.strftime("%-d %b"))
    ax.set_xticks(xticks)
    lax.set_xticks(xticks)
    lax.set_xticklabels(xticklabels)

    counts = np.zeros(366*2)
    for _, row in df.iterrows():
        counts[int(row['doy']):int(row['doy'] + days)] += 1

    lax.bar(np.arange(366*2), counts, edgecolor='blue', facecolor='blue')
    lax.set_ylabel("Years")
    lax.text(0.02, 0.9, "Frequency of Day\nwithin period",
             transform=lax.transAxes, va='top')
    ax.set_ylim(df.index.values.min() - 3, df.index.values.max() + 3)

    ax.set_xlim(df['doy'].min() - 10, df['doy'].max() + 10)
    lax.set_xlim(df['doy'].min() - 10, df['doy'].max() + 10)
    ax.yaxis.set_major_locator(MaxNLocator(prune='lower'))
    return fig, df
Exemplo n.º 8
0
def scale(args):
    dataset_name = args.get('dataset')
    scale = args.get('scale')
    scale = [float(component) for component in scale.split(',')]

    variable = args.get('variable')
    if variable.endswith('_anom'):
        variable = variable[0:-5]
        anom = True
    else:
        anom = False

    variable = variable.split(',')

    with open_dataset(get_dataset_url(dataset_name)) as dataset:
        variable_unit = get_variable_unit(dataset_name,
                                          dataset.variables[variable[0]])
        variable_name = get_variable_name(dataset_name,
                                          dataset.variables[variable[0]])

    if variable_unit.startswith("Kelvin"):
        variable_unit = "Celsius"

    if anom:
        cmap = colormap.colormaps['anomaly']
        variable_name = gettext("%s Anomaly") % variable_name
    else:
        cmap = colormap.find_colormap(variable_name)

    if len(variable) == 2:
        if not anom:
            cmap = colormap.colormaps.get('speed')

        variable_name = re.sub(
            r"(?i)( x | y |zonal |meridional |northward |eastward )", " ",
            variable_name)
        variable_name = re.sub(r" +", " ", variable_name)

    fig = plt.figure(figsize=(2, 5), dpi=75)
    ax = fig.add_axes([0.05, 0.05, 0.25, 0.9])
    norm = matplotlib.colors.Normalize(vmin=scale[0], vmax=scale[1])

    formatter = ScalarFormatter()
    formatter.set_powerlimits((-3, 4))
    bar = ColorbarBase(ax, cmap=cmap, norm=norm, orientation='vertical',
                       format=formatter)
    bar.set_label("%s (%s)" % (variable_name.title(),
                               utils.mathtext(variable_unit)))

    buf = StringIO()
    try:
        plt.savefig(buf, format='png', dpi='figure', transparent=False,
                    bbox_inches='tight', pad_inches=0.05)
        plt.close(fig)
        return buf.getvalue()
    finally:
        buf.close()
Exemplo n.º 9
0
def MakeReflectColorbar(ax=None, colorbarLabel="Reflectivity [dBZ]", **kwargs):
    # Probably need a smarter way to allow fine-grained control of properties
    # like fontsize and such...
    if ax is None:
        ax = plt.gca()

    cbar = ColorbarBase(ax, cmap=NWS_Reflect["ref_table"], norm=NWS_Reflect["norm"], **kwargs)
    cbar.set_label(colorbarLabel)
    return cbar
Exemplo n.º 10
0
def scale(args):
    dataset_name = args.get('dataset')
    scale = args.get('scale')
    scale = [float(component) for component in scale.split(',')]

    variable = args.get('variable')
    if variable.endswith('_anom'):
        variable = variable[0:-5]
        anom = True
    else:
        anom = False

    variable = variable.split(',')

    with open_dataset(get_dataset_url(dataset_name)) as dataset:
        variable_unit = get_variable_unit(dataset_name,
                                          dataset.variables[variable[0]])
        variable_name = get_variable_name(dataset_name,
                                          dataset.variables[variable[0]])

    if variable_unit.startswith("Kelvin"):
        variable_unit = "Celsius"

    if anom:
        cmap = colormap.colormaps['anomaly']
        variable_name = gettext("%s Anomaly") % variable_name
    else:
        cmap = colormap.find_colormap(variable_name)

    if len(variable) == 2:
        if not anom:
            cmap = colormap.colormaps.get('speed')

        variable_name = re.sub(
            r"(?i)( x | y |zonal |meridional |northward |eastward )", " ",
            variable_name)
        variable_name = re.sub(r" +", " ", variable_name)

    fig = plt.figure(figsize=(2, 5), dpi=75)
    ax = fig.add_axes([0.05, 0.05, 0.25, 0.9])
    norm = matplotlib.colors.Normalize(vmin=scale[0], vmax=scale[1])

    formatter = ScalarFormatter()
    formatter.set_powerlimits((-3, 4))
    bar = ColorbarBase(ax, cmap=cmap, norm=norm, orientation='vertical',
                       format=formatter)
    bar.set_label("%s (%s)" % (variable_name.title(),
                               utils.mathtext(variable_unit)))

    buf = StringIO()
    try:
        plt.savefig(buf, format='png', dpi='figure', transparent=False,
                    bbox_inches='tight', pad_inches=0.05)
        plt.close(fig)
        return buf.getvalue()
    finally:
        buf.close()
Exemplo n.º 11
0
def create_colorbar(cmap, norm, title=None):
    # Make a figure and axes with dimensions as desired.
    fig = Figure(figsize=(4,0.2))
    canvas = FigureCanvasAgg(fig)
    ax = fig.add_axes([0.005, 0.1, 0.985, 0.85])

    cb = ColorbarBase(ax, cmap=cmap, norm=norm, orientation='horizontal', format=NullFormatter(), ticks=NullLocator() )
    if title:
        cb.set_label(title, fontsize=12)
    fig.savefig('/home/dotcloud/data/media/plot/colorbar.png', format='png', transparent=True)
Exemplo n.º 12
0
def plot(countries, values, label='', clim=None, verbose=False):
    """
    Usage: worldmap.plot(countries, values [, label] [, clim])
    """
    countries_shp = shpreader.natural_earth(resolution='110m',
                                            category='cultural',
                                            name='admin_0_countries')
    ## Create a plot
    fig = plt.figure()
    ax = plt.axes(projection=ccrs.PlateCarree())
    ## Create a colormap
    cmap = plt.get_cmap('RdYlGn_r')
    if clim:
        vmin = clim[0]
        vmax = clim[1]
    else:
        val = values[np.isfinite(values)]
        mean = val.mean()
        std = val.std()
        vmin = mean - 2 * std
        vmax = mean + 2 * std
    norm = Normalize(vmin=vmin, vmax=vmax)
    smap = ScalarMappable(norm=norm, cmap=cmap)
    ax2 = fig.add_axes([0.3, 0.18, 0.4, 0.03])
    cbar = ColorbarBase(ax2, cmap=cmap, norm=norm, orientation='horizontal')
    cbar.set_label(label)
    ## Add countries to the map
    for country in shpreader.Reader(countries_shp).records():
        countrycode = country.attributes['adm0_a3']
        countryname = country.attributes['name_long']
        ## Check for country code consistency
        if countrycode == 'SDS':  #South Sudan
            countrycode = 'SSD'
        elif countrycode == 'ROU':  #Romania
            countrycode = 'ROM'
        elif countrycode == 'COD':  #Dem. Rep. Congo
            countrycode = 'ZAR'
        elif countrycode == 'KOS':  #Kosovo
            countrycode = 'KSV'
        if countrycode in countries:
            val = values[countries == countrycode]
            if np.isfinite(val):
                color = smap.to_rgba(val)
            else:
                color = 'grey'
        else:
            color = 'w'
            if verbose:
                print("No data available for " + countrycode + ": " +
                      countryname)
        ax.add_geometries(country.geometry,
                          ccrs.PlateCarree(),
                          facecolor=color,
                          label=countryname)
    plt.show()
Exemplo n.º 13
0
def MakeReflectColorbar(ax=None, colorbarLabel="Reflectivity [dBZ]", **kwargs):
    # Probably need a smarter way to allow fine-grained control of properties
    # like fontsize and such...
    if ax is None:
        ax = plt.gca()

    cbar = ColorbarBase(ax,
                        cmap=NWS_Reflect['ref_table'],
                        norm=NWS_Reflect['norm'],
                        **kwargs)
    cbar.set_label(colorbarLabel)
    return cbar
Exemplo n.º 14
0
def scale(args):
    dataset_name = args.get('dataset')
    config = DatasetConfig(dataset_name)
    scale = args.get('scale')
    scale = [float(component) for component in scale.split(',')]

    variable = args.get('variable')
    variable = variable.split(',')

    with open_dataset(config) as dataset:
        if len(variable) > 1:
            variable_unit = config.variable[",".join(variable)].unit
            variable_name = config.variable[",".join(variable)].name
        else:
            variable_unit = config.variable[dataset.variables[
                variable[0]]].unit
            variable_name = config.variable[dataset.variables[
                variable[0]]].name

    cmap = colormap.find_colormap(variable_name)

    if len(variable) == 2:
        cmap = colormap.colormaps.get('speed')

    fig = plt.figure(figsize=(2, 5), dpi=75)
    ax = fig.add_axes([0.05, 0.05, 0.25, 0.9])
    norm = matplotlib.colors.Normalize(vmin=scale[0], vmax=scale[1])

    formatter = ScalarFormatter()
    formatter.set_powerlimits((-3, 4))
    bar = ColorbarBase(ax,
                       cmap=cmap,
                       norm=norm,
                       orientation='vertical',
                       format=formatter)
    bar.set_label("%s (%s)" %
                  (variable_name.title(), utils.mathtext(variable_unit)),
                  fontsize=12)
    # Increase tick font size
    bar.ax.tick_params(labelsize=12)

    buf = BytesIO()
    plt.savefig(buf,
                format='png',
                dpi='figure',
                transparent=False,
                bbox_inches='tight',
                pad_inches=0.05)
    plt.close(fig)

    buf.seek(0)  # Move buffer back to beginning
    return buf
Exemplo n.º 15
0
 def update(frame):
     arr = var.isel({anim_dim: frame}).data
     ax.pcolor(lon, lat, arr, transform=proj, **kwargs)
     if add_title:
         ax.set_title(_title_creation(data, {**indexes, anim_dim: frame}))
     if add_cbar:
         cax.clear()
         cbar = ColorbarBase(cax,
                             boundaries=np.unique(
                                 arr[~np.isnan(arr)]).flatten(),
                             **kwargs)
         cbar.set_label(wrap("{} ({})".format(name,
                                              var.attrs.get('units'))))
Exemplo n.º 16
0
def swarmplot_with_cbar(cmap, cbar_label, *args, **kwargs):
    fig = plt.gcf()
    ax = sns.swarmplot(*args, **kwargs)
    # remove the legend, because we want to set a colorbar instead
    ax.legend().remove()
    ## create colorbar ##
    divider = make_axes_locatable(ax)
    ax_cb = divider.new_horizontal(size="3%", pad=0.05)
    fig.add_axes(ax_cb)
    cb = ColorbarBase(ax_cb, cmap=cmap, orientation='vertical')
    cb.set_label(cbar_label, labelpad=10)

    return fig
Exemplo n.º 17
0
def _scatter_legends(df, ax, fig, cmap, ck, ondata: bool, onside: bool,
                     fontsize: float, n_per_col: int, scale: float, ls: float,
                     cs: float) -> None:
    from matplotlib.colors import Normalize
    from matplotlib.colorbar import ColorbarBase

    x, y, vc = df.columns[:3]
    v = df[vc]
    if v.nunique() <= 1:
        return None
    if v.dtype.name == 'category':
        centers = df[[x, y, vc]].groupby(vc).median().T
        for i in centers:
            if ondata:
                ax.text(centers[i][x],
                        centers[i][y],
                        i,
                        fontsize=fontsize,
                        ha='center',
                        va='center')
            if onside:
                ax.scatter([float(centers[i][x])], [float(centers[i][y])],
                           c=ck[i],
                           label=i,
                           alpha=1,
                           s=0.01)
        if onside:
            n_cols = v.nunique() // n_per_col
            if v.nunique() % n_per_col > 0:
                n_cols += 1
            ax.legend(ncol=n_cols,
                      loc=(1, 0),
                      frameon=False,
                      fontsize=fontsize,
                      markerscale=scale,
                      labelspacing=ls,
                      columnspacing=cs)
    else:
        if fig is not None:
            cbaxes = fig.add_axes([0.2, 1, 0.6, 0.05])
            norm = Normalize(vmin=v.min(), vmax=v.max())
            cb = ColorbarBase(cbaxes,
                              cmap=cmap,
                              norm=norm,
                              orientation='horizontal')
            cb.set_label(vc, fontsize=fontsize)
            cb.ax.xaxis.set_label_position('top')
        else:
            logger.warning(
                "Not plotting the colorbar because fig object was not passed")
    return None
Exemplo n.º 18
0
def plot(countries,values,label='',clim=None,verbose=False):
    """
    Usage: worldmap.plot(countries, values [, label] [, clim])
    """
    countries_shp = shpreader.natural_earth(resolution='110m',category='cultural',
                                            name='admin_0_countries')
    ## Create a plot
    fig = plt.figure()
    ax = plt.axes(projection=ccrs.PlateCarree())
    ## Create a colormap
    cmap = plt.get_cmap('RdYlGn_r')
    if clim:
       vmin = clim[0]
       vmax = clim[1]
    else:
       val = values[np.isfinite(values)]
       mean = val.mean()
       std = val.std()
       vmin = mean-2*std
       vmax = mean+2*std
    norm = Normalize(vmin=vmin,vmax=vmax)
    smap = ScalarMappable(norm=norm,cmap=cmap)
    ax2 = fig.add_axes([0.3, 0.18, 0.4, 0.03])
    cbar = ColorbarBase(ax2,cmap=cmap,norm=norm,orientation='horizontal')
    cbar.set_label(label)
    ## Add countries to the map
    for country in shpreader.Reader(countries_shp).records():
        countrycode = country.attributes['adm0_a3']
        countryname = country.attributes['name_long']
        ## Check for country code consistency
        if countrycode == 'SDS': #South Sudan
           countrycode = 'SSD'
        elif countrycode == 'ROU': #Romania
           countrycode = 'ROM'
        elif countrycode == 'COD': #Dem. Rep. Congo
           countrycode = 'ZAR'
        elif countrycode == 'KOS': #Kosovo
           countrycode = 'KSV'
        if countrycode in countries:
           val = values[countries==countrycode]
           if np.isfinite(val):
              color = smap.to_rgba(val)
           else:
              color = 'grey'
        else:
           color = 'w'
           if verbose:
              print("No data available for "+countrycode+": "+countryname)
        ax.add_geometries(country.geometry,ccrs.PlateCarree(),facecolor=color,label=countryname)
    plt.show()
Exemplo n.º 19
0
    def error_plot(self, ax_lb, ax_ub, cax, cborientation='vertical'):
        # plot the error map
        ttP_lb = np.zeros((self.dims[1::]))
        ttP_ub = ttP_lb.copy()
        for _i1 in xrange(self.dims[1]):
            for _i2 in xrange(self.dims[2]):
                for _i3 in xrange(self.dims[3]):
                    ttP_lb[_i1, _i2,
                           _i3] = scoreatpercentile(self.ttP[:, _i1, _i2, _i3],
                                                    16)
                    ttP_ub[_i1, _i2,
                           _i3] = scoreatpercentile(self.ttP[:, _i1, _i2, _i3],
                                                    84)

        mlb = copy(self.m)
        mlb.ax = ax_lb
        mub = copy(self.m)
        mub.ax = ax_ub

        cmap = cm.get_cmap(self.cmapname)
        cmap.set_over('grey')

        mlb.contourf(self.x,
                     self.y,
                     ttP_lb[:, :, 0],
                     cmap=cmap,
                     levels=np.arange(self.vmin, self.vmax + 0.5, 0.5),
                     norm=Normalize(vmin=self.vmin, vmax=self.vmax),
                     extend=self.extend)
        mub.contourf(self.x,
                     self.y,
                     ttP_ub[:, :, 0],
                     cmap=cmap,
                     levels=np.arange(self.vmin, self.vmax + 0.5, 0.5),
                     norm=Normalize(vmin=self.vmin, vmax=self.vmax),
                     extend=self.extend)
        mlb.drawcoastlines(zorder=2)
        mlb.drawcountries(linewidth=1.0, zorder=2)
        mub.drawcoastlines(zorder=2)
        mub.drawcountries(linewidth=1.0, zorder=2)
        cb = ColorbarBase(cax,
                          cmap=cmap,
                          norm=Normalize(vmin=self.vmin, vmax=self.vmax),
                          orientation=cborientation,
                          extend=self.extend)
        cb.set_label(self.cb_label)
        return mlb, mub
Exemplo n.º 20
0
def create_colorbar(cmap, norm, title=None):
    # Make a figure and axes with dimensions as desired.
    fig = Figure(figsize=(4, 0.2))
    canvas = FigureCanvasAgg(fig)
    ax = fig.add_axes([0.005, 0.1, 0.985, 0.85])

    cb = ColorbarBase(ax,
                      cmap=cmap,
                      norm=norm,
                      orientation='horizontal',
                      format=NullFormatter(),
                      ticks=NullLocator())
    if title:
        cb.set_label(title, fontsize=12)
    fig.savefig('/home/dotcloud/data/media/plot/colorbar.png',
                format='png',
                transparent=True)
Exemplo n.º 21
0
def show_colormap(base):
    """Display a colormap.

    **Argument:**

    *base*
        The name of a base colormap or a `ColormapBase` instance to plot.

    """
    import matplotlib.pyplot as plt
    from matplotlib.colorbar import ColorbarBase
    try:
        base = get_colormap_base(base)
    except ValueError:
        pass
    cmap = create_colormap(base.ncolors, base=base.name)
    fig = plt.figure(figsize=(9, .7))
    ax = fig.add_axes([.01, .35, .98, .63])
    cb = ColorbarBase(ax, cmap=cmap, orientation='horizontal', ticks=[])
    cb.set_label('{:s}: {:d} colors'.format(base.name, base.ncolors))
    plt.show()
Exemplo n.º 22
0
 def get_colorbar(self,title,label,min,max):
     '''Create a colorbar from given data.  Returns a png image as a string.'''
     
     fig=pylab.figure(figsize=(2,5))
     ax=fig.add_axes([0.35,0.03,0.1,0.9])
     norm=self.get_norm(min,max)
     formatter=self.get_formatter()
     if formatter:
         cb1 = ColorbarBase(ax,norm=norm,format=formatter,spacing='proportional',orientation='vertical')
     else:
         cb1 = ColorbarBase(ax,norm=norm,spacing='proportional',orientation='vertical')
     cb1.set_label(label,color='1')
     ax.set_title(title,color='1')
     for tl in ax.get_yticklabels():
         tl.set_color('1')
     im=cStringIO.StringIO()
     fig.savefig(im,dpi=300,format='png',transparent=True)
     pylab.close(fig)
     s=im.getvalue()
     im.close()
     return s
Exemplo n.º 23
0
    axpbar = plt.axes([0, 0, 101, 101], zorder=2)
    axpbar.spines['bottom'].set_color('w')
    axpbar.spines['top'].set_color('w')
    axpbar.spines['left'].set_color('w')
    axpbar.spines['right'].set_color('w')
    axpbar.tick_params(axis='x', colors='w')
    axpbar.tick_params(axis='y', colors='w')
    axpbar.set_axes_locator(InsetPosition(ax1, [0.45, 0.91, 0.45, 0.05]))
    cb1 = ColorbarBase(axpbar,
                       cmap=cmap,
                       norm=cnorm,
                       orientation='horizontal',
                       ticks=[0.0, 0.25, 0.5, 0.75, 1.0])
    cb1.outline.set_edgecolor('w')
    cb1.set_label(r'$\Delta^{op}$ (arb.)', color='w')

    ax2.plot(spectrum[:, 0], spectrum[:, 1] / np.max(spectrum[:, 1]), '-k')

    xs = np.linspace(np.min(l0), np.max(l0), 400)
    norm = w[wi] * np.sqrt(2 * np.pi)
    for j in range(npeaks):
        ax2.plot(xs,
                 norm * gauss(xs, w[wi], peak[j][wi, 1] - peak[j][wi, 2] / 2),
                 color='C' + str(j))
        ax2.plot(xs,
                 norm * gauss(xs, w[wi], peak[j][wi, 1] + peak[j][wi, 2] / 2),
                 color='C' + str(j))
        ax2.text(peak[j][wi, 1] - peak[j][wi, 2] / 2,
                 1.12,
                 r'$\lambda_0 = $' + str(peak[j][wi, 1]) + ' nm',
Exemplo n.º 24
0
def create_shot_chart(made_shots, missed_shots, filename, title, plot_type='hexbin', hex_size=2, **kwargs):

    made_x = np.array([shot.shot_x for shot in made_shots])
    made_y = np.array([shot.shot_y for shot in made_shots])
    missed_x = np.array([shot.shot_x for shot in missed_shots])
    missed_y = np.array([shot.shot_y for shot in missed_shots])

    num_made = float(len(made_shots))
    num_missed = float(len(missed_shots))

    frac_made = 100 * (num_made / (num_made + num_missed))
    frac_missed = 100 - frac_made

    shot_distances_made = [euclidean(shot.shot_x, shot.shot_y) for shot in made_shots]
    shot_distances_missed = [euclidean(shot.shot_x, shot.shot_y) for shot in missed_shots]

    bins = np.linspace(0, 50, 26)

    frac_made_arr = np.zeros(len(bins))
    shots_taken = np.zeros(len(bins))
    for i, bin in enumerate(bins[:-1]):
        bin_made = [loc for loc in shot_distances_made if loc > bin and loc < bins[i + 1]]
        bin_missed = [loc for loc in shot_distances_missed if loc > bin and loc < bins[i + 1]]
        if len(bin_made) != 0 and len(bin_missed) != 0:
            frac_made_arr[i] = (float(len(bin_made)) / float(len(bin_made) + len(bin_missed)))
        shots_taken[i] = len(bin_made) + len(bin_missed)

    if plot_type == 'distance':
        mpl.clf()
        ax1 = mpl.subplot(111)
        # l1 = ax1.plot(bins, frac_made_arr * 100, 'go-', label='% made')
        ax2 = ax1.twinx()
        # l2 = ax2.plot(bins, shots_taken, 'rs-', label='shots taken')

        smooth_x = np.linspace(0, 40, 300)
        smooth_made = spline(bins, frac_made_arr * 100, smooth_x)
        smooth_taken = spline(bins, shots_taken, smooth_x)

        l1 = ax1.plot(smooth_x, smooth_made, 'g-', label='% made')
        l2 = ax2.plot(smooth_x, smooth_taken, 'r-', label='# shots taken')

        ax1.set_xlabel('Distance from basket')
        ax1.set_ylabel('Percentage made')
        ax2.set_ylabel('Number of shots taken')

        lns = l1 + l2
        labels = [l.get_label() for l in lns]

        ax1.set_xlim(0, 40)
        ax2.set_ylim(0, 40)

        mpl.title(title)
        mpl.legend(lns, labels)
        ax1.grid(True)

    if plot_type == 'hexbin' or plot_type == 'hexbin_contour':

        return_cells = False
        if 'return_cells' in kwargs:
            return_cells = kwargs['return_cells']

        hexes = create_hexes(hex_size)
        fig = mpl.figure()

        gs = gridspec.GridSpec(1, 2, width_ratios=[1, 10])

        ax_cb = mpl.subplot(gs[0,0])
        ax = mpl.subplot(gs[0,1])

        draw_court(ax)

        for x, y in zip(made_x, made_y):
            cell = find_hex_from_xy(hexes, x, y, s=hex_size)
            if cell is not None:
                if is_shot_three(x, y):
                    #print x, y, euclidean((x, y), (0, 0))
                    cell['threes'] += 1
                cell['made'] += 1
            else:
                ## this should never happen
                print 'made shot not in cell: ({}, {})'.format(x, y)

        for x, y in zip(missed_x, missed_y):
            cell = find_hex_from_xy(hexes, x, y, s=hex_size)
            if cell is not None:
                #if is_shot_three(x, y):
                #    print x, y, euclidean((x, y), (0, 0))
                cell['missed'] += 1
            else:
                ## this should never happen
                print 'missed shot not in cell: ({}, {})'.format(x, y)

        max_attempts = max([cell['made'] + cell['missed'] for cell in hexes])
        min_attempts = min([cell['made'] + cell['missed'] for cell in hexes if cell['made'] + cell['missed'] > 0])
        total_attempts = sum([cell['made'] + cell['missed'] for cell in hexes])

        max_attempts_frac = 100.0 * max_attempts / total_attempts
        min_attempts_frac = 100.0 * min_attempts / total_attempts

        #print 'max_attempts: {}, min_attempts: {}, total_attempts: {}'.format(max_attempts, min_attempts, total_attempts)
        #print 'max_attempts_frac: {}, min_attempts_frac: {}'.format(max_attempts_frac, min_attempts_frac)

        if 'scale_factor' in kwargs:
            max_attempts_frac = max_attempts_frac * kwargs['scale_factor']
        else:
            # default scale factor
            # max_attempts_frac = min_attempts_frac * 64
            pass

        max_size = hex_size
        min_size = hex_size / 8.0

        if max_attempts > 1:
            m = (float(max_size) - min_size) / (max_attempts_frac - 1)
            b = min_size - m
        else:
            m = max_size / max_attempts_frac
            b = 0

        #print 'm: {}, b: {}, max_size: {}, min_size: {}'.format(m, b, max_size, min_size)

        cm = mpl.cm.YlOrBr
        norm = Normalize(0, 1.5)

        total_made = 0
        total_threes = 0
        for cell in hexes:
            attempts = cell['made'] + cell['missed']
            #total_attempts += attempts
            if attempts > 0:
                attempts_frac = 100.0 * attempts / total_attempts
                total_made += cell['made']
                total_threes += cell['threes']
                efg = (cell['made'] + 0.5 * cell['threes']) / attempts
                cell['efg'] = efg
                scaled_attempts = min(attempts_frac, max_attempts_frac)
                size = scaled_attempts * m + b
                #print size, scaled_attempts, attempts_frac, max_attempts_frac
                #print size
                if plot_type == 'hexbin' and not return_cells:
                    cell['patch'] = RegularPolygon((cell['x'], cell['y']), 6, size, orientation=np.pi/6, color=cm(norm(efg)), alpha=0.75)
                    outline = RegularPolygon((cell['x'], cell['y']), 6, hex_size, orientation=np.pi/6, fill=False, color='y', linestyle='dotted')
                    ax.add_patch(cell['patch'])
                    ax.add_patch(outline)
                    if 'print_pct' in kwargs and kwargs['print_pct'] == True:
                        ax.text(cell['x'] - 1, cell['y'] - 1, '{0:2.2f}'.format(attempts_frac))

        if return_cells:
            return hexes

        if plot_type == 'hexbin':
            cb = ColorbarBase(ax_cb, cmap=cm, norm=norm, orientation='vertical')
            cb.set_label('Effective Field Goal Percentage')
            mpl.tight_layout()

        if plot_type == 'hexbin_contour':
            efg = []
            bin_x = [cell['x'] for cell in hexes]
            bin_y = [cell['y'] for cell in hexes]
            efg = [cell['efg'] for cell in hexes]

            xi = np.linspace(-25, 25, 200)
            yi = np.linspace(0, 47.5, 200)
            zi = np.griddata(bin_x, bin_y, efg, xi, yi)

            mpl.contourf(xi, yi, zi, 5, cmap=mpl.cm.YlOrBr)
            mpl.colorbar()

        if 'overplot_shots' in kwargs:
            if kwargs['overplot_shots'] == True:
                mpl.plot(made_x, made_y, 'go')
                mpl.plot(missed_x, missed_y, 'rs')

        ax.text(0.02, 0.96, 'Total attempts: {}'.format(total_attempts), transform=ax.transAxes)
        ax.text(0.02, 0.93, 'Total made: {}'.format(total_made), transform=ax.transAxes)
        ax.text(0.02, 0.90, 'Total threes made: {}'.format(total_threes), transform=ax.transAxes)
        ax.text(0.02, 0.87, 'Total twos made: {}'.format(total_made - total_threes), transform=ax.transAxes)
        if total_attempts > 0:
            efg = 100 * (total_made + 0.5 * total_threes) / total_attempts
        else:
            efg = 0
        ax.text(0.02, 0.84, 'eFG%: {0:2.2f}'.format(efg),
                    transform=ax.transAxes)

        ax.set_title(title, fontsize='small')

    if plot_type == 'xo':

        mpl.plot(made_x, made_y, 'go')
        mpl.plot(missed_x, missed_y, 'rd')

        mpl.title(title)

    if plot_type == '3d':

        from mpl_toolkits.mplot3d import Axes3D

        fig = mpl.figure()
        ax = fig.gca(projection='3d')
        surf = ax.plot_surface(X, Y, frac_counts, cmap=mpl.cm.coolwarm)

        mpl.show()

    plot_dir = os.path.split(filename)
    if not os.path.exists(plot_dir[0]):
        os.makedirs(plot_dir[0])
    mpl.savefig(filename)
Exemplo n.º 25
0
def drawGeoms(geoms,
              srs=4326,
              ax=None,
              simplificationFactor=5000,
              colorBy=None,
              figsize=(12, 12),
              xlim=None,
              ylim=None,
              fontsize=16,
              hideAxis=False,
              cbarPadding=0.01,
              cbarTitle=None,
              vmin=None,
              vmax=None,
              cmap="viridis",
              cbar=True,
              cbax=None,
              cbargs=None,
              leftMargin=0.01,
              rightMargin=0.01,
              topMargin=0.01,
              bottomMargin=0.01,
              **mplArgs):
    """Draw geometries onto a matplotlib figure
    
    * Each geometry type is displayed as an appropriate plotting type
        -> Points/ Multipoints are displayed as points using plt.plot(...)
        -> Lines/ MultiLines are displayed as lines using plt.plot(...)
        -> Polygons/ MultiPolygons are displayed as patches using the descartes 
           library
    * Each geometry can be given its own set of matplotlib plotting parameters

    Notes:
    ------
    This function does not call plt.show() for the final display of the figure.
    This must be done manually after calling this function. Otherwise 
    plt.savefig(...) can be called to save the output somewhere.

    Sometimes geometries will disappear because of the simplification procedure.
    If this happens, the procedure can be avoided by setting simplificationFactor
    to None. This will take much more memory and will take longer to plot, however

    Parameters:
    -----------
    geoms : ogr.Geometry or [ogr.Geometry, ] or pd.DataFrame
        The geometries to be drawn
          * If a DataFrame is given, the function looks for geometries under a
            columns named 'geom'
          * plotting arguments can be given by adding a column named 'MPL:****'
            where '****' stands in for the argument to be added
              - For geometries that should ignore this argument, set it as None

    srs : Anything acceptable to geokit.srs.loadSRS(); optional
        The srs in which to draw each geometry
          * If not given, longitude/latitude is assumed
          * Although geometries can be given in any SRS, it is very helpful if
            they are already provided in the correct SRS

    ax : matplotlib axis; optional
        The axis to draw the geometries on
          * If not given, a new axis is generated and returned

    simplificationFactor : float; optional
        The level to which geometries should be simplified. It can be thought of
        as the number of verticies allowed in either the X or Y dimension across
        the figure
          * A higher value means a more detailed plot, but may take longer to draw

    colorBy : str; optional
        The column in the geoms DataFrame to color by
          * Only useful when geoms is given as a DataFrame

    figsize : (int, int); optional
        The figure size to create when generating a new axis
          * If resultign figure looks wierd, altering the figure size is your best
            bet to make it look nicer

    xlim : (float, float); optional
        The x-axis limits

    ylim : (float, float); optional
        The y-axis limits

    fontsize : int; optional
        A base font size to apply to tick marks which appear
          * Titles and labels are given a size of 'fontsize' + 2

    hideAxis : bool; optional
        Instructs the created axis to hide its boundary
          * Only useful when generating a new axis

    cbarPadding : float; optional
        The spacing padding to add between the generated axis and the generated
        colorbar axis
          * Only useful when generating a new axis
          * Only useful when 'colorBy' is given

    cbarTitle : str; optional
        The title to give to the generated colorbar
          * If not given, but 'colorBy' is given, the same string for 'colorBy'
            is used
            * Only useful when 'colorBy' is given

    vmin : float; optional
        The minimum value to color
          * Only useful when 'colorBy' is given

    vmax : float; optional
        The maximum value to color
          * Only useful when 'colorBy' is given

    cmap : str or matplotlib ColorMap; optional
        The colormap to use when coloring
          * Only useful when 'colorBy' is given

    cbax : matplotlib axis; optional
        An explicitly given axis to use for drawing the colorbar
          * If not given, but 'colorBy' is given, an axis for the colorbar is 
            automatically generated
    
    cbargs : dict; optional
        keyword arguments to pass on when creating the colorbar 

    leftMargin : float; optional
        Additional margin to add to the left of the figure
          * Before using this, try adjusting the 'figsize'

    rightMargin : float; optional
        Additional margin to add to the left of the figure
          * Before using this, try adjusting the 'figsize'

    topMargin : float; optional
        Additional margin to add to the left of the figure
          * Before using this, try adjusting the 'figsize'

    bottomMargin : float; optional
        Additional margin to add to the left of the figure
          * Before using this, try adjusting the 'figsize'

    **mplArgs
        All other keyword arguments are passed on to the plotting functions called
        for each geometry
          * Will be applied to ALL geometries. Be careful since this can cause 
            errors when plotting geometries of different types
    
    Returns:
    --------
    A namedtuple containing:
       'ax' -> The map axis
       'handles' -> All geometry handles which were created in the order they were 
                    drawn
       'cbar' -> The colorbar handle if it was drawn

    """
    if isinstance(ax, AxHands): ax = ax.ax

    if ax is None:
        newAxis = True

        import matplotlib.pyplot as plt

        plt.figure(figsize=figsize)

        if colorBy is None:  # We don't need a colorbar
            if not hideAxis: leftMargin += 0.07

            ax = plt.axes([
                leftMargin, bottomMargin, 1 - (rightMargin + leftMargin),
                1 - (topMargin + bottomMargin)
            ])
            cbax = None

        else:  # We need a colorbar
            rightMargin += 0.08  # Add area on the right for colorbar text
            if not hideAxis:
                leftMargin += 0.07

            cbarExtraPad = 0.05
            cbarWidth = 0.04

            ax = plt.axes([
                leftMargin, bottomMargin,
                1 - (rightMargin + leftMargin + cbarWidth + cbarPadding),
                1 - (topMargin + bottomMargin)
            ])

            cbax = plt.axes([
                1 - (rightMargin + cbarWidth), bottomMargin + cbarExtraPad,
                cbarWidth, 1 - (topMargin + bottomMargin + 2 * cbarExtraPad)
            ])

        if hideAxis: ax.axis("off")
        else: ax.tick_params(labelsize=fontsize)
    else:
        newAxis = False

    # Be sure we have a list
    pargs = None
    isFrame = False
    if isinstance(geoms, ogr.Geometry):
        geoms = [
            geoms,
        ]

    elif isinstance(
            geoms,
            pd.DataFrame):  # We have a DataFrame with plotting arguments
        isFrame = True
        data = geoms.drop("geom", axis=1)
        geoms = geoms["geom"].values

        pargs = pd.DataFrame(index=data.index)
        for c in data.columns:
            if not c[:4] == "MPL:": continue
            pargs[c[4:]] = data[c]

        if pargs.size == 0: pargs = None

    else:  #Assume its an iterable
        geoms = list(geoms)

    # Check Geometry SRS
    if not srs is None:
        srs = loadSRS(srs)
        for gi, g in enumerate(geoms):
            gsrs = g.GetSpatialReference()
            if gsrs is None: continue  # Skip it if we don't know it...
            if not gsrs.IsSame(srs): geoms[gi] = transform(geoms[gi], srs)

    # Apply simplifications if required
    if not simplificationFactor is None:
        if xlim is None or ylim is None:
            xMin, yMin, xMax, yMax = 1e100, 1e100, -1e100, -1e100
            for g in geoms:
                _xMin, _xMax, _yMin, _yMax = g.GetEnvelope()

                xMin = min(_xMin, xMin)
                xMax = max(_xMax, xMax)
                yMin = min(_yMin, yMin)
                yMax = max(_yMax, yMax)

        if not xlim is None: xMin, xMax = xlim
        if not ylim is None: yMin, yMax = ylim

        simplificationValue = max(xMax - xMin,
                                  yMax - yMin) / simplificationFactor

        oGeoms = geoms
        geoms = []

        def doSimplify(g):
            ng = g.Simplify(simplificationValue)
            return ng

        for g in oGeoms:
            #carefulSimplification=False
            #if carefulSimplification and "MULTI" in g.GetGeometryName():
            if False and "MULTI" in g.GetGeometryName(
            ):  # This doesn't seem to help...
                subgeoms = []
                for gi in range(g.GetGeometryCount()):
                    ng = doSimplify(g.GetGeometryRef(gi))
                    subgeoms.append(ng)

                geoms.append(flatten(subgeoms))
            else:
                geoms.append(doSimplify(g))

    ### Handle color value
    if not colorBy is None:
        colorVals = data[colorBy].values

        if isinstance(cmap, str):
            from matplotlib import cm
            cmap = getattr(cm, cmap)

        cValMax = colorVals.max() if vmax is None else vmax
        cValMin = colorVals.min() if vmin is None else vmin

        _colorVals = [
            cmap(v) for v in (colorVals - cValMin) / (cValMax - cValMin)
        ]

    ### Do Plotting
    # make patches
    h = []

    for gi, g in enumerate(geoms):
        if not pargs is None:
            s = [not v is None for v in pargs.iloc[gi]]
            plotargs = pargs.iloc[gi, s].to_dict()
        else:
            plotargs = dict()
        plotargs.update(mplArgs)

        if not colorBy is None: colorVal = _colorVals[gi]
        else: colorVal = None

        # Determine type
        if g.GetGeometryName() == "POINT":
            h.append(drawPoint(g, plotargs, ax, colorVal))
        elif g.GetGeometryName() == "MULTIPOINT":
            h.append(drawMultiPoint(g, plotargs, ax, colorVal))
        elif g.GetGeometryName() == "LINESTRING":
            h.append(drawLine(g, plotargs, ax, colorVal))
        elif g.GetGeometryName() == "MULTILINESTRING":
            h.append(drawMultiLine(g, plotargs, ax, colorVal))
        elif g.GetGeometryName() == "LINEARRING":
            h.append(drawLinearRing(g, plotargs, ax, colorVal))
        elif g.GetGeometryName() == "POLYGON":
            h.append(drawPolygon(g, plotargs, ax, colorVal))
        elif g.GetGeometryName() == "MULTIPOLYGON":
            h.append(drawMultiPolygon(g, plotargs, ax, colorVal))
        else:
            msg = "Could not draw geometry of type:", pargs.index[
                gi], "->", g.GetGeometryName()
            warnings.warn(msg, UserWarning)

    # Add the colorbar, maybe
    if not colorBy is None and cbar:
        from matplotlib.colorbar import ColorbarBase
        from matplotlib.colors import Normalize

        norm = Normalize(vmin=cValMin, vmax=cValMax)
        tmp = dict(cmap=cmap, norm=norm, orientation='vertical')
        if not cbargs is None: tmp.update(cbargs)
        cbar = ColorbarBase(cbax, **tmp)
        cbar.ax.tick_params(labelsize=fontsize)
        cbar.set_label(colorBy if cbarTitle is None else cbarTitle,
                       fontsize=fontsize + 2)
    else:
        cbar = None

    # Do some formatting
    if newAxis:
        ax.set_aspect('equal')
        ax.autoscale(enable=True)

    if not xlim is None: ax.set_xlim(*xlim)
    if not ylim is None: ax.set_ylim(*ylim)

    # Organize return
    if isFrame:
        return AxHands(ax, pd.Series(h, index=data.index), cbar)
    else:
        return AxHands(ax, h, cbar)
Exemplo n.º 26
0
class Plotter3d():
    def __init__(self, notify, figure, settings):
        self.notify = notify
        self.figure = figure
        self.settings = settings
        self.axes = None
        self.plot = None
        self.extent = None
        self.threadPlot = None
        self.wireframe = settings.wireframe
        self.setup_plot()
        self.set_grid(settings.grid)

    def setup_plot(self):
        gs = GridSpec(1, 2, width_ratios=[9.5, 0.5])
        self.axes = self.figure.add_subplot(gs[0], projection='3d')

        numformatter = ScalarFormatter(useOffset=False)
        timeFormatter = DateFormatter("%H:%M:%S")

        self.axes.set_xlabel("Frequency (MHz)")
        self.axes.set_ylabel('Time')
        self.axes.set_zlabel('Level (dB)')
        self.axes.w_xaxis.set_pane_color(hex2color(self.settings.background))
        self.axes.w_yaxis.set_pane_color(hex2color(self.settings.background))
        self.axes.w_zaxis.set_pane_color(hex2color(self.settings.background))
        self.axes.xaxis.set_major_formatter(numformatter)
        self.axes.yaxis.set_major_formatter(timeFormatter)
        self.axes.zaxis.set_major_formatter(numformatter)
        self.axes.xaxis.set_minor_locator(AutoMinorLocator(10))
        self.axes.yaxis.set_minor_locator(AutoMinorLocator(10))
        self.axes.zaxis.set_minor_locator(AutoMinorLocator(10))
        self.axes.set_xlim(self.settings.start, self.settings.stop)
        now = time.time()
        self.axes.set_ylim(epoch_to_mpl(now), epoch_to_mpl(now - 10))
        self.axes.set_zlim(-50, 0)

        self.bar = self.figure.add_subplot(gs[1])
        norm = Normalize(vmin=-50, vmax=0)
        self.barBase = ColorbarBase(self.bar, norm=norm,
                                    cmap=cm.get_cmap(self.settings.colourMap))
        self.barBase.set_label('Level (dB)')

    def scale_plot(self, force=False):
        if self.extent is not None and self.plot is not None:
            if self.settings.autoF or force:
                self.axes.set_xlim(self.extent.get_f())
            if self.settings.autoL or force:
                self.axes.set_zlim(self.extent.get_l())
                self.plot.set_clim(self.extent.get_l())
                self.barBase.set_clim(self.extent.get_l())
                try:
                    self.barBase.draw_all()
                except:
                    pass
            if self.settings.autoT or force:
                self.axes.set_ylim(self.extent.get_t())

    def draw_measure(self, *args):
        pass

    def hide_measure(self):
        pass

    def redraw_plot(self):
        if self.figure is not None:
            post_event(self.notify, EventThreadStatus(Event.DRAW))

    def get_axes(self):
        return self.axes

    def get_plot_thread(self):
        return self.threadPlot

    def set_title(self, title):
        self.axes.set_title(title)

    def set_plot(self, data, extent, annotate=False):
        self.extent = extent
        self.threadPlot = ThreadPlot(self, self.axes,
                                     data, self.extent,
                                     self.settings.retainMax,
                                     self.settings.colourMap,
                                     self.settings.autoF,
                                     self.barBase,
                                     annotate)
        self.threadPlot.start()

    def clear_plots(self):
        children = self.axes.get_children()
        for child in children:
            if child.get_gid() is not None:
                if child.get_gid() == "plot" or child.get_gid() == "peak":
                    child.remove()

    def set_grid(self, on):
        self.axes.grid(on)
        self.redraw_plot()

    def set_colourmap(self, colourMap):
        if self.plot is not None:
            self.plot.set_cmap(colourMap)
        self.barBase.set_cmap(colourMap)
        try:
            self.barBase.draw_all()
        except:
            pass

    def close(self):
        self.figure.clear()
        self.figure = None
Exemplo n.º 27
0
def plot():
    global DATA, store
    c = Config(args.config)
    conf = PlotConf()
    conf = conf.new_child(c['scatterplot'].get('conf', {}))
    attrs = store.get_storer(path).attrs
    if hasattr(attrs, 'config') and conf.get('conf_overwrite', False):
        attrs.config['scatterplot'] = {}
        c.append(attrs.config)

    if not DATA.empty and 'newfields' in conf:
        for field, expr in conf['newfields'].items():
            logging.debug("executing DATA[{}] = {}]".format(field, expr))
            DATA[field] = eval(expr)
        logging.debug("done.")

    pcount = 0
    for p in c['scatterplot']['plots']:
        lcount = 0

        pconf = conf.new_child(p)

        plt.cla()
        plt.clf()
        plt.rcParams.update(pconf['rcParams'])

        if pconf['figsize']:
            plt.figure(figsize=pconf['figsize'])
        else:
            plt.figure()

        if pconf['fontsize'] != conf['fontsize']:
            plt.rcParams.update({'font.size': pconf['fontsize']})

        if pconf['colorbar_only']:
            plt.figure(figsize=(8, 0.25))
            ax = plt.gca()
            norm = Normalize(vmin=pconf['z-axis']['vmin'],
                             vmax=pconf['z-axis']['vmax'])
            if pconf['z-axis']['lognorm']:
                norm = LogNorm(vmin=pconf['z-axis']['vmin'],
                               vmax=pconf['z-axis']['vmax'])
            cbar = ColorbarBase(
                ax,
                norm=norm,
                cmap=pconf['cmap'],
                orientation=pconf['z-axis']['colorbar_orientation'])
            if pconf['z-axis']['colorbar_orientation'] == 'horizontal':
                ax.xaxis.set_label_position('top')
                ax.xaxis.set_ticks_position('top')
            if pconf['z-axis']['label']:
                cbar.set_label(pconf['z-axis']['label'])
            if pconf['z-axis']['ticks']:
                cbar.set_ticks(pconf['z-axis']['ticks'])
            plt.savefig(pconf['filename'], bbox_inches='tight')
            plt.figure()
            continue

        if pconf['title']:
            plt.title(conf['title'])

        if 'plots' not in p:
            p['plots'] = [p]

        for l in p['plots']:  # noqa: E741
            lconf = pconf.new_child(l)

            label = lconf['label']
            label = label if label else None
            cmap = lconf['cmap']
            zorder = lconf.get('zorder', lcount)
            color = lconf.get('color', "C{}".format(lcount))

            x = lconf.get('x-field', lconf['x-axis'].get('field', None))
            y = lconf.get('y-field', lconf['y-axis'].get('field', None))
            z = lconf.get('z-field', lconf['z-axis'].get('field', None))

            xlabel = lconf['x-axis']['label']
            ylabel = lconf['y-axis']['label']
            zlabel = lconf['z-axis']['label']
            if hasattr(c, 'parameters'):
                xlabel = c.parameters.get(
                    x, {'latex': xlabel})['latex'] if not xlabel else xlabel
                ylabel = c.parameters.get(
                    y, {'latex': ylabel})['latex'] if not ylabel else ylabel
                zlabel = c.parameters.get(
                    z, {'latex': zlabel})['latex'] if not zlabel else zlabel

            if xlabel:
                plt.xlabel(xlabel)
            if ylabel:
                plt.ylabel(ylabel)

            if lconf['hline']:
                plt.axhline(y=y,
                            color=color,
                            linestyle='-',
                            lw=lconf['lw'],
                            label=label,
                            zorder=zorder,
                            alpha=lconf['alpha'])
                continue
            if lconf['vline']:
                plt.axvline(x=x,
                            color=color,
                            linestyle='-',
                            lw=lconf['lw'],
                            label=label,
                            zorder=zorder,
                            alpha=lconf['alpha'])
                continue

            if hasattr(c, 'parameters'):
                x = c.parameters.get(x, {'lha': x})['lha']
                y = c.parameters.get(y, {'lha': y})['lha']
                z = c.parameters.get(z, {'lha': z})['lha']

            PDATA = DATA
            for constr in lconf['constraints']:
                PDATA = PDATA[eval(constr)]

            if (lconf['datafile'] and lconf['datafile'] != conf['datafile']):
                conf['datafile'] = lconf['datafile']  # TODO
                store.close()
                del DATA, PDATA, store
                store = HDFStore(lconf['datafile'])  # TODO
                DATA = store['results']  # TODO
                PDATA = DATA

                if not PDATA.empty and 'newfields' in conf:
                    for field, expr in conf['newfields'].items():
                        logging.debug("executing PATA[{}] = {}]".format(
                            field, expr))
                        PDATA[field] = eval(expr)
                    logging.debug("done.")

            for ax, field in {'x-axis': x, 'y-axis': y, 'z-axis': z}.items():
                bounds = lconf[ax]['boundaries']
                if len(bounds) == 2:
                    logging.debug(
                        "applying boundaries [{},{}] on axis {}, field {}".
                        format(bounds[0], bounds[1], ax, field))
                    PDATA = PDATA[(PDATA[field] >= bounds[0])
                                  & (PDATA[field] <= bounds[1])]

            if lconf['x-axis']['lognorm']:
                if type(lconf['x-axis']['lognorm']) == str:
                    plt.xscale(lconf['x-axis']['lognorm'])
                else:
                    plt.xscale('log')

            if lconf['y-axis']['lognorm']:
                if type(lconf['y-axis']['lognorm']) == str:
                    plt.yscale(lconf['y-axis']['lognorm'])
                else:
                    plt.yscale('log')

            if z:
                PDATA = PDATA.sort_values(by=z)
                color = PDATA[z]
                vmin = PDATA[z].min(
                ) if not lconf['z-axis']['vmin'] else lconf['z-axis']['vmin']
                vmax = PDATA[z].max(
                ) if not lconf['z-axis']['vmax'] else lconf['z-axis']['vmax']
            else:
                vmin = None
                vmax = None
            znorm = LogNorm(vmin=vmin,
                            vmax=vmax) if lconf['z-axis']['lognorm'] else None

            if lconf['exec']:
                exec(lconf['exec'])

            if len(PDATA) == 0:
                logging.error(
                    'In plot {}, x:{} , y:{}; no data to plot! (wrong boundaries or constraints?)'
                    .format(p['filename'], x, y))
                continue

            if pconf.get('type', 'scatter') == 'scatter':
                cs = plt.scatter(PDATA[x],
                                 PDATA[y],
                                 zorder=zorder,
                                 label=label,
                                 cmap=cmap,
                                 c=color,
                                 vmin=vmin,
                                 vmax=vmax,
                                 norm=znorm,
                                 s=lconf['s'],
                                 alpha=lconf['alpha'],
                                 marker=lconf.get('marker', None))
            else:
                PDATA = PDATA[[x, y]].dropna().sort_values(by=x)
                cs = plt.plot(PDATA[x],
                              PDATA[y],
                              lconf.get('fmt', '.'),
                              zorder=zorder,
                              c=color,
                              alpha=lconf['alpha'],
                              label=label,
                              **lconf.get('kwargs', {}))

            plt.grid(b=True,
                     which='major',
                     color='#777777',
                     linestyle='-',
                     alpha=0.3,
                     zorder=0)
            plt.minorticks_on()
            plt.grid(b=True,
                     which='minor',
                     color='#999999',
                     linestyle='-',
                     alpha=0.1,
                     zorder=0)

            plt.margins(x=0.01, y=0.01)  # TODO
            if lconf['x-axis']['ticks']:
                if type(lconf['x-axis']['ticks'][0]) is not list:
                    lconf['x-axis']['ticks'] = [
                        lconf['x-axis']['ticks'],
                        ['${}$'.format(xt) for xt in lconf['x-axis']['ticks']]
                    ]
                plt.xticks(lconf['x-axis']['ticks'][0],
                           lconf['x-axis']['ticks'][1])
            if lconf['y-axis']['ticks']:
                if type(lconf['y-axis']['ticks'][0]) is not list:
                    lconf['y-axis']['ticks'] = [
                        lconf['y-axis']['ticks'],
                        ['${}$'.format(yt) for yt in lconf['y-axis']['ticks']]
                    ]
                plt.yticks(lconf['y-axis']['ticks'][0],
                           lconf['y-axis']['ticks'][1])

            if lconf['z-axis']['colorbar']:
                cbar = plt.colorbar(
                    cs,
                    orientation=lconf['z-axis']['colorbar_orientation'],
                    **lconf['z-axis'].get('kwargs', {}))
                if zlabel:
                    cbar.set_label(zlabel)
                if lconf['z-axis']['ticks']:
                    if type(lconf['z-axis']['ticks'][0]) is not list:
                        lconf['z-axis']['ticks'] = [
                            lconf['z-axis']['ticks'],
                            [
                                '${}$'.format(zt)
                                for zt in lconf['z-axis']['ticks']
                            ]
                        ]
                    cbar.set_ticks(lconf['z-axis']['ticks'])
                for label in cbar.ax.yaxis.get_ticklabels():
                    if lconf['z-axis']['colorbar_orientation'] == 'horizontal':
                        label.set_ha('center')
                    else:
                        label.set_va('center')

            lcount += 1

        if pconf['textbox'] and 'text' in pconf['textbox']:
            bbox = pconf['textbox'].get(
                'bbox', dict(boxstyle='round', facecolor='white', alpha=0.2))
            va = pconf['textbox'].get('va', 'top')
            ha = pconf['textbox'].get('ha', 'left')
            textsize = pconf['textbox'].get(
                'fontsize', pconf['rcParams'].get('font.size', 15))
            xtext = pconf['textbox'].get('x', 0.95)
            ytext = pconf['textbox'].get('y', 0.85)
            plt.gcf().text(xtext,
                           ytext,
                           pconf['textbox']['text'],
                           fontsize=textsize,
                           va=va,
                           ha=ha,
                           bbox=bbox)

        if pconf['tick_params']:
            plt.tick_params(**pconf['tick_params'])

        ax = plt.gca()
        for label in ax.yaxis.get_ticklabels():
            label.set_verticalalignment('center')
        for label in ax.xaxis.get_ticklabels():
            label.set_horizontalalignment('center')

        for ann in p.get('annotiations', []):
            plt.annotate(ann['label'], ann['pos'], **ann.get('kwargs', {}))

        if any([lbl.get('label', False) for lbl in p['plots']]):
            plt.legend(**pconf['legend'])

        plotfile = DIR + p.get('filename', 'plot{}.png'.format(pcount))
        logging.info("Saving {}.".format(plotfile))
        plt.savefig(plotfile, bbox_inches="tight", dpi=pconf['dpi'])
        pcount += 1
Exemplo n.º 28
0
    def show(self, **kwargs):
        def split_key(key):
            tl = list(key)
            wp = len(tl) // 4 + int(len(tl) % 4 > 1)
            return '\n'.join([' '.join(s) for s in [tl[i * len(tl) // wp: (i + 1) * len(tl) // wp] for i in range(wp)]])

        out = kwargs.get('out', None)
        cmap = kwargs.get('cmap', 'Purples')
        alpha = kwargs.get('alpha', 0.6)
        label = kwargs.get('label', False)
        bulk = kwargs.get('bulk', False)

        if isinstance(out, str):
            out = [out]
        # check shapes created
        if not self.ready:
            self.refresh_geometry()
        vv = np.unique([self.variance[k] for k in self])
        pscolors = plt.get_cmap(cmap)(np.linspace(0, 1, vv.size))
        # Set alpha
        pscolors[:, -1] = alpha
        pscmap = ListedColormap(pscolors)
        norm = BoundaryNorm(np.arange(min(vv) - 0.5, max(vv) + 1), vv.size)
        fig, ax = plt.subplots()
        lbls = []
        exc = frozenset.intersection(*self.keys)
        for k in self:
            lbls.append((split_key(k.difference(exc)), self.shapes[k].representative_point().coords[0]))
            ax.add_patch(PolygonPatch(self.shapes[k], fc=pscmap(norm(self.variance[k])), ec='none'))
        ax.autoscale_view()
        self.add_overlay(ax)
        if out:
            for o in out:
                lst = [self.prj.get_trimmed_uni(row[0]) for row in self.prj.unilist if o in row[4]['out']]
                if lst:
                    ax.plot(np.hstack([(*seg[0], np.nan) for seg in lst]),
                            np.hstack([(*seg[1], np.nan) for seg in lst]),
                            lw=2, label=o)
            # Shrink current axis's width
            box = ax.get_position()
            ax.set_position([box.x0 + box.width * 0.07, box.y0, box.width * 0.95, box.height])
            # Put a legend below current axis
            ax.legend(loc='upper right', bbox_to_anchor=(-0.08, 1), title='Out', borderaxespad=0, frameon=False)
        if label:
            for txt, xy in lbls:
                ax.annotate(s=txt, xy=xy, weight='bold', fontsize=6, ha='center', va='center')
        divider = make_axes_locatable(ax)
        cax = divider.append_axes('right', size='4%', pad=0.05)
        cb = ColorbarBase(ax=cax, cmap=pscmap, norm=norm, orientation='vertical', ticks=vv)
        cb.set_label('Variance')
        ax.axis(self.prj.trange + self.prj.prange)
        if bulk:
            if label:
                ax.set_xlabel(self.prj.name + (len(exc) * ' +{}').format(*exc))
            else:
                ax.set_xlabel(self.prj.name)
            # bulk composition
            ox, vals = self.prj.get_bulk_composition()
            table = r'''\begin{tabular}{ ''' + ' | '.join(len(ox)*['c']) + '}' + ' & '.join(ox) + r''' \\\hline ''' + ' & '.join(vals) + r'''\end{tabular}'''
            plt.figtext(0.08, 0.94, table, size=10, va='top', usetex=True)
        else:
            if label:
                ax.set_title(self.prj.name + (len(exc) * ' +{}').format(*exc))
            else:
                ax.set_title(self.prj.name)
        # connect button press
        cid = fig.canvas.mpl_connect('button_press_event', self.onclick)
        plt.show()
Exemplo n.º 29
0
    cols = ('C0', 'C1', 'C2', 'C3', 'C4', 'C5')
    cmap2 = ListedColormap(cols)

    plt.figure(figsize = (scol, 0.7 * scol))
    mp = m.pcolormesh(lonedges, latedges, UTC, 
                      norm = BoundaryNorm(bounds, cmap1.N), cmap = cmap1, 
                      latlon = True, rasterized = True)
    for hhr, col in zip(range(t1 - t0 + 1), cols):
        m.contour(lons, lats, numPixelIntp[hhr] > 0, 1, colors = col, 
                  linewidths = 1, latlon = True)
    m.drawcoastlines(linewidth = 0.5)
    m.drawparallels((-60, 60))
    cb = ColorbarBase(plt.axes([0.125, 0.1, 0.775, 0.025]), cmap = cmap2,
                      orientation = 'horizontal',
                      norm = BoundaryNorm(bounds, cmap2.N))
    cb.set_label('UTC hour')

    plt.savefig('fig.cr.composite.pdf')
    plt.close()


#--- Distribution figures ---#


if 'dist.meanprecip' in options:

    meanPrecip = collapse_sat(get_processed_data('meanPrecip', year0, month0, 
                                                 year1, month1, tres))
    numNonzero = collapse_sat(get_processed_data('numNonzero', year0, month0, 
                                                 year1, month1, tres))
Exemplo n.º 30
0
def _scatter_legends(
    df,
    ax,
    cmap,
    ck,
    ondata: bool,
    onside: bool,
    fontsize: float,
    title: str,
    title_fontsize: float,
    hide_title: bool,
    n_per_col: int,
    scale: float,
    ls: float,
    cs: float,
    cbs: float,
) -> None:
    """

    Args:
        df: dataframe
        ax: axis object
        cmap: color map
        ck: color key
        ondata: display legend over scatter plot?
        onside: display legend on side?
        fontsize: fontsize of legend text
        title: Title of subplot/axes
        hide_title: Whether to hide the title
        n_per_col: number of legends per column
        scale: scale legend marker size
        ls: line spacing
        cs: column spacing
        cbs: Cbar shrink factor

    Returns:

    """
    from matplotlib.colors import Normalize
    from matplotlib.colorbar import ColorbarBase, make_axes_gridspec

    x, y, vc = df.columns[:3]
    v = df[vc]
    cax = make_axes_gridspec(ax,
                             location="top",
                             shrink=cbs,
                             aspect=25,
                             fraction=0.1)[0]
    if v.nunique() <= 1:
        cax.set_axis_off()
        return None
    if v.dtype.name == "category":
        if hide_title is False:
            if title is not None:
                ax.title.set_text(title)
            else:
                ax.title.set_text(vc)
            ax.title.set_fontsize(title_fontsize)
        centers = df[[x, y, vc]].groupby(vc).median().T
        for i in centers:
            if ondata:
                ax.text(
                    centers[i][x],
                    centers[i][y],
                    i,
                    fontsize=fontsize,
                    ha="center",
                    va="center",
                )
            if onside:
                ax.scatter(
                    [float(centers[i][x])],
                    [float(centers[i][y])],
                    c=ck[i],
                    label=i,
                    alpha=1,
                    s=0.01,
                )
        if onside:
            n_cols = v.nunique() // n_per_col
            if v.nunique() % n_per_col > 0:
                n_cols += 1
            ax.legend(
                ncol=n_cols,
                loc=(1, 0),
                frameon=False,
                fontsize=fontsize,
                markerscale=scale,
                labelspacing=ls,
                columnspacing=cs,
            )
        cax.set_axis_off()
    else:
        norm = Normalize(vmin=v.min(), vmax=v.max())
        cb = ColorbarBase(cax, cmap=cmap, norm=norm, orientation="horizontal")
        if hide_title is False:
            if title is not None:
                cb.set_label(title, fontsize=title_fontsize)
            else:
                cb.set_label(vc, fontsize=title_fontsize)
        cb.ax.xaxis.set_label_position("bottom")
        cb.ax.xaxis.set_ticks_position("top")
        cb.outline.set_visible(False)
    return None
Exemplo n.º 31
0
def make_plot(filename, grid_name, x_name='x', y_name='y', t_name='time',
                n_cols=6, outpath='', filename_prefix='LMA', 
                do_save=True, image_type='pdf', colormap='gist_earth'):
    """ colormap: a string giving the name of a matplotlib built-in colormap, 
            or a matplotlib.colors.Colormap instance
        """

    f = nc.NetCDFFile(filename)
    data = f.variables  # dictionary of variable names to nc_var objects
    dims = f.dimensions # dictionary of dimension names to sizes
    x = data[x_name]
    y = data[y_name]
    t = data[t_name]
    grid = data[grid_name]
    
    assert len(x.shape) == 1
    assert len(y.shape) == 1
    assert len(t.shape) == 1
        
    grid_dims = grid.dimensions # tuple of dimension names
    name_to_idx = dict((k, i) for i, k in enumerate(grid_dims))
    
    grid_t_idx = name_to_idx[t.dimensions[0]]
    grid_x_idx = name_to_idx[x.dimensions[0]]
    grid_y_idx = name_to_idx[y.dimensions[0]]
        
    n_frames = t.shape[0]
    # n_cols = 6
    n_rows = int(ceil( float(n_frames) / n_cols ))
    
    if type(colormap) == type(''):
        colormap = get_cmap(colormap)
    grey_color = (0.5,)*3
    frame_color = (0.2,)*3
    
    density_maxes = []
    total_counts = []
    all_t = []
    
    xedge = centers_to_edges(x)
    x_range = xedge.max() - xedge.min()
    yedge = centers_to_edges(y)
    y_range = yedge.max() - yedge.min()
    dx = (xedge[1]-xedge[0])
    
    # w, h = figaspect(float(n_rows)/n_cols) # breaks for large numbers of frames - has a hard-coded max figure size
    w, h, n_rows_perpage, n_pages = multiples_figaspect(n_rows, n_cols, x_range, y_range, fig_width=8.5, max_height=None)
    
    # count_scale_factor = dx # / 1000.0
    # max_count_baseline = 450 * count_scale_factor #/ 10.0
    min_count, max_count = 1, grid[:].max() #max_count_baseline*(t[1]-t[0])
    if (max_count == 0) | (max_count == 1 ):
        max_count = min_count+1
    f.close()
    
    default_vmin = -0.2
    if np.log10(max_count) <= default_vmin:
        vmin_count = np.log10(max_count) + default_vmin
    else:
        vmin_count = default_vmin
    
    fig = Figure(figsize=(w,h))
    canvas = FigureCanvasAgg(fig)
    fig.set_canvas(canvas)
    p = small_multiples_plot(fig=fig, rows=n_rows, columns=n_cols)
    p.label_edges(True)
    pad = 0.0 # for time labels in each frame
    
    for ax in p.multiples.flat:
        ax.set_axis_bgcolor('black')
        ax.spines['top'].set_edgecolor(frame_color)
        ax.spines['bottom'].set_edgecolor(frame_color)
        ax.spines['left'].set_edgecolor(frame_color)
        ax.spines['right'].set_edgecolor(frame_color)
    #     ax.yaxis.set_major_formatter(kilo_formatter)
    #     ax.xaxis.set_major_formatter(kilo_formatter)
    base_date = datetime.strptime(t.units, "seconds since %Y-%m-%d %H:%M:%S")
    time_delta = timedelta(0,float(t[0]),0)
    start_time = base_date + time_delta
        
    indexer = [slice(None),]*len(grid.shape)
    
    
    frame_start_times = []
    for i in range(n_frames):
        frame_start = base_date + timedelta(0,float(t[i]),0)
        frame_start_times.append(frame_start)
        indexer[grid_t_idx] = i
        
        density = grid[indexer]
        
        # density,edges = np.histogramdd((x,y), bins=(xedge,yedge))
        density_plot  = p.multiples.flat[i].pcolormesh(xedge,yedge,
                                   np.log10(density.transpose()), 
                                   vmin=vmin_count,
                                   vmax=np.log10(max_count),
                                   cmap=colormap)
        label_string = frame_start.strftime('%H%M:%S')
        text_label = p.multiples.flat[i].text(xedge[0]-pad+x_range*.015, yedge[0]-pad+y_range*.015, label_string, color=grey_color, size=6)
        density_plot.set_rasterized(True)
        density_maxes.append(density.max())
        total_counts.append(density.sum())
        all_t.append(frame_start)
        print label_string, x.shape, density.max(), density.sum()
        
    color_scale = ColorbarBase(p.colorbar_ax, cmap=density_plot.cmap,
                                       norm=density_plot.norm,
                                       orientation='horizontal')
    
    # color_scale.set_label('count per pixel')
    color_scale.set_label('log10(count per pixel)')
    
    view_x = (xedge.min(), xedge.max())
    view_y = (yedge.min(), yedge.max())
    
    print 'making multiples',
    p.multiples.flat[0].axis(view_x+view_y)
    filename = '%s-%s_%s_%05.2fkm_%05.1fs.%s' % (filename_prefix, grid_name, start_time.strftime('%Y%m%d_%H%M%S'), dx, time_delta.seconds, image_type)
    filename = os.path.join(outpath, filename)
    if do_save:
        fig.savefig(filename, dpi=150)
    
    return fig, p, frame_start_times, filename
    
    print ' ... done'
Exemplo n.º 32
0
class Spectrogram:
    def __init__(self, notify, figure, settings):
        self.notify = notify
        self.figure = figure
        self.settings = settings
        self.data = [[], [], []]
        self.index = 0
        self.axes = None
        self.plot = None
        self.extent = None
        self.lineHalfFS = None
        self.lineHalfFE = None
        self.lineObwFS = None
        self.lineObwFE = None

        self.labelHalfFS = None
        self.labelHalfFE = None
        self.labelObwFS = None
        self.labelObwFE = None

        self.threadPlot = None
        self.setup_plot()
        self.set_grid(self.settings.grid)

    def setup_plot(self):
        gs = GridSpec(1, 2, width_ratios=[9.5, 0.5])
        self.axes = self.figure.add_subplot(gs[0],
                                            axisbg=self.settings.background)

        self.axes.set_xlabel("Frequency (MHz)")
        self.axes.set_ylabel('Time')
        numFormatter = ScalarFormatter(useOffset=False)
        timeFormatter = DateFormatter("%H:%M:%S")

        self.axes.xaxis.set_major_formatter(numFormatter)
        self.axes.yaxis.set_major_formatter(timeFormatter)
        self.axes.xaxis.set_minor_locator(AutoMinorLocator(10))
        self.axes.yaxis.set_minor_locator(AutoMinorLocator(10))
        self.axes.set_xlim(self.settings.start, self.settings.stop)
        now = time.time()
        self.axes.set_ylim(epoch_to_mpl(now), epoch_to_mpl(now - 10))

        self.bar = self.figure.add_subplot(gs[1])
        norm = Normalize(vmin=-50, vmax=0)
        self.barBase = ColorbarBase(self.bar, norm=norm,
                                    cmap=cm.get_cmap(self.settings.colourMap))
        self.barBase.set_label('Level (dB)')

        self.setup_measure()

    def setup_measure(self):
        dashesHalf = [1, 5, 5, 5, 5, 5]
        self.lineHalfFS = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='purple')
        self.lineHalfFE = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='purple')
        self.lineObwFS = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='#996600')
        self.lineObwFE = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='#996600')
        if matplotlib.__version__ >= '1.3':
            effect = patheffects.withStroke(linewidth=3, foreground="w",
                                            alpha=0.75)
            self.lineHalfFS.set_path_effects([effect])
            self.lineHalfFE.set_path_effects([effect])
            self.lineObwFS.set_path_effects([effect])
            self.lineObwFE.set_path_effects([effect])

        self.axes.add_line(self.lineHalfFS)
        self.axes.add_line(self.lineHalfFE)
        self.axes.add_line(self.lineObwFS)
        self.axes.add_line(self.lineObwFE)

        box = dict(boxstyle='round', fc='white', ec='purple')
        self.labelHalfFS = Text(0, 0, '-3dB', fontsize='x-small', ha="center",
                                va="top", bbox=box, color='purple')
        self.labelHalfFE = Text(0, 0, '-3dB', fontsize='x-small', ha="center",
                                va="top", bbox=box, color='purple')
        box['ec'] = '#996600'
        self.labelObwFS = Text(0, 0, 'OBW', fontsize='x-small', ha="center",
                                va="top", bbox=box, color='#996600')
        self.labelObwFE = Text(0, 0, 'OBW', fontsize='x-small', ha="center",
                                va="top", bbox=box, color='#996600')

        self.axes.add_artist(self.labelHalfFS)
        self.axes.add_artist(self.labelHalfFE)
        self.axes.add_artist(self.labelObwFS)
        self.axes.add_artist(self.labelObwFE)

        self.hide_measure()

    def draw_vline(self, line, label, x):
        yLim = self.axes.get_ylim()
        xLim = self.axes.get_xlim()
        if xLim[0] < x < xLim[1]:
            line.set_visible(True)
            line.set_xdata([x, x])
            line.set_ydata([yLim[0], yLim[1]])
            self.axes.draw_artist(line)
            label.set_visible(True)
            label.set_position((x, yLim[1]))
            self.axes.draw_artist(label)

    def draw_measure(self, background, measure, show):
        if self.axes._cachedRenderer is None:
            return

        self.hide_measure()
        canvas = self.axes.get_figure().canvas
        canvas.restore_region(background)

        if show[Measure.HBW]:
            xStart, xEnd, _y = measure.get_hpw()
            self.draw_vline(self.lineHalfFS, self.labelHalfFS, xStart)
            self.draw_vline(self.lineHalfFE, self.labelHalfFE, xEnd)

        if show[Measure.OBW]:
            xStart, xEnd, _y = measure.get_obw()
            self.draw_vline(self.lineObwFS, self.labelObwFS, xStart)
            self.draw_vline(self.lineObwFE, self.labelObwFE, xEnd)

        canvas.blit(self.axes.bbox)

    def hide_measure(self):
        self.labelHalfFS.set_visible(False)
        self.labelHalfFE.set_visible(False)
        self.labelObwFS.set_visible(False)
        self.labelObwFE.set_visible(False)

    def scale_plot(self, force=False):
        if self.figure is not None and self.plot is not None:
            extent = self.plot.get_extent()
            if self.settings.autoF or force:
                if extent[0] == extent[1]:
                    extent[1] += 1
                self.axes.set_xlim(extent[0], extent[1])
            if self.settings.autoL or force:
                vmin, vmax = self.plot.get_clim()
                self.barBase.set_clim(vmin, vmax)
                try:
                    self.barBase.draw_all()
                except:
                    pass
            if self.settings.autoT or force:
                self.axes.set_ylim(extent[2], extent[3])

    def redraw_plot(self):
        if self.figure is not None:
            post_event(self.notify, EventThreadStatus(Event.DRAW))

    def get_axes(self):
        return self.axes

    def get_plot_thread(self):
        return self.threadPlot

    def set_title(self, title):
        self.axes.set_title(title)

    def set_plot(self, data, extent, annotate=False):
        self.extent = extent
        self.threadPlot = ThreadPlot(self, self.axes,
                                     data, self.extent,
                                     self.settings.retainMax,
                                     self.settings.colourMap,
                                     self.settings.autoL,
                                     self.barBase,
                                     annotate)
        self.threadPlot.start()

    def clear_plots(self):
        children = self.axes.get_children()
        for child in children:
            if child.get_gid() is not None:
                if child.get_gid() == "plot" or child.get_gid() == "peak":
                    child.remove()

    def set_grid(self, on):
        if on:
            self.axes.grid(True, color='w')
        else:
            self.axes.grid(False)
        self.redraw_plot()

    def set_colourmap(self, colourMap):
        if self.plot is not None:
            self.plot.set_cmap(colourMap)
        self.barBase.set_cmap(colourMap)
        try:
            self.barBase.draw_all()
        except:
            pass

    def close(self):
        self.figure.clear()
        self.figure = None
Exemplo n.º 33
0
                     zorder=10)  # hi zorder -> top

# Plot tissots showing possible scale of candidate scatter.
for l, b in zip(lvals, bvals):
    m.tissot(l, b, 5., 30, ec='none', color='g', alpha=0.25)

# Show the closest candidate to each CR.
for cr in CRs.values():
    cand = cands[cr.near_id]
    m.geodesic(cr.l, cr.b, cand.l, cand.b, lw=0.5, ls='-', c='g')

plt.title('UHE Cosmic Rays and Candidate Sources')
plt.legend([cr_pts, cand_pts], ['UHE CR', 'Candidate'],
           frameon=False,
           loc='lower right',
           scatterpoints=1)

# Plot a colorbar for the CR energies.
cb_ax = plt.axes([0.25, .1, .5, .03], frameon=False)  # rect=L,B,W,H
#bar = ColorbarBase(cb_ax, cmap=cmap, orientation='horizontal', drawedges=False)
vals = np.linspace(Evals.min(), Evals.max(), 100)
bar = ColorbarBase(cb_ax,
                   values=vals,
                   norm=norm_E,
                   cmap=cmap,
                   orientation='horizontal',
                   drawedges=False)
bar.set_label('CR Energy (EeV)')

plt.show()
Exemplo n.º 34
0
    def statistics(self, fns, fn, stationfn, eventinfo=None, latencies=None,
                   computedelay=False, map=False, interactive=False):
        """
        Compare predicted and observed alert times quantitatively.
        """
        a = np.load(fn)
        lats_tt = a['lat'][:, :, 0]
        lons_tt = a['lon'][:, :, 0]
        times = np.median(a['ttP'], axis=-1)
        tree = spatial.KDTree(zip(lats_tt.ravel(), lons_tt.ravel()))
        vals = []
        perc_max = 84
        perc_min = 16

        rp = ReportsParser(dmin=UTCDateTime(2012, 1, 1, 0, 0, 0),
                           dmax=UTCDateTime(2013, 11, 1, 0, 0, 0))
        # t = EventCA()
        t = EventSoCal()
        rp.sfilter = t.point_in_polygon

        for _f in fns:
            rp.read_reports(_f)

        correct = rp.get_correct(mmin=3.5, mmax=10.0)
        pid = correct[:, 0]
        ot = correct[:, 2].astype('float')
        lats = correct[:, 3].astype('float')
        lons = correct[:, 4].astype('float')
        deps = correct[:, 5].astype('float')
        mags = correct[:, 6].astype('float')
        ts1 = correct[:, 7].astype('float')
        lats1 = correct[:, 9].astype('float')
        lons1 = correct[:, 10].astype('float')
        mags1 = correct[:, 12].astype('float')
        rfns = correct[:, 21]
        diff = ts1 - ot
        magdiff = mags - mags1
        cnt = 0
        allcnt = 0
        allm = []
        dataX = []
        dataY = []
        popup_values = []

        fig = plt.figure()
        ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
        m = self.background_map(ax)
        cmap = cm.ScalarMappable(norm=Normalize(vmin=0, vmax=2), cmap='RdBu_r')
        stats_used = []
        for lon, lat, dep, delay, evid, lat1, lon1, dmag, time, mag, rfn in \
            zip(lons, lats, deps, diff, pid, lats1, lons1, magdiff, ot, mags, rfns):
            allcnt += 1
            try:
                if eventinfo is not None and len(eventinfo[evid]) != 4:
                    # print "Event %s does not have 4 initial picks." % evid
                    continue
            except KeyError:
                print "No event information available for: %s (%s)" % (evid, UTCDateTime(time))
                continue
            if evid in self.event_excludes:
                print "Event %s was set to be excluded." % evid
                continue

            if computedelay:
                # Compute the expected alert time for the actual epicenter and
                # the first stations that detected the event
                class NetworkInfo:
                    def __init__(self):
                        self.networks = {'ca':{'lat': [], 'lon': [], 'chn': [],
                                               'nw': [], 'nm': [], 'lc': [],
                                               'color':'black',
                                               'label':'UC Berkeley'}}
                    def get_networks(self):
                        return self.networks

                # read in SCEDC master station list
                fh = open(stationfn)
                scedc_stations = {}
                for _l in fh.readlines():
                    if _l.startswith('#'):
                        continue
                    net, sta, chan, loc, lt, ln, elev, ondate, offdate = _l.split()
                    ns = '.'.join((net, sta))
                    if ns not in scedc_stations:
                        scedc_stations[ns] = (float(lt), float(ln))
                ni = NetworkInfo()
                for _st in eventinfo[evid]:
                    ni.networks['ca']['lat'].append(scedc_stations[_st][0])
                    ni.networks['ca']['lon'].append(scedc_stations[_st][1])
                    ni.networks['ca']['nm'].append(_st)
                    if _st not in stats_used:
                        stats_used.append(_st)
                de = DelayEEW()
                elat, elon, edep, ttP, tstarget = \
                de.compute(ni, np.array([float(lon)]), np.array([float(lat)]),
                           np.array([float(dep)]),
                           vp=6.5, vs=3.5, nnst=4, procdelay=True, nmaps=500,
                           resultsfn=None, latencies=latencies)
                med = np.median(ttP)
                lb = scoreatpercentile(ttP, perc_min)
                ub = scoreatpercentile(ttP, perc_max)
            else:
                distance, index = tree.query(np.array([[lat, lon]]))
                irow, icol = divmod(index[0], lats_tt.shape[1])
                med = np.median(times[:, irow, icol])
                lb = scoreatpercentile(times[:, irow, icol], perc_min)
                ub = scoreatpercentile(times[:, irow, icol], perc_max)

            cnt += 1
            allm.append(mag)
            val = (delay - lb) / (ub - lb)
            print med, lb, ub, delay, val, med - delay
            vals.append(val)
            cl = cmap.to_rgba(val)
            x, y = m(lon, lat)
            dataX.append(x)
            dataY.append(y)
            info = '%s: %.2f %s\n' % (UTCDateTime(time), mag, evid)
            info += '%.2f %.2f %.2f\n' % (delay, med, val)
            for _st in eventinfo[evid]:
                info += ' %s' % _st
            popup_values.append(info)
            m.plot(x, y, ms=8, c=cl, marker='o', picker=5.)
            # plt.figure()
            # plt.hist(times[ilon, ilat, :], bins=np.arange(0, 30), normed=True, histtype='step')
            # plt.show()
        print "Stations used in detections:"
        print stats_used
        idx = np.where((np.array(vals) <= 1.0) & (np.array(vals) >= 0))
        print "%.1f lie within the %d and %d percentile" % ((idx[0].size / float(len(vals))) * 100, perc_min, perc_max)
        # plt.plot(allm, vals, 'bo')
        if interactive:
            self.popup(fig, dataX, dataY, popup_values)
        cax = fig.add_axes([0.87, 0.1, 0.05, 0.8])
        cb = ColorbarBase(cax, cmap='RdBu_r',
                          norm=Normalize(vmin=0, vmax=2))
        cb.set_label('Alert accuracy')

        plt.figure()
        plt.hist(vals, bins=20)
        plt.show()
Exemplo n.º 35
0
            axis.set_xlim(ext[0], ext[1])
            axis.set_ylim(ext[2], ext[3])
            axis.imshow(to_plot[j][i],
                        origin='lower',
                        cmap=cmaps[i],
                        norm=norm[i],
                        aspect='auto',
                        extent=ext)
            axis.plot(xcen, ycen, 'x', color='#000000', markersize=7, mew=1.5)

            cb = ColorbarBase(ax_cb[i],
                              orientation='vertical',
                              cmap=cmaps[i],
                              norm=norm[i])
            cb.solids.set_edgecolor('face')
            cb.set_label(barlab[i], fontsize=13)

            if i == 0:
                axis.text(0.5,
                          1.05,
                          titles[j],
                          ha='center',
                          transform=axis.transAxes,
                          fontsize=15)
            elif i == 1:
                axis.plot(x, y, color='#808080', linewidth=2)
            if j == 0:
                axis.text(-0.1,
                          0.5,
                          mapname[i],
                          va='center',
Exemplo n.º 36
0
class MplCanvas(MyMplCanvas):#,gui.QWidget):#(MyMplCanvas):
    """
    A class for displaying radar data in basic mode. In this mode, the width and height of plot are equal.

    Parameters 
    ----------
    title : string
        Plotting header label.
    colormap : ColorMap
        ColorMap object.

    Attributes
    ----------
    figurecanvas : FigureCanvas
        The canvas for display.
    zoomer : list
        Storing zoom windows.
    _zoomWindow : QRectF
        Storing current zoom window.
    origin : list
        Storing the coordinates for onPress event.
    var_ : dict
        Storing variables for display.
    AZIMUTH : boolean
        Flag for azimuth display.
    RANGE_RING : boolean
        Flag for RANGE_RING display.
    COLORBAR : boolean
        Flag for colorbar display.
    PICKER_LABEL : boolean
        Flag for picker label display.
    cb : ColorbarBase
        Colorbar object.
    cMap : ColorMap
        ColorMap object.
    pressEvent : event
        Press event.
    pressed : boolean
        Flag for press event.
    deltaX : float
        X change of rubberband. Zoom window only when the change is greater than ZOOM_WINDOW_PIXEL_LIMIT.
    deltaY : float
        Y change of rubberband.
    startX : float
        Rubberband start x value.
    startY : float
        Rubberband start y value.
    moveLabel : QLabel
        Picker label
    sweep : Sweep 
        Sweep object.
    ranges : list
        Sweep ranges
    varName : string
        Storing current display variable name.
    x : list
        Storing sweep x values.
    y : list
        Storing sweep y values.
    label : string
        Storing header label and sweep time stamp
    """

    def __init__(self, title, colormap, parent=None, width=3, height=3, dpi=100):
        self.fig = Figure()#plt.figure()#figsize=(width, height), dpi=dpi)
        plt.axis('off')
        self.axes = self.fig.add_subplot(111,aspect='equal')
        self.fig.set_dpi( dpi )
        self.headerLabel = title
        #self.axes.hold(False)
        #self.fig.canvas.mpl_connect('pick_event', self.onpick)

        self.figurecanvas = FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(self,
                                   gui.QSizePolicy.Expanding,
                                   gui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

        self.setWindow(core.QRectF(-1. * RENDER_PIXELS/2., 1. * RENDER_PIXELS/2., 1. * RENDER_PIXELS, -1. * RENDER_PIXELS))
#        self.origins = core.QPoint()
        self.ignorePaint = False
        #self.bottomRight = core.QPoint()
        self.rubberBand = gui.QRubberBand(gui.QRubberBand.Rectangle, self)
        self.zoomer = []
#        self.picker = []
            
        self.origin = [RENDER_PIXELS,RENDER_PIXELS]
        self.scaleFactor = 1.0
#        self.offsetX = 0.0
#        self.offsetY = 0.0
        self.var_ = {}
        self.AZIMUTH = False
        self.RANGE_RING = False
        self.COLORBAR = True
        self.PICKER_LABEL = False
        self.cb = None
        self.cMap = colormap

        self.pressEvent = None
        self.pressed = False
        self.deltaX = 0.
        self.deltaY = 0.
        self.startX = None
        self.startY = None

        self.moveLabel = gui.QLabel("",self)
        self.moveLabel.setText("")
        self.moveLabel.hide()
        self.moveLabel.setStyleSheet("font-size:12px; margin:3px; padding:4px; background:#FFFFFF; border:2px solid #000;")

        self.mpl_connect('button_press_event', self.onPress)
        self.mpl_connect('button_release_event', self.onRelease)
        self.mpl_connect('motion_notify_event', self.onMove)

    def onPress(self,event):
        """ method called when mouse press"""
        if event.button == 1: ## left button
            xdata = event.xdata
            ydata = event.ydata
            # check if mouse is outside the figure        
            if xdata is None or ydata is None:
                return       

            self.pressed = True
            self.pressEvent = event

            self.origin = core.QPoint(event.x, self.height() - event.y)
            self.rubberBand.setGeometry(core.QRect(self.origin, core.QSize()))
            self.rubberBand.show()

            # start point        
            self.startX = xdata
            self.startY = ydata

        if event.button == 2: ## middle botton - zoom in the center
            pass
        if event.button == 3:
            pass

    def onMove(self,event):
        """ method called when mouse moves """
        xdata = event.xdata
        ydata = event.ydata
        if xdata is None or ydata is None:
            self.moveLabel.hide()
            return

        if self.pressed:  ## display rubberband
            if self.PICKER_LABEL:
                self.moveLabel.hide()

            deltaX = event.x - self.pressEvent.x  ## moved distance
            deltaY = event.y - self.pressEvent.y  ## for rubberband
            dx = dy = min(fabs(deltaX),fabs(deltaY))
            if deltaX<0: 
                dx = -dx
            if deltaY<0:
                dy = -dy
            newRect = core.QRect(self.origin.x(), self.origin.y(), int(dx), -int(dy))
            newRect = newRect.normalized()
            self.rubberBand.setGeometry(newRect)
            self.deltaX = dx
            self.deltaY = dy

        else:  ## display label
            if self.PICKER_LABEL:
                i,j = self.retrieve_z_value(xdata,ydata)
                self.moveLabel.show()
                if i is not None and j is not None:
#                    self.moveLabel.setText(core.QString(r"x=%g, y=%g, z=%g" % (xdata,ydata,self.var_[i][j]))) ## TODO: should use xdata or self.x[i][j]
                    self.moveLabel.setText(r"x=%g, y=%g, z=%g" % (xdata,ydata,self.var_[i][j])) ## TODO: should use xdata or self.x[i][j]
                    
                else:
#                    self.moveLabel.setText(core.QString(r"x=%g, y=%g, z=n/a" % (xdata,ydata)))
                    self.moveLabel.setText(r"x=%g, y=%g, z=n/a" % (xdata,ydata))
                self.moveLabel.adjustSize()
                offset = 10
                if self.width()-event.x < self.moveLabel.width():
                    offset = -10 - self.moveLabel.width()
                self.moveLabel.move(event.x+offset,self.height()-event.y)

    def retrieve_z_value(self, xdata, ydata):
        #xpos = np.argmin(np.abs(xdata-self.x))
        #ypos = np.argmin(np.abs(ydata-self.y))
        MIN = 99999
        iv = None
        jv = None
        for i in range(len(self.x)):
            j = self.findNearest(np.copy(self.x[i]),xdata)
            if j is not None:
                d = self.distance(xdata,ydata,self.x[i][j],self.y[i][j]) 
                if d < MIN:
                    iv = i
                    jv = j
                    MIN = d
        return iv,jv

    def onRelease(self,event):
        """ method called when mouse button is released """
        if event.button == 1:
            self.pressed = False
            self.rubberBand.hide()

            xdata = event.xdata ## mouse real position
            ydata = event.ydata
            if xdata is None or ydata is None or self.startX is None or self.startY is None:
                return

            d0 = self.width() * FIGURE_CANCAS_RATIO
            x_range = self.axes.get_xlim()[1]-self.axes.get_xlim()[0]
            y_range = self.axes.get_ylim()[1]-self.axes.get_ylim()[0]
            (x1,y1) = self.startX, self.startY
            (x2,y2) = x1 + self.deltaX/d0 * x_range, y1+self.deltaY/d0 * y_range

            oldRect = core.QRectF() # last rubberband rect
            oldRect.setLeft(self.axes.get_xlim()[0])
            oldRect.setRight(self.axes.get_xlim()[1])
            oldRect.setBottom(self.axes.get_ylim()[0])
            oldRect.setTop(self.axes.get_ylim()[1])

            rect = core.QRectF()  # current rubberband rect
            rect.setLeft(min(x1,x2))
            rect.setRight(max(x1,x2))
            rect.setBottom(min(y1,y2))
            rect.setTop(max(y1,y2))

            ## react only when draged region is greater than 0.01 times of old rect
            if fabs(self.deltaX)>ZOOM_WINDOW_PIXEL_LIMIT and \
               fabs(rect.width())>ZOOM_WINDOW_WIDTH_LIMIT and \
               fabs(rect.width()) >= 0.01*fabs(oldRect.width()): 
                self.zoomer.append(oldRect)
                self.zoomTo(rect)
                self._zoomWindow = rect

    def zoomTo(self,rect):
        """ adjust zoom winodw to rect """
        self.axes.set_xlim(rect.left(),rect.right())
        self.axes.set_ylim(rect.bottom(),rect.top())
        self.draw()

    def findNearest(self, array, target):
        """ find nearest value to target and return its index """
        diff = abs(array - target)
        mask = np.ma.greater(diff, 0.151) ## TODO: select a threshold (range:meters_between_gates = 150.000005960464)
        if np.all(mask):
            return None # returns None if target is greater than any value
        masked_diff = np.ma.masked_array(diff, mask)
        return masked_diff.argmin()
    
    def distance(self, x1, y1, x2, y2):
        """ calculate distance between two points """
        return sqrt((x1-x2)**2 + (y1-y2)**2) ## TODO: formula

    def sizeHint(self):
        w, h = self.get_width_height()
        return core.QSize(w, h)

    def minimumSizeHint(self):
        return core.QSize(10, 10)

    def setWindow(self, window):
        """ initialize the full window to use for this widget """
        self._zoomWindow = window
        self._aspectRatio = window.width() / window.height()

    def resizeEvent(self, event):
        """ method called when resize window """
        sz = event.size()
        width = sz.width()
        height = sz.height()
        dpival = self.fig.dpi
        winch = float(width)/dpival
        hinch = float(height)/dpival
        self.fig.set_size_inches( winch, hinch )
        #self.draw()
        #self.update()
        self.fig.canvas.draw()
        self.origin = [width,height]
        
    def drawSweep(self, sweep, varName, beamWidth):
        """ draw sweep """
        self.beamWidth = beamWidth
        self.ranges = sweep.ranges
        self.sweep = sweep
        self.varName = varName.lower()
        self.var_ = sweep.vars_[varName] #in list
        self.x = sweep.x
        self.y = sweep.y
        self.label = self.headerLabel + sweep.timeLabel
        self.update_figure() #update figure

    def update_figure(self):
        """ update figure - need to call it explicitly """
        if len(self.var_) > 0:
            self.axes.clear()
            # avoid missing values of -32768
            self.var_ = np.ma.array(self.var_, mask=(self.var_ < -32000))
            vmin = min(min(x) for x in self.var_)
            vmax = max(max(x) for x in self.var_)

            im = self.axes.pcolormesh(self.x,self.y,self.var_, vmin=vmin, vmax=vmax, cmap=self.cMap(self.varName)) 
            ## setup zeniths, azimuths, and colorbar
            if self.RANGE_RING:
                self.draw_range_ring()
            if self.AZIMUTH:
                self.draw_azimuth_line()
            if self.COLORBAR:
                self.draw_colorbar(im,vmin,vmax)
            #self.x[0:359]/1e3,self.y[0:359]/1e3,self.var_,vmin=vmin, vmax=vmax)

            #plt.axis('off') ## show x, y axes or not
            #self.adjustZoomWindow() ## zoomWindow will not change for different variable - keep using the current zoom window
            self.zoomTo(self._zoomWindow)
            self.axes.set_title(self.label, size=9) ## TODO: change size to be adaptive
            self.fig.canvas.draw()
            ## draw contour - a new feature - grayscale, no zoom in/out support
            ## self.axes.contour(self.x,self.y,self.var_,[0.5], linewidths=2., colors='k')
            #self.fig.canvas.blit(self.axes.bbox)

    def draw_azimuth_line(self):
        """ draw azimuths with 30-degree intervals """
        angles = np.arange(0, 360, 30)
        labels = [90,60,30,0,330,300,270,240,210,180,150,120]
        x = R * np.cos(np.pi*angles/180)
        y = R * np.sin(np.pi*angles/180)

        for xi,yi,ang,lb in zip(x,y,angles,labels):
            line = plt.Line2D([0,xi],[0,yi],linestyle='dashed',color='lightgray',lw=0.8)
            self.axes.add_line(line)
            xo,yo = 0,0
            if ang>90 and ang<180:
                xo = -10
                yo = 3
            elif ang == 180:
                xo = -15
                yo = -3
            elif ang>180 and ang<270:
                xo = -12
                yo = -10
            elif ang == 270:
                xo = -10
                yo = -8
            elif ang >270 and ang<360:
                yo = -5
            self.axes.annotate(str(lb), xy=(xi,yi), xycoords='data',
                               xytext=(xo,yo), textcoords='offset points',
                               arrowprops=None,size=10)

    def draw_range_ring(self):
        """ draw zeniths with 30 intervals """
        zeniths = np.arange(0,R+1,30)
        angle = 135.
        for r in zeniths:
            circ = plt.Circle((0, 0),radius=r,linestyle='dashed',color='lightgray',lw=0.8,fill=False)
            self.axes.add_patch(circ)
            x = R * np.cos(np.pi*angle/180.) * r/R
            y = R * np.sin(np.pi*angle/180.) * r/R
            print 'r=',r, x, y
            self.axes.annotate(int(r), xy=(x,y), xycoords='data', arrowprops=None,size=10)

    def draw_colorbar(self,im,vmin,vmax):
        """ draw colorbar """
        if self.cb:
            self.fig.delaxes(self.fig.axes[1])
            self.fig.subplots_adjust(right=0.90)

        pos = self.axes.get_position()
        l, b, w, h = pos.bounds
        cax = self.fig.add_axes([l, b-0.06, w, 0.03]) # colorbar axes
        cmap=self.cMap(self.varName)
        substName = self.varName
        if not self.cMap.ticks_label.has_key(self.varName):
            # we couldn't find 'vel_f', so try searching for 'vel'
            u = self.varName.find('_')
            if u:
                substName = self.varName[:u]
                if not self.cMap.ticks_label.has_key(substName):
                
                    msgBox = gui.QMessageBox()
                    msgBox.setText(
    """ Please define a color scale for '{0}' in your configuration file """.format(self.varName))
                    msgBox.exec_()
                    raise RuntimeError(
   """ Please define a color scale for '{0}' in your configuration file """.format(self.varName))
        bounds = self.cMap.ticks_label[substName]
        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
        self.cb = ColorbarBase(cax, cmap=cmap, norm=norm,  orientation='horizontal',  boundaries=bounds,ticks=bounds)#, format='%1i')  ## spacing='proportional' -- divide proportionally by the value
        self.cb.ax.tick_params(labelsize=8) 
        #t = [str(int(i)) for i in bounds]
        t = [str(i) for i in bounds]
        self.cb.set_ticklabels(t,update_ticks=True)
        self.cb.set_label('Color Scale', size=8)

    def resetFactors(self):
        """ reset factors """
        self.zoomer = []
        self.setWindow(core.QRect(-1 * RENDER_PIXELS/2, 1 * RENDER_PIXELS/2, 1 * RENDER_PIXELS, 1 * RENDER_PIXELS))
#        self.update_figure()
        self.fig.canvas.draw()

    def changeZoomerPointer(self, ind=None):
        """ method called when mouse button is pressed, changing zoomer pointer """
        if ind is None:
            if len(self.zoomer)>0:
                zoomWindow = self.zoomer[-1]
                self.zoomTo(zoomWindow)
                self.zoomer.pop()
        else:
            if len(self.zoomer)>0:
                zoomWindow = self.zoomer[0]
                self.zoomTo(zoomWindow)
                self.zoomer=[]      
            
    def getAspectRatio(self):
        return self._aspectRatio

    def keyPressEvent(self, event):
        """ method called when key press """
        print 'RadialDisplay::keyPressEvent: ', event.key()
        if event.key() == core.Qt.Key_C:
            self.resetFactors()
            event.accept()

    '''
Exemplo n.º 37
0
class MplCanvas(MyMplCanvas):  #,gui.QWidget):#(MyMplCanvas):
    """
    A class for displaying radar data in basic mode. In this mode, the width and height of plot are equal.

    Parameters 
    ----------
    title : string
        Plotting header label.
    colormap : ColorMap
        ColorMap object.

    Attributes
    ----------
    figurecanvas : FigureCanvas
        The canvas for display.
    zoomer : list
        Storing zoom windows.
    _zoomWindow : QRectF
        Storing current zoom window.
    origin : list
        Storing the coordinates for onPress event.
    var_ : dict
        Storing variables for display.
    AZIMUTH : boolean
        Flag for azimuth display.
    RANGE_RING : boolean
        Flag for RANGE_RING display.
    COLORBAR : boolean
        Flag for colorbar display.
    PICKER_LABEL : boolean
        Flag for picker label display.
    cb : ColorbarBase
        Colorbar object.
    cMap : ColorMap
        ColorMap object.
    pressEvent : event
        Press event.
    pressed : boolean
        Flag for press event.
    deltaX : float
        X change of rubberband. Zoom window only when the change is greater than ZOOM_WINDOW_PIXEL_LIMIT.
    deltaY : float
        Y change of rubberband.
    startX : float
        Rubberband start x value.
    startY : float
        Rubberband start y value.
    moveLabel : QLabel
        Picker label
    sweep : Sweep 
        Sweep object.
    ranges : list
        Sweep ranges
    varName : string
        Storing current display variable name.
    x : list
        Storing sweep x values.
    y : list
        Storing sweep y values.
    label : string
        Storing header label and sweep time stamp
    """
    def __init__(self,
                 title,
                 colormap,
                 parent=None,
                 width=3,
                 height=3,
                 dpi=100):
        self.fig = Figure()  #plt.figure()#figsize=(width, height), dpi=dpi)
        plt.axis('off')
        self.axes = self.fig.add_subplot(111, aspect='equal')
        self.fig.set_dpi(dpi)
        self.headerLabel = title
        #self.axes.hold(False)
        #self.fig.canvas.mpl_connect('pick_event', self.onpick)

        self.figurecanvas = FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(self, gui.QSizePolicy.Expanding,
                                   gui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

        self.setWindow(
            core.QRectF(-1. * RENDER_PIXELS / 2., 1. * RENDER_PIXELS / 2.,
                        1. * RENDER_PIXELS, -1. * RENDER_PIXELS))
        #        self.origins = core.QPoint()
        self.ignorePaint = False
        #self.bottomRight = core.QPoint()
        self.rubberBand = gui.QRubberBand(gui.QRubberBand.Rectangle, self)
        self.zoomer = []
        #        self.picker = []

        self.origin = [RENDER_PIXELS, RENDER_PIXELS]
        self.scaleFactor = 1.0
        #        self.offsetX = 0.0
        #        self.offsetY = 0.0
        self.var_ = {}
        self.AZIMUTH = False
        self.RANGE_RING = False
        self.COLORBAR = True
        self.PICKER_LABEL = False
        self.cb = None
        self.cMap = colormap

        self.pressEvent = None
        self.pressed = False
        self.deltaX = 0.
        self.deltaY = 0.
        self.startX = None
        self.startY = None

        self.moveLabel = gui.QLabel("", self)
        self.moveLabel.setText("")
        self.moveLabel.hide()
        self.moveLabel.setStyleSheet(
            "font-size:12px; margin:3px; padding:4px; background:#FFFFFF; border:2px solid #000;"
        )

        self.mpl_connect('button_press_event', self.onPress)
        self.mpl_connect('button_release_event', self.onRelease)
        self.mpl_connect('motion_notify_event', self.onMove)

    def onPress(self, event):
        """ method called when mouse press"""
        if event.button == 1:  ## left button
            xdata = event.xdata
            ydata = event.ydata
            # check if mouse is outside the figure
            if xdata is None or ydata is None:
                return

            self.pressed = True
            self.pressEvent = event

            self.origin = core.QPoint(event.x, self.height() - event.y)
            self.rubberBand.setGeometry(core.QRect(self.origin, core.QSize()))
            self.rubberBand.show()

            # start point
            self.startX = xdata
            self.startY = ydata

        if event.button == 2:  ## middle botton - zoom in the center
            pass
        if event.button == 3:
            pass

    def onMove(self, event):
        """ method called when mouse moves """
        xdata = event.xdata
        ydata = event.ydata
        if xdata is None or ydata is None:
            self.moveLabel.hide()
            return

        if self.pressed:  ## display rubberband
            if self.PICKER_LABEL:
                self.moveLabel.hide()

            deltaX = event.x - self.pressEvent.x  ## moved distance
            deltaY = event.y - self.pressEvent.y  ## for rubberband
            dx = dy = min(fabs(deltaX), fabs(deltaY))
            if deltaX < 0:
                dx = -dx
            if deltaY < 0:
                dy = -dy
            newRect = core.QRect(self.origin.x(), self.origin.y(), int(dx),
                                 -int(dy))
            newRect = newRect.normalized()
            self.rubberBand.setGeometry(newRect)
            self.deltaX = dx
            self.deltaY = dy

        else:  ## display label
            if self.PICKER_LABEL:
                i, j = self.retrieve_z_value(xdata, ydata)
                self.moveLabel.show()
                if i is not None and j is not None:
                    #                    self.moveLabel.setText(core.QString(r"x=%g, y=%g, z=%g" % (xdata,ydata,self.var_[i][j]))) ## TODO: should use xdata or self.x[i][j]
                    self.moveLabel.setText(
                        r"x=%g, y=%g, z=%g" % (xdata, ydata, self.var_[i][j])
                    )  ## TODO: should use xdata or self.x[i][j]

                else:
                    #                    self.moveLabel.setText(core.QString(r"x=%g, y=%g, z=n/a" % (xdata,ydata)))
                    self.moveLabel.setText(r"x=%g, y=%g, z=n/a" %
                                           (xdata, ydata))
                self.moveLabel.adjustSize()
                offset = 10
                if self.width() - event.x < self.moveLabel.width():
                    offset = -10 - self.moveLabel.width()
                self.moveLabel.move(event.x + offset, self.height() - event.y)

    def retrieve_z_value(self, xdata, ydata):
        #xpos = np.argmin(np.abs(xdata-self.x))
        #ypos = np.argmin(np.abs(ydata-self.y))
        MIN = 99999
        iv = None
        jv = None
        for i in range(len(self.x)):
            j = self.findNearest(np.copy(self.x[i]), xdata)
            if j is not None:
                d = self.distance(xdata, ydata, self.x[i][j], self.y[i][j])
                if d < MIN:
                    iv = i
                    jv = j
                    MIN = d
        return iv, jv

    def onRelease(self, event):
        """ method called when mouse button is released """
        if event.button == 1:
            self.pressed = False
            self.rubberBand.hide()

            xdata = event.xdata  ## mouse real position
            ydata = event.ydata
            if xdata is None or ydata is None or self.startX is None or self.startY is None:
                return

            d0 = self.width() * FIGURE_CANCAS_RATIO
            x_range = self.axes.get_xlim()[1] - self.axes.get_xlim()[0]
            y_range = self.axes.get_ylim()[1] - self.axes.get_ylim()[0]
            (x1, y1) = self.startX, self.startY
            (
                x2, y2
            ) = x1 + self.deltaX / d0 * x_range, y1 + self.deltaY / d0 * y_range

            oldRect = core.QRectF()  # last rubberband rect
            oldRect.setLeft(self.axes.get_xlim()[0])
            oldRect.setRight(self.axes.get_xlim()[1])
            oldRect.setBottom(self.axes.get_ylim()[0])
            oldRect.setTop(self.axes.get_ylim()[1])

            rect = core.QRectF()  # current rubberband rect
            rect.setLeft(min(x1, x2))
            rect.setRight(max(x1, x2))
            rect.setBottom(min(y1, y2))
            rect.setTop(max(y1, y2))

            ## react only when draged region is greater than 0.01 times of old rect
            if fabs(self.deltaX)>ZOOM_WINDOW_PIXEL_LIMIT and \
               fabs(rect.width())>ZOOM_WINDOW_WIDTH_LIMIT and \
               fabs(rect.width()) >= 0.01*fabs(oldRect.width()):
                self.zoomer.append(oldRect)
                self.zoomTo(rect)
                self._zoomWindow = rect

    def zoomTo(self, rect):
        """ adjust zoom winodw to rect """
        self.axes.set_xlim(rect.left(), rect.right())
        self.axes.set_ylim(rect.bottom(), rect.top())
        self.draw()

    def findNearest(self, array, target):
        """ find nearest value to target and return its index """
        diff = abs(array - target)
        mask = np.ma.greater(
            diff, 0.151
        )  ## TODO: select a threshold (range:meters_between_gates = 150.000005960464)
        if np.all(mask):
            return None  # returns None if target is greater than any value
        masked_diff = np.ma.masked_array(diff, mask)
        return masked_diff.argmin()

    def distance(self, x1, y1, x2, y2):
        """ calculate distance between two points """
        return sqrt((x1 - x2)**2 + (y1 - y2)**2)  ## TODO: formula

    def sizeHint(self):
        w, h = self.get_width_height()
        return core.QSize(w, h)

    def minimumSizeHint(self):
        return core.QSize(10, 10)

    def setWindow(self, window):
        """ initialize the full window to use for this widget """
        self._zoomWindow = window
        self._aspectRatio = window.width() / window.height()

    def resizeEvent(self, event):
        """ method called when resize window """
        sz = event.size()
        width = sz.width()
        height = sz.height()
        dpival = self.fig.dpi
        winch = float(width) / dpival
        hinch = float(height) / dpival
        self.fig.set_size_inches(winch, hinch)
        #self.draw()
        #self.update()
        self.fig.canvas.draw()
        self.origin = [width, height]

    def drawSweep(self, sweep, varName, beamWidth):
        """ draw sweep """
        self.beamWidth = beamWidth
        self.ranges = sweep.ranges
        self.sweep = sweep
        self.varName = varName.lower()
        self.var_ = sweep.vars_[varName]  #in list
        self.x = sweep.x
        self.y = sweep.y
        self.label = self.headerLabel + sweep.timeLabel
        self.update_figure()  #update figure

    def update_figure(self):
        """ update figure - need to call it explicitly """
        if len(self.var_) > 0:
            self.axes.clear()

            vmin = min(min(x) for x in self.var_)
            vmax = max(max(x) for x in self.var_)

            im = self.axes.pcolormesh(self.x,
                                      self.y,
                                      self.var_,
                                      vmin=vmin,
                                      vmax=vmax,
                                      cmap=self.cMap(self.varName))
            ## setup zeniths, azimuths, and colorbar
            if self.RANGE_RING:
                self.draw_range_ring()
            if self.AZIMUTH:
                self.draw_azimuth_line()
            if self.COLORBAR:
                self.draw_colorbar(im, vmin, vmax)
            #self.x[0:359]/1e3,self.y[0:359]/1e3,self.var_,vmin=vmin, vmax=vmax)

            #plt.axis('off') ## show x, y axes or not
            #self.adjustZoomWindow() ## zoomWindow will not change for different variable - keep using the current zoom window
            self.zoomTo(self._zoomWindow)
            self.axes.set_title(self.label,
                                size=9)  ## TODO: change size to be adaptive
            self.fig.canvas.draw()
            ## draw contour - a new feature - grayscale, no zoom in/out support
            ## self.axes.contour(self.x,self.y,self.var_,[0.5], linewidths=2., colors='k')
            #self.fig.canvas.blit(self.axes.bbox)

    def draw_azimuth_line(self):
        """ draw azimuths with 30-degree intervals """
        angles = np.arange(0, 360, 30)
        labels = [90, 60, 30, 0, 330, 300, 270, 240, 210, 180, 150, 120]
        x = R * np.cos(np.pi * angles / 180)
        y = R * np.sin(np.pi * angles / 180)

        for xi, yi, ang, lb in zip(x, y, angles, labels):
            line = plt.Line2D([0, xi], [0, yi],
                              linestyle='dashed',
                              color='lightgray',
                              lw=0.8)
            self.axes.add_line(line)
            xo, yo = 0, 0
            if ang > 90 and ang < 180:
                xo = -10
                yo = 3
            elif ang == 180:
                xo = -15
                yo = -3
            elif ang > 180 and ang < 270:
                xo = -12
                yo = -10
            elif ang == 270:
                xo = -10
                yo = -8
            elif ang > 270 and ang < 360:
                yo = -5
            self.axes.annotate(str(lb),
                               xy=(xi, yi),
                               xycoords='data',
                               xytext=(xo, yo),
                               textcoords='offset points',
                               arrowprops=None,
                               size=10)

    def draw_range_ring(self):
        """ draw zeniths with 30 intervals """
        zeniths = np.arange(0, R + 1, 30)
        angle = 135.
        for r in zeniths:
            circ = plt.Circle((0, 0),
                              radius=r,
                              linestyle='dashed',
                              color='lightgray',
                              lw=0.8,
                              fill=False)
            self.axes.add_patch(circ)
            x = R * np.cos(np.pi * angle / 180.) * r / R
            y = R * np.sin(np.pi * angle / 180.) * r / R
            print 'r=', r, x, y
            self.axes.annotate(int(r),
                               xy=(x, y),
                               xycoords='data',
                               arrowprops=None,
                               size=10)

    def draw_colorbar(self, im, vmin, vmax):
        """ draw colorbar """
        if self.cb:
            self.fig.delaxes(self.fig.axes[1])
            self.fig.subplots_adjust(right=0.90)

        pos = self.axes.get_position()
        l, b, w, h = pos.bounds
        cax = self.fig.add_axes([l, b - 0.06, w, 0.03])  # colorbar axes
        cmap = self.cMap(self.varName)
        substName = self.varName
        if not self.cMap.ticks_label.has_key(self.varName):
            # we couldn't find 'vel_f', so try searching for 'vel'
            u = self.varName.find('_')
            if u:
                substName = self.varName[:u]
                if not self.cMap.ticks_label.has_key(substName):

                    msgBox = gui.QMessageBox()
                    msgBox.setText(
                        """ Please define a color scale for '{0}' in your configuration file """
                        .format(self.varName))
                    msgBox.exec_()
                    raise RuntimeError(
                        """ Please define a color scale for '{0}' in your configuration file """
                        .format(self.varName))
        bounds = self.cMap.ticks_label[substName]
        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
        self.cb = ColorbarBase(
            cax,
            cmap=cmap,
            norm=norm,
            orientation='horizontal',
            boundaries=bounds,
            ticks=bounds
        )  #, format='%1i')  ## spacing='proportional' -- divide proportionally by the value
        self.cb.ax.tick_params(labelsize=8)
        #t = [str(int(i)) for i in bounds]
        t = [str(i) for i in bounds]
        self.cb.set_ticklabels(t, update_ticks=True)
        self.cb.set_label('Color Scale', size=8)

    def resetFactors(self):
        """ reset factors """
        self.zoomer = []
        self.setWindow(
            core.QRect(-1 * RENDER_PIXELS / 2, 1 * RENDER_PIXELS / 2,
                       1 * RENDER_PIXELS, 1 * RENDER_PIXELS))
        #        self.update_figure()
        self.fig.canvas.draw()

    def changeZoomerPointer(self, ind=None):
        """ method called when mouse button is pressed, changing zoomer pointer """
        if ind is None:
            if len(self.zoomer) > 0:
                zoomWindow = self.zoomer[-1]
                self.zoomTo(zoomWindow)
                self.zoomer.pop()
        else:
            if len(self.zoomer) > 0:
                zoomWindow = self.zoomer[0]
                self.zoomTo(zoomWindow)
                self.zoomer = []

    def getAspectRatio(self):
        return self._aspectRatio

    def keyPressEvent(self, event):
        """ method called when key press """
        print 'RadialDisplay::keyPressEvent: ', event.key()
        if event.key() == core.Qt.Key_C:
            self.resetFactors()
            event.accept()

    '''
Exemplo n.º 38
0
for svg_file in svg_files:
    index = float(svg_file.rsplit('_', 1)[-1].rstrip('.svg'))
    if int(index) > max_wind_index:
        continue
    wind = index * index2ms
    color = rgb2hex(cmap(int(round(index * cmap.N / max_wind_index))))
    out_file = outdir + '/' + svg_file.rsplit('/')[-1]
    with open(svg_file, 'r') as infile, open(out_file, 'w') as outfile:
        line = infile.readline()
        while line:
            outfile.write(line)
            line = infile.readline()
            line = line.replace('#000000', str(color))
    indices.append(index)
    winds.append(wind)
    colors.append(color)

for (index, wind, color) in sorted(zip(indices, winds, colors)):
    print "{:2.0f} {:5.1f} {}".format(index, wind, color)

# Create an image showing the colorbar for the choosen colormap
fig = plt.figure(figsize=(1, 3.2), dpi=100)
ax = fig.add_axes([0.05, 0.05, 0.45, 0.9])
cb = ColorbarBase(ax, cmap=cmap, norm=norm, orientation='vertical')
cbytick_obj = plt.getp(cb.ax.axes, 'yticklabels')
plt.setp(cbytick_obj, fontsize=8)
cb.set_label('Wind speed (mph)', fontsize=9)
plt.savefig(outdir + '/amv_winds_key.png', transparent=True)

Exemplo n.º 39
0
    def alert_times_map(self, fns, m=None, fig=None, ax=None, scale=10000.,
                        cb=True, disterr=False, interactive=False,
                        eventinfo=None, msscale=1, cmapname='jet'):
        """
        Plot a map of observed alert times.
        """
        cmap = cm.ScalarMappable(norm=Normalize(vmin=6, vmax=25), cmap=cmapname)
        rp = ReportsParser(dmin=UTCDateTime(2012, 1, 1, 0, 0, 0),
                           dmax=UTCDateTime(2013, 11, 1, 0, 0, 0))
        t = EventCA()
        rp.sfilter = t.point_in_polygon

        for _f in fns:
            rp.read_reports(_f)

        correct = rp.get_correct(mmin=3.5, mmax=10.0)
        pid = correct[:, 0]
        ot = correct[:, 2].astype('float')
        lats = correct[:, 3].astype('float')
        lons = correct[:, 4].astype('float')
        mags = correct[:, 6].astype('float')
        ts1 = correct[:, 7].astype('float')
        lats1 = correct[:, 9].astype('float')
        lons1 = correct[:, 10].astype('float')
        mags1 = correct[:, 12].astype('float')
        rfns = correct[:, 21]
        diff = ts1 - ot
        magdiff = mags - mags1

        if m is None and fig is None and ax is None:
            fig = plt.figure()
            ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
            m = self.background_map(ax)
        dataX = []
        dataY = []
        values = []
        # load event info
        cnt = 0
        allcnt = 0
        for lon, lat, delay, evid, lat1, lon1, dmag, time, mag, rfn in \
            zip(lons, lats, diff, pid, lats1, lons1, magdiff, ot, mags, rfns):
            allcnt += 1
            try:
                if eventinfo is not None and len(eventinfo[evid]) != 4:
                    print "Event %s does not have 4 initial picks." % evid
                    continue
            except KeyError:
                print "No event information available for: %s (%s)" % (evid, UTCDateTime(time))
                continue
            if evid in self.event_excludes:
                print "Event %s was set to be excluded." % evid
                continue
            cnt += 1
            ddist, az, baz = gps2DistAzimuth(lat, lon, lat1, lon1)
            ddist /= 1000.
            x, y = m(lon, lat)
            dataX.append(x)
            dataY.append(y)
            info = '%s: %.2f %.2f %s' % (UTCDateTime(time), delay, mag, evid)
            for _st in eventinfo[evid]:
                info += ' %s' % _st
            values.append(info)
            cl = cmap.to_rgba(delay)
            if disterr:
                factor = math.sqrt(abs(float(ddist)))
                sl2 = scale * factor
                p2 = Wedge((x, y), sl2, 0, 360, facecolor=cl,
                           edgecolor='black', picker=5, lw=1.0)
                ax.add_patch(p2)
            else:
                m.plot(x, y, ms=8 * msscale, c=cl, marker='o', picker=5.)
        print "Plotted %d out of %d events." % (cnt, allcnt)
        if interactive:
            self.popup(fig, dataX, dataY, values)
        if cb:
            # Colorbar
            cax = fig.add_axes([0.87, 0.1, 0.05, 0.8])
            cb = ColorbarBase(cax, cmap=cmapname,
                              norm=Normalize(vmin=6., vmax=25.))
            cb.set_label('Time since origin time [s]')
Exemplo n.º 40
0
def create_multipanel_plot(size, dpi, shape, layout, var_info, cmap, lims):
        fig = plt.figure(figsize=size, dpi=dpi)
        rings = []

        # the rect parameter will be ignore as we will set axes_locator
        rect = (0.08, 0.08, 0.9, 0.9)
        nrow,ncol = shape

        # divide the axes rectangle into grid whose size is specified
        # by horiz * vert
        horiz = [Scaled(1.)]
        for i in range(ncol - 1):
            horiz.extend([Fixed(.2), Scaled(1.)])

        vert = [Scaled(.1), Fixed(.35), Scaled(1.)]
        for i in range(nrow - 1):
            vert.extend([Fixed(.1), Scaled(1.)])

        divider = Divider(fig, rect, horiz, vert, aspect=False)

#        ax0 = fig.add_axes(rect, label="0")
#        ax0.set_aspect('equal', 'datalim')
#        ax = [ax0] + [fig.add_axes(rect, label="%d"%i, sharex=ax0, sharey=ax0)
#            for i in range(1,6)]
        ax = [fig.add_axes(rect, label="%d"%i) for i in range(len(layout))]
        cax = [fig.add_axes(rect, label='cb%d'%i) for i in range(ncol)]

        for i,a in enumerate(ax):
#            a.set_axes_locator(divider.new_locator(nx=(i // nrow) * 2,
#                ny=((i%nrow) + 1) * 2))
            a.set_axes_locator(divider.new_locator(nx=(i % ncol) * 2,
                ny=(nrow - (i // ncol)) * 2))
            a.set_aspect('equal', 'datalim')

        for i,a in enumerate(cax):
            a.set_axes_locator(divider.new_locator(nx=2 * i, ny=0))

        for num,(a,(data, label, var)) in enumerate(zip(ax, layout)):
            norm,ticks,units = var_info[var]
            ppi_plot(init_data.xlocs, init_data.ylocs, data, norm=norm,
                cmap=cmap, ax=a, rings=rings)
#            a.set_title('%s (%s)' % (moment, units))

            if num >= ncol:
                a.set_xlabel('X Distance (km)')
                cbar = ColorbarBase(ax=cax[num%ncol], norm=norm, cmap=cmap,
                    orientation='horizontal')
                cbar.set_label('%s (%s)' % (label, units))
                cbar.set_ticks(ticks)
            else:
                a.xaxis.set_major_formatter(plt.NullFormatter())

            if num % ncol == 0:
                a.set_ylabel('Y Distance (km)')
            else:
                a.yaxis.set_major_formatter(plt.NullFormatter())

            if lims:
                a.xaxis.set_major_locator(plt.MultipleLocator(lims[0]))
                a.yaxis.set_major_locator(plt.MultipleLocator(lims[0]))
                a.set_xlim(*lims[1:3])
                a.set_ylim(*lims[3:])

            # loc = 2 is upper left. TODO: Should patch matplotlib to use
            # same strings as legend
            at = AnchoredText("%s)" % chr(97 + num), loc=2, prop=dict(size='large'),
                frameon=True)
#            at.patch.set_boxstyle("round, pad=0., rounding_size=0.2")
            a.add_artist(at)

        return fig
Exemplo n.º 41
0
        ppi_plot(init_data.xlocs, init_data.ylocs, init_data.vel_h_ts, norm=vel_norm, cmap=cmap, ax=ax4, rings=rings)
        ax4.set_title('TS Velocity (m/s)')

        ax6 = fig.add_subplot(nrow, ncol, 6, sharex=ax, sharey=ax)
        ppi_plot(init_data.xlocs, init_data.ylocs, init_data.spw_h_ts, norm=spw_norm, cmap=cmap, ax=ax6, rings=rings)
        ax6.set_title('TS Spectrum Width (m/s)')

    fig.subplots_adjust(bottom=0.15)
    lpos = list(ax.get_position().bounds)
    lpos[1] = 0.04
    lpos[3] = 0.04
    cax_left = fig.add_axes(lpos)

    cbar_left = ColorbarBase(ax=cax_left,
        norm=pwr_norm, cmap=cmap, orientation='horizontal')
    cbar_left.set_label('Power (dBm)')

    mpos = list(ax3.get_position().bounds)
    mpos[1] = 0.04
    mpos[3] = 0.04
    cax_mid = fig.add_axes(mpos)
    cbar_mid = ColorbarBase(ax=cax_mid,
        norm=vel_norm, cmap=cmap, orientation='horizontal')
    cbar_mid.set_label('Velocity (m/s)')

    rpos = list(ax5.get_position().bounds)
    rpos[1] = 0.04
    rpos[3] = 0.04
    cax_right = fig.add_axes(rpos)
    cbar_right = ColorbarBase(ax=cax_right,
        norm=spw_norm, cmap=cmap, orientation='horizontal')
Exemplo n.º 42
0
def runtest(lmaManager=None, lma_view=None, HDFmanagers=None):
    # colormap = get_cmap('gist_yarg_r')
    colormap = get_cmap('gist_earth')
    
    density_maxes = []
    total_counts = []
    all_t = []
    
    for delta_minutes in minute_intervals:
        time_delta = DateTimeDelta(0, 0, delta_minutes, 0)
        
        n_frames   = int(ceil((end_time - start_time) / time_delta))
        n_cols = 6
        n_rows = int(ceil( float(n_frames) / n_cols ))
        w, h = figaspect(float(n_rows)/n_cols)

        xedge=np.arange(b.x[0], b.x[1]+dx, dx)
        yedge=np.arange(b.y[0], b.y[1]+dy, dy)
        x_range = b.x[1] - b.x[0]
        y_range = b.y[1] - b.y[0]

        min_count, max_count = 1, max_count_baseline*delta_minutes

        f = figure(figsize=(w,h))
        p = small_multiples_plot(fig=f, rows=n_rows, columns=n_cols)
        p.label_edges(True)
        
        for ax in p.multiples.flat:
            ax.yaxis.set_major_formatter(kilo_formatter)
            ax.xaxis.set_major_formatter(kilo_formatter)

        for i in range(n_frames):
            frame_start = start_time + i*time_delta
            frame_end   = frame_start + time_delta
            b.sec_of_day = (frame_start.abstime, frame_end.abstime)
            b.t = (frame_start, frame_end)
            
            do_plot = False
            flash_extent_density = True
            density = None
            
            if source_density==True:
                lmaManager.refresh(b)
                lma_view.transformed.cache_is_old()
                x,y,t=lma_view.transformed['x','y','t']
                density,edges = np.histogramdd((x,y), bins=(xedge,yedge))
                do_plot=True
            else:
                for lmaManager in HDFmanagers:
                    # yes, loop through every file every time and reselect data.
                    # so wrong, yet so convenient.
                    h5 = lmaManager.h5file
                    if flash_extent_density == False:
                        lmaManager.refresh(b)
                        lma_view = AcuityView(DataSelection(lmaManager.data, b), mapProj, bounds=b)
                        # lma_view.transformed.cache_is_old()
                        x,y,t=lma_view.transformed['x','y','t']
                        if x.shape[0] > 1: do_plot = True
                        break
                    else:
                        # assume here that the bounds sec_of_day day is the same as
                        # the dataset day
                        t0, t1 = b.sec_of_day
                        # events = getattr(h5.root.events, lmaManager.table.name)[:]
                        # flashes = getattr(h5.root.flashes, lmaManager.table.name)[:]
                        
                        event_dtype = getattr(h5.root.events, lmaManager.table.name)[0].dtype
                        events_all = getattr(h5.root.events, lmaManager.table.name)[:]
                        flashes = getattr(h5.root.flashes, lmaManager.table.name)
                        
                        def event_yielder(evs, fls):
                            these_events = []
                            for fl in fls:
                                if (    (fl['n_points']>9) & 
                                        (t0 < fl['start']) & 
                                        (fl['start'] <= t1) 
                                    ):
                                    these_events = evs[evs['flash_id'] == fl['flash_id']]
                                    if len(these_events) <> fl['n_points']:
                                        print 'not giving all ', fl['n_points'], ' events? ', these_events.shape
                                    for an_ev in these_events:
                                        yield an_ev

                        
                        # events = np.fromiter((an_ev for an_ev in ( events_all[events_all['flash_id'] == fl['flash_id']] 
                        #                 for fl in flashes if (
                        #                   (fl['n_points']>9) & (t0 < fl['start']) & (fl['start'] <= t1)
                        #                 )
                        #               ) ), dtype=event_dtype)
                        events = np.fromiter(event_yielder(events_all, flashes), dtype=event_dtype)
                        
                        # print events['flash_id'].shape

                        ### Flash extent density ###                        
                        x,y,z = mapProj.fromECEF( 
                                *geoProj.toECEF(events['lon'], events['lat'], events['alt'])
                                )
                                
                        # Convert to integer grid coordinate bins
                        #      0    1    2    3
                        #   |    |    |    |    |
                        # -1.5  0.0  1.5  3.0  4.5
                    
                        if x.shape[0] > 1:
                            density, edges = extent_density(x,y,events['flash_id'].astype('int32'),
                                                            b.x[0], b.y[0], dx, dy, xedge, yedge)
                            do_plot = True                        
                            break
                # print 'density values: ', density.min(), density.max()
                    
            
            if do_plot == True:  # need some data
                # density,edges = np.histogramdd((x,y), bins=(xedge,yedge))
                density_plot  = p.multiples.flat[i].pcolormesh(xedge,yedge,
                                           np.log10(density.transpose()), 
                                           vmin=-0.2,
                                           vmax=np.log10(max_count),
                                           cmap=colormap)
                label_string = frame_start.strftime('%H%M:%S')
                text_label = p.multiples.flat[i].text(b.x[0]-pad+x_range*.01, b.y[0]-pad+y_range*.01, label_string, color=(0.5,)*3, size=6)
                density_plot.set_rasterized(True)
                density_maxes.append(density.max())
                total_counts.append(density.sum())
                all_t.append(frame_start)
                print label_string, x.shape, density.max(), density.sum()

        color_scale = ColorbarBase(p.colorbar_ax, cmap=density_plot.cmap,
                                           norm=density_plot.norm,
                                           orientation='horizontal')
        # color_scale.set_label('count per pixel')
        color_scale.set_label('log10(count per pixel)')
        
        # moving reference frame correction. all panels will have same limits, based on time of last frame
        view_dt = 0.0 # (frame_start - t0).seconds
        x_ctr = x0 + view_dt*u
        y_ctr = y0 + view_dt*v
        view_x = (x_ctr - view_dx/2.0 - pad, x_ctr + view_dx/2.0 + pad)
        view_y = (y_ctr - view_dy/2.0 - pad, y_ctr + view_dy/2.0 + pad)
        # view_x  = (b.x[0]+view_dt*u, b.x[1]+view_dt*u)
        # view_y  = (b.y[0]+view_dt*v, b.y[1]+view_dt*v)
        
        # print 'making timeseries',
        # time_series = figure(figsize=(16,9))
        # ts_ax = time_series.add_subplot(111)
        # ts_ax.plot_date(mx2num(all_t),total_counts,'-', label='total sources', tz=tz)
        # ts_ax.plot_date(mx2num(all_t),density_maxes,'-', label='max pixel', tz=tz)
        # ts_ax.xaxis.set_major_formatter(time_series_x_fmt)
        # ts_ax.legend()
        # time_filename = 'out/LMA-timeseries_%s_%5.2fkm_%5.1fs.pdf' % (start_time.strftime('%Y%m%d_%H%M%S'), dx/1000.0, time_delta.seconds)
        # time_series.savefig(time_filename)
        # print ' ... done'
        
        print 'making multiples',
        p.multiples.flat[0].axis(view_x+view_y)
        filename = 'out/LMA-density_%s_%5.2fkm_%5.1fs.pdf' % (start_time.strftime('%Y%m%d_%H%M%S'), dx/1000.0, time_delta.seconds)
        f.savefig(filename, dpi=150)
        print ' ... done'
        f.clf()
        return events
Exemplo n.º 43
0
    def clusterPlot(
        self,
        metric: str = "mutual information",
        metric_kws: dict = None,
        symmetric: bool = True,  # this should usually be True??
        self_correlation: bool = False,
        savedir: str = "",
        verbose: bool = True,
        plot_unclustered: bool = False,
        col_for_legend: str = "zone",
        col_for_cbar: str = "number of probes",
    ):
        """
        calculate, plot and cluster the correlation matrix
        """
        self._checkMetricImplemented(metric)

        corr_matrix = np.empty((self.num_genes, self.num_genes),
                               dtype=np.float64)
        corr_matrix.fill(np.nan)

        # the main title of the plot
        title = (f"Clustered Pairwise {metric}\n"
                 f"bin size = {self.bin_size[0]} pix "
                 f"by {self.bin_size[1]} pix")
        if metric == "mutual information":
            title += f"\n(bins = {metric_kws['bins']})"

        #
        # Set diagonal fill values for given metric
        # -----------------------------------------
        #

        if metric in [
                "mutual information", "JS divergence", "normalized crosscorr",
                "pearson", "SSIM"
        ]:
            fill_diagonal = 0.
        else:
            fill_diagonal = 0.
        # FIXME: might want to set diagonals values differently for some metrics.

        for gene1 in self.gene_index_dict:
            gene1_idx = self.gene_index_dict[gene1]['index']
            for gene2 in self.gene_index_dict:
                gene2_idx = self.gene_index_dict[gene2]['index']

                # ------------------------------
                # skip self-correlation of genes
                # ------------------------------
                if not self_correlation and gene2_idx == gene1_idx:
                    corr_matrix[gene1_idx, gene2_idx] = fill_diagonal
                    continue

                #
                # skip if already calculated
                # --------------------------
                if not np.isnan(corr_matrix[gene1_idx, gene2_idx]):
                    continue

                gene1_array = self.img_array[gene1_idx, ...]
                gene2_array = self.img_array[gene2_idx, ...]

                if verbose:
                    print(f"Gene 1 {gene1} array shape: {gene1_array.shape}\n"
                          f"Gene 2 {gene2} array shape: {gene2_array.shape}\n")

                #
                # run metric of choice
                # --------------------
                #

                if metric == "mutual information":
                    dist = calcImageMI(gene1_array,
                                       gene2_array,
                                       bins=metric_kws["bins"])

                    # dist = calcMIcustom(gene1_array, gene2_array,
                    #                    bins=metric_kws["bins"])
                elif metric == "normalized crosscorr":
                    dist = normXCorr(
                        gene1_array,
                        gene2_array,
                    )
                elif metric == "pearson":
                    dist = pearson(
                        gene1_array,
                        gene2_array,
                    )
                elif metric == "JS divergence":
                    dist = js(
                        gene1_array,
                        gene2_array,
                    )
                elif metric == "SSIM":
                    dist = ssim(
                        gene1_array,
                        gene2_array,
                    )
                else:
                    raise ValueError(f"Metric {metric} not recognised")

                # enter result into correlation matrix
                corr_matrix[gene1_idx, gene2_idx] = dist
                if symmetric:
                    corr_matrix[gene2_idx, gene1_idx] = dist

        #
        # set plotting params for given metrics
        # -------------------------------------
        #
        print(f'plotting for {metric} ...')
        # these metrics start from 0
        if metric in ["mutual information", "JS divergence"]:
            center = None
            cmap = "hot"

        # these metrics can have +ve and -ve values
        elif metric in ["normalized crosscorr", "pearson", "SSIM"]:
            center = 0
            cmap = "vlag"

        # default settings
        else:
            center = None
            cmap = "hot"

        if verbose:
            print(f"Filled correlation matrix:\n" f"{corr_matrix}")

        #
        # set up row colours
        # ------------------
        #

        if self.annotation_csv is not None:

            #
            # parse annotation csv file into a dataframe
            # ------------------------------------------
            #

            genes_df = pd.DataFrame({"name": self.ordered_genes}, )
            # print(f"genes dataframe initial:\n {genes_df}")
            self.annotation_df = pd.read_csv(self.annotation_csv)
            # print(f"annotation dataframe:\n {self.annotation_df}")
            self.genes_df = genes_df.merge(self.annotation_df,
                                           how="left",
                                           on="name",
                                           copy=False)
            self.genes_df.set_index("name", inplace=True)

            if verbose:
                print(f"genes dataframe final:\n "
                      f"{self.genes_df}\n{self.genes_df.dtypes}")

            #
            # Generate Row-colours
            # --------------------
            # generate row-colours dataframe,
            # also saving lut dictionary and category labels
            #

            row_colours = []
            lut_labels_dict = {}

            for col in self.genes_df.columns:
                # sequential palette for numerical annotations
                if col in [
                        "number of probes",
                ]:
                    row_colour, lut, labels = self._makeRowColours(
                        self.genes_df[col], "Blues")
                else:
                    row_colour, lut, labels = self._makeRowColours(
                        self.genes_df[col], "Set1")
                row_colours.append(row_colour)
                lut_labels_dict[col] = (lut, labels)

            row_colours = pd.concat(row_colours, axis=1)

            if verbose:
                print(f"Dict of Look-up table and labels:\n")
                pp.pprint(lut_labels_dict)

                print(f"Row colours df:\n"
                      f"{row_colours}\n{row_colours.dtypes}")

        else:
            row_colours = None

        #
        # Plot clustermap
        # ---------------
        #

        sns.set_style("dark")

        # plot heatmap without clustering
        if plot_unclustered:
            fig_mat, ax_mat = plt.subplots(figsize=(9, 9))
            sns.heatmap(corr_matrix,
                        ax=ax_mat,
                        square=True,
                        yticklabels=self.ordered_genes,
                        xticklabels=self.ordered_genes)

        g = sns.clustermap(
            pd.DataFrame(data=corr_matrix,
                         index=self.ordered_genes,
                         columns=self.ordered_genes),
            square=False,
            yticklabels=True,
            xticklabels=True,
            # yticklabels=self.ordered_genes,
            # xticklabels=self.ordered_genes,
            center=center,
            cmap=cmap,
            row_colors=row_colours,
        )

        #
        # set up annotation legend and/or colorbar
        # ----------------------------------------
        #

        if self.annotation_csv is not None:
            lut, labels = lut_labels_dict[col_for_legend]

            # create a new axes on the bottom right of plot
            labels_ax = g.fig.add_axes([0.4, 0.01, 0.58, 0.08])
            labels_ax.axis('off')

            for label in labels:
                labels_ax.bar(0, 0, color=lut[label], label=label, linewidth=0)
            labels_ax.legend(
                loc="lower right",
                ncol=4,
                frameon=False,
            )

            cbar_params, labels = lut_labels_dict[col_for_cbar]
            norm, cmap = cbar_params

            # create a new axes on the bottom right of plot
            cbar_ax = g.fig.add_axes([0.35, 0.04, 0.15, 0.01])

            cb1 = ColorbarBase(cbar_ax,
                               cmap=cmap,
                               norm=norm,
                               orientation='horizontal')
            cb1.set_label(col_for_cbar)

        g.ax_heatmap.tick_params(axis='both', which='major', labelsize=5)
        g.fig.subplots_adjust(top=0.94)
        g.fig.suptitle(title, fontsize=12, fontweight="bold")

        if not os.path.exists(savedir):
            os.mkdir(savedir)
        filename = (f"{metric.replace(' ','_')}" f"_clusterplot.png")
        g.fig.savefig(
            os.path.join(savedir, filename),
            dpi=600,
        )

        # list of genes in order shown on clustermap
        reordered_genes = [
            self.ordered_genes[idx] for idx in g.dendrogram_row.reordered_ind
        ]
        if verbose:
            print(f"Reorderd indices:\n"
                  f"{g.dendrogram_row.reordered_ind}\n"
                  f"Reordered genes:\n{reordered_genes}")

        g.fig.clear()
        plt.close()
        return corr_matrix, reordered_genes
Exemplo n.º 44
0
#!/usr/bin/env python
from BRadar.plotutils import NWS_Reflect
'''
Make a colorbar as a separate figure.
'''

#from matplotlib import pyplot, mpl
import matplotlib.pyplot as plt
from matplotlib.colorbar import ColorbarBase

# Make a figure and axes with dimensions as desired.
fig = plt.figure()
ax1 = fig.add_axes([0.45, 0.05, 0.03, 0.75])

# ColorbarBase derives from ScalarMappable and puts a colorbar
# in a specified axes, so it has everything needed for a
# standalone colorbar.  There are many more kwargs, but the
# following gives a basic continuous colorbar with ticks
# and labels.
cb1 = ColorbarBase(ax1,
                   cmap=NWS_Reflect['ref_table'],
                   norm=NWS_Reflect['norm'])
cb1.set_label('Reflectivity [dBZ]')

#pyplot.savefig('../../Documents/SPA/Colorbar_Raw.eps')
#pyplot.savefig('../../Documents/SPA/Colorbar_Raw.png', dpi=250)

plt.show()
Exemplo n.º 45
0
class Plotter():
    def __init__(self, notify, figure, settings):
        self.notify = notify
        self.figure = figure
        self.settings = settings
        self.average = settings.average
        self.axes = None
        self.bar = None
        self.threadPlot = None
        self.extent = None
        self.lineMinP = None
        self.lineMaxP = None
        self.lineAvgP = None
        self.lineGMP = None
        self.lineHalfP = None
        self.lineHalfFS = None
        self.lineHalfFE = None
        self.lineObwP = None
        self.lineObwFS = None
        self.lineObwFE = None

        self.labelMinP = None
        self.labelMaxP = None
        self.labelAvgP = None
        self.labelGMP = None
        self.labelHalfP = None
        self.labelHalfFS = None
        self.labelHalfFE = None
        self.labelObwFS = None
        self.labelObwFE = None

        self.setup_plot()
        self.set_grid(self.settings.grid)

    def setup_plot(self):
        formatter = ScalarFormatter(useOffset=False)

        gs = GridSpec(1, 2, width_ratios=[9.5, 0.5])

        self.axes = self.figure.add_subplot(gs[0],
                                            axisbg=self.settings.background)
        self.axes.set_xlabel("Frequency (MHz)")
        self.axes.set_ylabel('Level (dB)')
        self.axes.xaxis.set_major_formatter(formatter)
        self.axes.yaxis.set_major_formatter(formatter)
        self.axes.xaxis.set_minor_locator(AutoMinorLocator(10))
        self.axes.yaxis.set_minor_locator(AutoMinorLocator(10))
        self.axes.set_xlim(self.settings.start, self.settings.stop)
        self.axes.set_ylim(-50, 0)

        self.bar = self.figure.add_subplot(gs[1])
        norm = Normalize(vmin=-50, vmax=0)
        self.barBase = ColorbarBase(self.bar, norm=norm,
                                    cmap=cm.get_cmap(self.settings.colourMap))
        self.barBase.set_label('Level (dB)')

        self.setup_measure()

    def setup_measure(self):
        dashesAvg = [4, 5, 1, 5, 1, 5]
        dashesGM = [5, 5, 5, 5, 1, 5, 1, 5]
        dashesHalf = [1, 5, 5, 5, 5, 5]
        self.lineMinP = Line2D([0, 0], [0, 0], linestyle='--', color='black')
        self.lineMaxP = Line2D([0, 0], [0, 0], linestyle='-.', color='black')
        self.lineAvgP = Line2D([0, 0], [0, 0], dashes=dashesAvg, color='magenta')
        self.lineGMP = Line2D([0, 0], [0, 0], dashes=dashesGM, color='green')
        self.lineHalfP = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='purple')
        self.lineHalfFS = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='purple')
        self.lineHalfFE = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='purple')
        self.lineObwP = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='#996600')
        self.lineObwFS = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='#996600')
        self.lineObwFE = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='#996600')
        if matplotlib.__version__ >= '1.3':
            effect = patheffects.withStroke(linewidth=3, foreground="w",
                                            alpha=0.75)
            self.lineMinP.set_path_effects([effect])
            self.lineMaxP.set_path_effects([effect])
            self.lineAvgP.set_path_effects([effect])
            self.lineGMP.set_path_effects([effect])
            self.lineHalfP.set_path_effects([effect])
            self.lineHalfFS.set_path_effects([effect])
            self.lineHalfFE.set_path_effects([effect])
            self.lineObwP.set_path_effects([effect])
            self.lineObwFS.set_path_effects([effect])
            self.lineObwFE.set_path_effects([effect])

        self.axes.add_line(self.lineMinP)
        self.axes.add_line(self.lineMaxP)
        self.axes.add_line(self.lineAvgP)
        self.axes.add_line(self.lineGMP)
        self.axes.add_line(self.lineHalfP)
        self.axes.add_line(self.lineHalfFS)
        self.axes.add_line(self.lineHalfFE)
        self.axes.add_line(self.lineObwP)
        self.axes.add_line(self.lineObwFS)
        self.axes.add_line(self.lineObwFE)

        box = dict(boxstyle='round', fc='white', ec='black')
        self.labelMinP = Text(0, 0, 'Min', fontsize='x-small', ha="right",
                              va="bottom", bbox=box, color='black')
        self.labelMaxP = Text(0, 0, 'Max', fontsize='x-small', ha="right",
                              va="top", bbox=box, color='black')
        box['ec'] = 'magenta'
        self.labelAvgP = Text(0, 0, 'Mean', fontsize='x-small', ha="right",
                              va="center", bbox=box, color='magenta')
        box['ec'] = 'green'
        self.labelGMP = Text(0, 0, 'GMean', fontsize='x-small', ha="right",
                            va="center", bbox=box, color='green')
        box['ec'] = 'purple'
        self.labelHalfP = Text(0, 0, '-3dB', fontsize='x-small', ha="right",
                              va="center", bbox=box, color='purple')
        self.labelHalfFS = Text(0, 0, '-3dB', fontsize='x-small', ha="center",
                                va="top", bbox=box, color='purple')
        self.labelHalfFE = Text(0, 0, '-3dB', fontsize='x-small', ha="center",
                                va="top", bbox=box, color='purple')
        box['ec'] = '#996600'
        self.labelObwP = Text(0, 0, 'OBW', fontsize='x-small', ha="right",
                              va="center", bbox=box, color='#996600')
        self.labelObwFS = Text(0, 0, 'OBW', fontsize='x-small', ha="center",
                                va="top", bbox=box, color='#996600')
        self.labelObwFE = Text(0, 0, 'OBW', fontsize='x-small', ha="center",
                                va="top", bbox=box, color='#996600')

        self.axes.add_artist(self.labelMinP)
        self.axes.add_artist(self.labelMaxP)
        self.axes.add_artist(self.labelAvgP)
        self.axes.add_artist(self.labelGMP)
        self.axes.add_artist(self.labelHalfP)
        self.axes.add_artist(self.labelHalfFS)
        self.axes.add_artist(self.labelHalfFE)
        self.axes.add_artist(self.labelObwP)
        self.axes.add_artist(self.labelObwFS)
        self.axes.add_artist(self.labelObwFE)

        self.hide_measure()

    def draw_hline(self, line, label, y):
        xLim = self.axes.get_xlim()
        yLim = self.axes.get_ylim()
        if yLim[0] < y < yLim[1]:
            line.set_visible(True)
            line.set_xdata([xLim[0], xLim[1]])
            line.set_ydata([y, y])
            self.axes.draw_artist(line)
            label.set_visible(True)
            label.set_position((xLim[1], y))
            self.axes.draw_artist(label)

    def draw_vline(self, line, label, x):
        yLim = self.axes.get_ylim()
        xLim = self.axes.get_xlim()
        if xLim[0] < x < xLim[1]:
            line.set_visible(True)
            line.set_xdata([x, x])
            line.set_ydata([yLim[0], yLim[1]])
            self.axes.draw_artist(line)
            label.set_visible(True)
            label.set_position((x, yLim[1]))
            self.axes.draw_artist(label)

    def draw_measure(self, background, measure, show):
        if self.axes._cachedRenderer is None:
            return

        self.hide_measure()
        canvas = self.axes.get_figure().canvas
        canvas.restore_region(background)

        if show[Measure.MIN]:
            y = measure.get_min_p()[1]
            self.draw_hline(self.lineMinP, self.labelMinP, y)

        if show[Measure.MAX]:
            y = measure.get_max_p()[1]
            self.draw_hline(self.lineMaxP, self.labelMaxP, y)

        if show[Measure.AVG]:
            y = measure.get_avg_p()
            self.draw_hline(self.lineAvgP, self.labelAvgP, y)

        if show[Measure.GMEAN]:
            y = measure.get_gmean_p()
            self.draw_hline(self.lineGMP, self.labelGMP, y)

        if show[Measure.HBW]:
            xStart, xEnd, y = measure.get_hpw()
            self.draw_hline(self.lineHalfP, self.labelHalfP, y)
            self.draw_vline(self.lineHalfFS, self.labelHalfFS, xStart)
            self.draw_vline(self.lineHalfFE, self.labelHalfFE, xEnd)

        if show[Measure.OBW]:
            xStart, xEnd, y = measure.get_obw()
            self.draw_hline(self.lineObwP, self.labelObwP, y)
            self.draw_vline(self.lineObwFS, self.labelObwFS, xStart)
            self.draw_vline(self.lineObwFE, self.labelObwFE, xEnd)

        canvas.blit(self.axes.bbox)

    def hide_measure(self):
        self.lineMinP.set_visible(False)
        self.lineMaxP.set_visible(False)
        self.lineAvgP.set_visible(False)
        self.lineGMP.set_visible(False)
        self.lineHalfP.set_visible(False)
        self.lineHalfFS.set_visible(False)
        self.lineHalfFE.set_visible(False)
        self.lineObwP.set_visible(False)
        self.lineObwFS.set_visible(False)
        self.lineObwFE.set_visible(False)
        self.labelMinP.set_visible(False)
        self.labelMaxP.set_visible(False)
        self.labelAvgP.set_visible(False)
        self.labelGMP.set_visible(False)
        self.labelHalfP.set_visible(False)
        self.labelHalfFS.set_visible(False)
        self.labelHalfFE.set_visible(False)
        self.labelObwP.set_visible(False)
        self.labelObwFS.set_visible(False)
        self.labelObwFE.set_visible(False)

    def scale_plot(self, force=False):
        if self.extent is not None:
            if self.settings.autoF or force:
                self.axes.set_xlim(self.extent.get_f())
            if self.settings.autoL or force:
                self.axes.set_ylim(self.extent.get_l())
                self.barBase.set_clim(self.extent.get_l())
                norm = Normalize(vmin=self.extent.get_l()[0],
                                 vmax=self.extent.get_l()[1])
                for collection in self.axes.collections:
                    collection.set_norm(norm)
                try:
                    self.barBase.draw_all()
                except:
                    pass

    def redraw_plot(self):
        if self.figure is not None:
            post_event(self.notify, EventThreadStatus(Event.DRAW))

    def get_axes(self):
        return self.axes

    def get_plot_thread(self):
        return self.threadPlot

    def set_title(self, title):
        self.axes.set_title(title)

    def set_plot(self, spectrum, extent, annotate=False):
        self.extent = extent
        self.threadPlot = ThreadPlot(self, self.axes, spectrum,
                                     self.extent,
                                     self.settings.colourMap,
                                     self.settings.autoL,
                                     self.settings.lineWidth,
                                     self.barBase,
                                     self.settings.fadeScans,
                                     annotate, self.settings.average)
        self.threadPlot.start()

    def clear_plots(self):
        children = self.axes.get_children()
        for child in children:
            if child.get_gid() is not None:
                if child.get_gid() == "plot" or child.get_gid() == "peak":
                    child.remove()

    def set_grid(self, on):
        self.axes.grid(on)
        self.redraw_plot()

    def set_colourmap(self, colourMap):
        for collection in self.axes.collections:
            collection.set_cmap(colourMap)
        self.barBase.set_cmap(colourMap)
        try:
            self.barBase.draw_all()
        except:
            pass

    def close(self):
        self.figure.clear()
        self.figure = None
Exemplo n.º 46
0
def make_plot_3d(grid, grid_name, x, y, all_z, t, grid_t_idx, grid_x_idx, grid_z_idx, n_cols = 6,
                 outpath='', filename_prefix='LMA',do_save=True, 
                 image_type='pdf', colormap='cubehelix' , grid_range=None): 

    n_frames = t.shape[0]
    # n_cols = 6
    n_rows = int(ceil( float(n_frames) / n_cols ))
  
    if type(colormap) == type(''):
        colormap = get_cmap(colormap)
    grey_color = (0.5,)*3
    frame_color = (0.2,)*3
    
    density_maxes = []
    total_counts = []
    all_t = []
   
    xedge = centers_to_edges(x)
    x_range = xedge.max() - xedge.min()
    yedge = centers_to_edges(y)
    y_range = yedge.max() - yedge.min()
    dx = (xedge[1]-xedge[0])

    # count_scale_factor = dx # / 1000.0
    # max_count_baseline = 450 * count_scale_factor #/ 10.0
    min_count, max_count = 1, grid[:].max() #max_count_baseline*(t[1]-t[0])
    if (max_count == 0) | (max_count == 1 ):
        max_count = min_count+1

    default_vmin = -0.2
    if np.log10(max_count) <= default_vmin:
        vmin_count = np.log10(max_count) + default_vmin
    else:
        vmin_count = default_vmin

    # If the range of values for the colorbar is manually specified, 
    # overwrite what we did above
    if grid_range is not None:
        vmin_count = grid_range[0]
        max_count = grid_range[1]
            
    # w, h = figaspect(float(n_rows)/n_cols) # breaks for large numbers of frames - has a hard-coded max figure size
    w, h, n_rows_perpage, n_pages = multiples_figaspect(n_rows, n_cols, x_range, y_range, fig_width=8.5, max_height=None)
    fig = Figure(figsize=(w,h))
    canvas = FigureCanvasAgg(fig)
    fig.set_canvas(canvas)
    p = small_multiples_plot(fig=fig, rows=n_rows, columns=n_cols)
    p.label_edges(True)
    pad = 0.0 # for time labels in each frame

    for ax in p.multiples.flat:
        ax.set_axis_bgcolor('white')
        ax.spines['top'].set_edgecolor(frame_color)
        ax.spines['bottom'].set_edgecolor(frame_color)
        ax.spines['left'].set_edgecolor(frame_color)
        ax.spines['right'].set_edgecolor(frame_color)
    #   ax.yaxis.set_major_formatter(kilo_formatter)
    #   ax.xaxis.set_major_formatter(kilo_formatter)
    base_date = datetime.strptime(t.units, "seconds since %Y-%m-%d %H:%M:%S")
    time_delta = timedelta(0,float(t[0]),0)
    start_time = base_date + time_delta
    for zi in range(len(all_z)):
        indexer = [slice(None),]*len(grid.shape)
                                
        frame_start_times = []
          
        altitude = all_z[zi]
        for i in range(n_frames):
            p.multiples.flat[i].clear()   # reset (clear) the axes
            frame_start = base_date + timedelta(0,float(t[i]),0)
            frame_start_times.append(frame_start)
            indexer[grid_t_idx] = i
            indexer[grid_z_idx] = zi
            density = grid[indexer]
            density = np.ma.masked_where(density<=0.0, density) # mask grids 0 grids to reveal background color
             
            # density,edges = np.histogramdd((x,y), bins=(xedge,yedge))
            density_plot  = p.multiples.flat[i].pcolormesh(xedge,yedge,
                                       np.log10(density.transpose()),
                                       vmin=vmin_count,
                                       vmax=np.log10(max_count),
                                       cmap=colormap)
            label_string = frame_start.strftime('%H%M:%S')
            x_lab = xedge[0]-pad+x_range*.015
            y_lab = yedge[0]-pad+y_range*.015
            text_label = p.multiples.flat[i].text(x_lab, y_lab, label_string, color=grey_color, size=6)
            density_plot.set_rasterized(True)
            density_maxes.append(density.max())
            total_counts.append(density.sum())
            all_t.append(frame_start)
            print(label_string, x_lab, y_lab, grid_name, density.max(), density.sum())

        color_scale = ColorbarBase(p.colorbar_ax, cmap=density_plot.cmap,
                                           norm=density_plot.norm,
                                           orientation='horizontal')

        # color_scale.set_label('count per pixel')
        color_scale.set_label('log10(count per pixel)')

        view_x = (xedge.min(), xedge.max())
        view_y = (yedge.min(), yedge.max())

        print('making multiples')
        p.multiples.flat[0].axis(view_x+view_y)
        filename = '%s-%s_%s_%05.2fkm_%04.1fkm_%05.1fs.%s' % (filename_prefix, grid_name, start_time.strftime('%Y%m%d_%H%M%S'), dx, altitude, time_delta.seconds, image_type)
        filename = os.path.join(outpath, filename)
        if do_save:
            fig.savefig(filename, dpi=150)
        print('done ', zi)
    return fig, p, frame_start_times, filename
    print(' ... done with loop')
Exemplo n.º 47
0
def plotter(fdict):
    """ Go """
    ctx = get_autoplot_context(fdict, get_description())
    df = get_data(ctx)

    cmap = cm.get_cmap(ctx["cmap"])
    maxval = df["delta"].max()
    if maxval > 50:
        bins = np.arange(0, 101, 10)
    elif maxval > 25:
        bins = np.arange(0, 51, 5)
    else:
        bins = np.arange(0, 21, 2)
    bins[0] = 0.01
    norm = mpcolors.BoundaryNorm(bins, cmap.N)

    (fig, ax) = plt.subplots(1, 1, figsize=(6.4, 6.4))

    yearmax = df[["year", "delta"]].groupby("year").max()
    for year, df2 in df.groupby("year"):
        for _, row in df2.iterrows():
            # NOTE: minus 3.5 to center the 7 day bar
            ax.bar(
                row["doy"] - 3.5,
                1,
                bottom=year - 0.5,
                width=7,
                ec="None",
                fc=cmap(norm([row["delta"]]))[0],
            )

    sts = datetime.datetime(2000, 1,
                            1) + datetime.timedelta(days=int(df["doy"].min()))
    ets = datetime.datetime(2000, 1,
                            1) + datetime.timedelta(days=int(df["doy"].max()))
    now = sts
    interval = datetime.timedelta(days=1)
    jdays = []
    labels = []
    while now < ets:
        if now.day in [1, 8, 15, 22]:
            fmt = "%-d\n%b" if now.day == 1 else "%-d"
            jdays.append(int(now.strftime("%j")))
            labels.append(now.strftime(fmt))
        now += interval

    ax.set_xticks(jdays)
    ax.set_xticklabels(labels)

    minyear = df["year"].min()
    maxyear = df["year"].max()
    ax.set_yticks(range(minyear, maxyear + 1))
    ylabels = []
    for yr in range(minyear, maxyear + 1):
        if yr % 5 == 0:
            ylabels.append("%s %.0f" % (yr, yearmax.at[yr, "delta"]))
        else:
            ylabels.append("%.0f" % (yearmax.at[yr, "delta"], ))
    ax.set_yticklabels(ylabels, fontsize=10)

    ax.set_ylim(minyear - 0.5, maxyear + 0.5)
    ax.set_xlim(min(jdays), max(jdays))
    ax.grid(linestyle="-", linewidth="0.5", color="#EEEEEE", alpha=0.7)
    ax.set_title(("USDA NASS Weekly %s %s Progress\n"
                  "%s %% %s over weekly periods\n"
                  "yearly max labelled on left hand side") % (
                      ctx["unit_desc"],
                      PDICT2.get(ctx["commodity_desc"]),
                      state_names[ctx["state"]],
                      PDICT.get(ctx["unit_desc"]),
                  ))

    ax.set_position([0.13, 0.1, 0.71, 0.78])
    cax = plt.axes([0.86, 0.12, 0.03, 0.75],
                   frameon=False,
                   yticks=[],
                   xticks=[])
    cb = ColorbarBase(cax, norm=norm, cmap=cmap)
    cb.set_label("% Acres")

    return fig, df
Exemplo n.º 48
0
# Plot candidate directions.
lvals = [src.l for src in cands.values()]
bvals = [src.b for src in cands.values()]
x, y = m(lvals, bvals)
cand_pts = m.scatter(x, y, marker='+', linewidths=.5, 
    edgecolors='k', facecolors='none', zorder=10)  # hi zorder -> top

# Plot tissots showing possible scale of candidate scatter.
for l, b in zip(lvals, bvals):
    m.tissot(l, b, 5., 30, ec='none', color='g', alpha=0.25)

# Show the closest candidate to each CR.
for cr in CRs.values():
    cand = cands[cr.near_id]
    m.geodesic(cr.l, cr.b, cand.l, cand.b, lw=0.5, ls='-', c='g')

plt.title('UHE Cosmic Rays and Candidate Sources')
plt.legend([cr_pts, cand_pts], ['UHE CR', 'Candidate'],
    frameon=False, loc='lower right', scatterpoints=1)

# Plot a colorbar for the CR energies.
cb_ax = plt.axes([0.25, .1, .5, .03], frameon=False)  # rect=L,B,W,H
#bar = ColorbarBase(cb_ax, cmap=cmap, orientation='horizontal', drawedges=False)
vals = np.linspace(Evals.min(), Evals.max(), 100)
bar = ColorbarBase(cb_ax, values=vals, norm=norm_E, cmap=cmap, 
    orientation='horizontal', drawedges=False)
bar.set_label('CR Energy (EeV)')

plt.show()
Exemplo n.º 49
0
def showVarianceBar(mode_ensemble, highlights=None, **kwargs):

    from matplotlib.pyplot import figure, gca, annotate, subplots_adjust, plot
    from matplotlib.figure import Figure
    from matplotlib.colorbar import ColorbarBase
    from matplotlib.colors import Normalize, NoNorm
    from matplotlib import cm, colors

    fig = kwargs.pop('figure', None)

    if isinstance(fig, Figure):
        fig_num = fig.number
    elif fig is None or isinstance(fig, (int, str)):
        fig_num = fig
    else:
        raise TypeError(
            'figure can be either an instance of matplotlib.figure.Figure '
            'or a figure number.')
    if SETTINGS['auto_show']:
        if fig_num is None:
            figure(figsize=(6, 2))
        else:
            figure(fig_num)
    elif fig_num is not None:
        figure(fig_num)
    ax = gca()

    # adjust layouts
    box = ax.get_position()
    _, _, _, height = box.bounds
    ratio = 2.5
    box.y1 = box.y0 + height / ratio
    #box.y0 += height/7.
    ax.set_position(box)

    fract = kwargs.pop('fraction', True)

    #defarrow = {'width':1, 'headwidth':2,
    #            'facecolor':'black',
    #            'headlength': 4}
    defarrow = {'arrowstyle': '->'}
    arrowprops = kwargs.pop('arrowprops', defarrow)

    if fract:
        sig = calcSignatureFractVariance(mode_ensemble)
    else:
        sig = mode_ensemble.getVariances()

    variances = sig.getArray().sum(axis=1)
    #meanVar = variances.mean()
    #stdVar = variances.std()

    #variances = (variances - meanVar)/stdVar

    maxVar = variances.max()
    minVar = variances.min()

    cmap = kwargs.pop('cmap', 'jet')
    norm = Normalize(vmin=minVar, vmax=maxVar)
    cb = ColorbarBase(ax, cmap=cmap, norm=norm, orientation='horizontal')

    if not highlights:
        highlights = []

    indices = []
    labels = []
    ens_labels = mode_ensemble.getLabels()
    for hl in highlights:
        if isinstance(hl, str):
            if not ens_labels:
                raise TypeError(
                    'highlights should be a list of integers because '
                    'mode_ensemble has no label')
            indices.append(ens_labels.index(hl))
            labels.append(hl)
        else:
            try:
                index = int(hl)
            except:
                raise TypeError(
                    'highlights should be a list of integers or strings')
            indices.append(index)
            if ens_labels:
                labels.append(ens_labels[index])
            else:
                labels.append(str(index))

    annotations = []
    for i, label in zip(indices, labels):
        x = norm(variances[i])
        an = annotate(label,
                      xy=(x, 1),
                      xytext=(x, ratio),
                      arrowprops=arrowprops)
        annotations.append(an)

    for i in range(len(variances)):
        x = norm(variances[i])
        plot([x, x], [0, 1], 'w')

    cb.set_label('Variances')

    if SETTINGS['auto_show']:
        showFigure()
    return cb, annotations
Exemplo n.º 50
0
#!/usr/bin/env python
from BRadar.plotutils import NWS_Reflect


'''
Make a colorbar as a separate figure.
'''

#from matplotlib import pyplot, mpl
import matplotlib.pyplot as plt
from matplotlib.colorbar import ColorbarBase

# Make a figure and axes with dimensions as desired.
fig = plt.figure()
ax1 = fig.add_axes([0.45, 0.05, 0.03, 0.75])


# ColorbarBase derives from ScalarMappable and puts a colorbar
# in a specified axes, so it has everything needed for a
# standalone colorbar.  There are many more kwargs, but the
# following gives a basic continuous colorbar with ticks
# and labels.
cb1 = ColorbarBase(ax1, cmap=NWS_Reflect['ref_table'],
                                   norm=NWS_Reflect['norm'])
cb1.set_label('Reflectivity [dBZ]')

#pyplot.savefig('../../Documents/SPA/Colorbar_Raw.eps')
#pyplot.savefig('../../Documents/SPA/Colorbar_Raw.png', dpi=250)

plt.show()
Exemplo n.º 51
0
    def save_png(self, figname: str = "", **kwargs):
        """ """
        radius = self.radius.to(u.m).value
        colormap = kwargs.get("cmap", "YlGnBu_r")

        # Mini-Array positions in ENU coordinates
        nenufar = NenuFAR()[self.mini_arrays]
        ma_etrs = l93_to_etrs(nenufar.antenna_positions)
        ma_enu = etrs_to_enu(ma_etrs)

        # Plot the nearfield
        fig, ax = plt.subplots(figsize=kwargs.get("figsize", (10, 10)))
        nf_image_db = 10*np.log10(self.nearfield)
        ax.imshow(
            np.flipud(nf_image_db), # This needs to be understood...
            cmap=colormap,
            extent=[-radius, radius, -radius, radius],
            zorder=0,
            vmin=kwargs.get("vmin", np.min(nf_image_db)),
            vmax=kwargs.get("vmax", np.max(nf_image_db))
        )

        # Colorbar
        cax = inset_axes(ax,
           width="5%",
           height="100%",
           loc="lower left",
           bbox_to_anchor=(1.05, 0., 1, 1),
           bbox_transform=ax.transAxes,
           borderpad=0,
           )
        cb = ColorbarBase(
            cax,
            cmap=get_cmap(name=colormap),
            orientation="vertical",
            norm=Normalize(
                vmin=kwargs.get("vmin", np.min(nf_image_db)),
                vmax=kwargs.get("vmax", np.max(nf_image_db))
            ),
            ticks=LinearLocator(),
            format='%.2f'
        )
        cb.solids.set_edgecolor("face")
        cb.set_label(f"dB (Stokes {self.stokes})")
    
        # Show the contour of the simulated source imprints
        ground_granularity = np.linspace(-radius, radius, self.npix)
        posx, posy = np.meshgrid(ground_granularity, ground_granularity)
        dist = np.sqrt(posx**2 + posy**2)
        border_min = 0.1*self.npix
        border_max = self.npix - 0.1*self.npix
        for src in self.source_imprints.keys():
            # Normalize the imprint
            imprint = self.source_imprints[src]
            imprint /= imprint.max()
            # Plot the contours
            ax.contour(
                imprint,
                np.arange(0.8, 1, 0.04),
                cmap="copper",
                alpha=0.5,
                extent=[-radius, radius, -radius, radius],
                zorder=5
            )
            # Find the maximum of the emission
            max_y, max_x = np.unravel_index(
                imprint.argmax(),
                imprint.shape
            )
            # If maximum outside the plot, recenter it
            if (max_x <= border_min) or (max_y <= border_min) or (max_x >= border_max) or (max_y >= border_max):
                dist[dist<=np.median(dist)] = 0
                max_y, max_x = np.unravel_index(
                    ((1 - dist/dist.max())*imprint).argmax(),
                    imprint.shape
                )
            # Show the source name associated to the imprint
            ax.text(
                ground_granularity[max_x],
                ground_granularity[max_y],
                f" {src}",
                color="#b35900",
                fontweight="bold",
                va="center",
                ha="center",
                zorder=30
            )
        
        # NenuFAR mini-array positions
        ax.scatter(
            ma_enu[:, 0],
            ma_enu[:, 1],
            20,
            color='black',
            zorder=10
        )
        for i in range(ma_enu.shape[0]):
            ax.text(
                ma_enu[i, 0],
                ma_enu[i, 1],
                f" {self.mini_arrays[i]}",
                color="black",
                zorder=10
            )
        # ax.scatter(
        #     building_enu[:, 0],
        #     building_enu[:, 1],
        #     20,
        #     color="tab:red",#'tab:orange',
        #     zorder=10
        # )

        # Plot axis labels       
        ax.set_xlabel(r"$\Delta x$ (m)")
        ax.set_ylabel(r"$\Delta y$ (m)")
        ax.set_title(
            f"{np.mean(self.frequency.to(u.MHz).value):.3f} MHz -- {self.time.isot}"
        )

        # Save or show the figure
        if figname != "":
            plt.savefig(
                figname,
                dpi=300,
                bbox_inches="tight",
                transparent=True
            )
            log.info(f"Figure '{figname}' saved.")
        else:
            plt.show()
        plt.close("all")
Exemplo n.º 52
0
def showVarianceBar(mode_ensemble, highlights=None, **kwargs):

    from matplotlib.pyplot import figure, gca, annotate, subplots_adjust, plot
    from matplotlib.figure import Figure
    from matplotlib.colorbar import ColorbarBase
    from matplotlib.colors import Normalize, NoNorm
    from matplotlib import cm, colors
    
    fig = kwargs.pop('figure', None)

    if isinstance(fig, Figure):
        fig_num = fig.number
    elif fig is None or isinstance(fig, (int, str)):
        fig_num = fig
    else:
        raise TypeError('figure can be either an instance of matplotlib.figure.Figure '
                        'or a figure number.')
    if SETTINGS['auto_show']:
        if fig_num is None:
            figure(figsize=(6, 2))
        else:
            figure(fig_num)
    elif fig_num is not None:
        figure(fig_num)
    ax = gca()

    # adjust layouts
    box = ax.get_position()
    _, _, _, height = box.bounds
    ratio = 2.5
    box.y1 = box.y0 + height/ratio
    #box.y0 += height/7.
    ax.set_position(box)

    fract = kwargs.pop('fraction', True)

    #defarrow = {'width':1, 'headwidth':2, 
    #            'facecolor':'black',
    #            'headlength': 4}
    defarrow = {'arrowstyle': '->'}
    arrowprops = kwargs.pop('arrowprops', defarrow)

    if fract:
        sig = calcSignatureFractVariance(mode_ensemble)
    else:
        sig = mode_ensemble.getVariances() 

    variances = sig.getArray().sum(axis=1)
    #meanVar = variances.mean()
    #stdVar = variances.std()
    
    #variances = (variances - meanVar)/stdVar

    maxVar = variances.max()
    minVar = variances.min()

    cmap = kwargs.pop('cmap', 'jet')
    norm = Normalize(vmin=minVar, vmax=maxVar)
    cb = ColorbarBase(ax, cmap=cmap, norm=norm,
                      orientation='horizontal')

    if not highlights:
        highlights = []

    indices = []; labels = []
    ens_labels = mode_ensemble.getLabels()
    for hl in highlights:
        if isinstance(hl, str):
            if not ens_labels:
                raise TypeError('highlights should be a list of integers because '
                                    'mode_ensemble has no label')
            indices.append(ens_labels.index(hl))
            labels.append(hl)
        else:
            try:
                index = int(hl)
            except:
                raise TypeError('highlights should be a list of integers or strings') 
            indices.append(index)
            if ens_labels:
                labels.append(ens_labels[index])
            else:
                labels.append(str(index))

    annotations = []
    for i, label in zip(indices, labels):
        x = norm(variances[i])
        an = annotate(label, xy=(x, 1), xytext=(x, ratio), arrowprops=arrowprops)
        annotations.append(an)

    for i in range(len(variances)):
        x = norm(variances[i])
        plot([x, x], [0, 1], 'w')

    cb.set_label('Variances')

    if SETTINGS['auto_show']:
        showFigure()
    return cb, annotations