Exemple #1
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
Exemple #2
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()
Exemple #3
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
Exemple #4
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)
Exemple #5
0
def spikesplot_cb(position, cmap='viridis', fig=None):
    # Add colorbar
    if fig is None:
        fig = plt.gcf()

    cax = fig.add_axes(position)
    cb = ColorbarBase(cax, cmap=get_cmap(cmap), spacing='proportional',
                      orientation='horizontal', drawedges=False)
    cb.set_ticks([0, 0.5, 1.0])
    cb.set_ticklabels(['Inferior', '(axial slice)', 'Superior'])
    cb.outline.set_linewidth(0)
    cb.ax.xaxis.set_tick_params(width=0)
    return cax
Exemple #6
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()
Exemple #7
0
    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 ($\mathsf{dB/\sqrt{Hz}}$)')
        colour = hex2color(self.settings.background)
        colour += (1,)
        self.axes.w_xaxis.set_pane_color(colour)
        self.axes.w_yaxis.set_pane_color(colour)
        self.axes.w_zaxis.set_pane_color(colour)
        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))
Exemple #8
0
    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(utc_to_mpl(now), utc_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.__setup_measure()
        self.__setup_overflow()
        self.hide_measure()
    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)
Exemple #10
0
    def _colorbar_show(self, im, threshold):
        if threshold is None:
            offset = 0
        else:
            offset = threshold
        if offset > im.norm.vmax:
            offset = im.norm.vmax

        # create new  axis for the colorbar
        figure = self.frame_axes.figure
        _, y0, x1, y1 = self.rect
        height = y1 - y0
        x_adjusted_width = self._colorbar_width / len(self.axes)
        x_adjusted_margin = self._colorbar_margin['right'] / len(self.axes)
        lt_wid_top_ht = [x1 - (x_adjusted_width + x_adjusted_margin),
                         y0 + self._colorbar_margin['top'],
                         x_adjusted_width,
                         height - (self._colorbar_margin['top'] +
                                   self._colorbar_margin['bottom'])]
        self._colorbar_ax = figure.add_axes(lt_wid_top_ht, axis_bgcolor='w')

        our_cmap = im.cmap
        # edge case where the data has a single value
        # yields a cryptic matplotlib error message
        # when trying to plot the color bar
        nb_ticks = 5 if im.norm.vmin != im.norm.vmax else 1
        ticks = np.linspace(im.norm.vmin, im.norm.vmax, nb_ticks)
        bounds = np.linspace(im.norm.vmin, im.norm.vmax, our_cmap.N)

        # some colormap hacking
        cmaplist = [our_cmap(i) for i in range(our_cmap.N)]
        istart = int(im.norm(-offset, clip=True) * (our_cmap.N - 1))
        istop = int(im.norm(offset, clip=True) * (our_cmap.N - 1))
        for i in range(istart, istop):
            cmaplist[i] = (0.5, 0.5, 0.5, 1.)  # just an average gray color
        if im.norm.vmin == im.norm.vmax:  # len(np.unique(data)) == 1 ?
            return
        else:
            our_cmap = our_cmap.from_list('Custom cmap', cmaplist, our_cmap.N)

        self._cbar = ColorbarBase(
            self._colorbar_ax, ticks=ticks, norm=im.norm,
            orientation='vertical', cmap=our_cmap, boundaries=bounds,
            spacing='proportional')
        self._cbar.set_ticklabels(["%.2g" % t for t in ticks])

        self._colorbar_ax.yaxis.tick_left()
        tick_color = 'w' if self._black_bg else 'k'
        for tick in self._colorbar_ax.yaxis.get_ticklabels():
            tick.set_color(tick_color)
        self._colorbar_ax.yaxis.set_tick_params(width=0)

        self._cbar.update_ticks()
Exemple #11
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()
 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
Exemple #13
0
 def __init__(self, parent, colourMap):
     wx.Panel.__init__(self, parent)
     dpi = wx.ScreenDC().GetPPI()[0]
     figure = matplotlib.figure.Figure(facecolor='white', dpi=dpi)
     figure.set_size_inches(200.0 / dpi, 25.0 / dpi)
     self.canvas = FigureCanvas(self, -1, figure)
     axes = figure.add_subplot(111)
     figure.subplots_adjust(0, 0, 1, 1)
     norm = Normalize(vmin=0, vmax=1)
     self.bar = ColorbarBase(axes, norm=norm, orientation='horizontal',
                             cmap=cm.get_cmap(colourMap))
     axes.xaxis.set_visible(False)
def pic_switch(event):
    bounds = roi1.export()
    if zoom.value_selected == 'Zoom':
        axpic.cla()

        axpic.imshow(start.pic_list[int(pic_swap.val)], vmin=vmin.val, vmax=vmax.val, cmap=gray.value_selected)
        axpic.set_title(start.file_list[int(pic_swap.val)])
        axpic.set_xlim(bounds[2], bounds[3])
        axpic.set_ylim(bounds[1], bounds[0])
        axpic.axvline(x=bounds[2])
        axpic.axvline(x=bounds[3])
        axpic.axhline(y=bounds[0])
        axpic.axhline(y=bounds[1])
        axbar.cla()
        norm = Normalize(vmin=vmin.val, vmax=vmax.val)
        col = ColorbarBase(axbar, cmap=gray.value_selected, norm=norm, orientation='horizontal')
        col.set_ticks([vmin.val, vmax.val], update_ticks=True)
    else:
        axpic.cla()
        axpic.imshow(start.pic_list[int(pic_swap.val)], vmin=vmin.val, vmax=vmax.val, cmap=gray.value_selected)
        axpic.set_title(start.file_list[int(pic_swap.val)])
        axpic.axvline(x=bounds[2])
        axpic.axvline(x=bounds[3])
        axpic.axhline(y=bounds[0])
        axpic.axhline(y=bounds[1])
        axbar.cla()
        norm = Normalize(vmin=vmin.val, vmax=vmax.val)
        col = ColorbarBase(axbar, cmap=gray.value_selected, norm=norm, orientation='horizontal')
        col.set_ticks([vmin.val, vmax.val], update_ticks=True)
Exemple #15
0
    def display_median_price_animation(self):
        """Kicks off the animation of median price information."""
        fig = plotter.figure(num = 1, figsize = (10, 12), tight_layout = True)
        fig.canvas.set_window_title('Percent increase in median house ' + \
                                    'price since 1996')

        axis = fig.add_axes([0.85, 0.04, 0.03, 0.92])
        colorbar_ticks = [0, .2, .4, .6, .8, 1.0]
        colorbar_labels = ['-100%', '0%', '250%', '500%', '750%', '>1000%']
        colorbar = ColorbarBase(axis, self._colormap, orientation='vertical')
        colorbar.set_ticks(colorbar_ticks)
        colorbar.set_ticklabels(colorbar_labels)

        fig.add_axes([0.0, 0.0, 0.82, 1.0])
        anim = FuncAnimation(fig,
                             self._animate,
                             frames = self.endyear + 1 - self.startyear,
                             interval = 1000,
                             blit = True,
                             init_func = self._init_animate,
                             repeat_delay = 3000)
        plotter.show()
Exemple #16
0
    def __init__(self, parent=None):
        FigureCanvas.__init__(self, Figure())

        self._telemetry = None
        self._resolution = None
        self._cmap = None
        self._wireframe = False

        self.setParent(parent)

        self.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.setFocus()

        colour = self.palette().color(self.backgroundRole()).getRgbF()
        self.figure.patch.set_facecolor(colour[:-1])

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

        self._axes = self.figure.add_subplot(gs[0], projection='3d')
        self._axes.set_title('3D Plot')
        self._axes.set_xlabel('Longitude')
        self._axes.set_ylabel('Latitude')
        self._axes.set_zlabel('Level (dB)')
        self._axes.tick_params(axis='both', which='major', labelsize='smaller')
        self._axes.grid(True)
        formatMaj = ScalarFormatter(useOffset=False)
        self._axes.xaxis.set_major_formatter(formatMaj)
        self._axes.yaxis.set_major_formatter(formatMaj)
        self._axes.zaxis.set_major_formatter(formatMaj)
        formatMinor = AutoMinorLocator(10)
        self._axes.xaxis.set_minor_locator(formatMinor)
        self._axes.yaxis.set_minor_locator(formatMinor)
        self._axes.zaxis.set_minor_locator(formatMinor)

        self._axesBar = self.figure.add_subplot(gs[1])
        self._axesBar.tick_params(axis='both', which='major',
                                  labelsize='smaller')
        self._bar = ColorbarBase(self._axesBar)

        if matplotlib.__version__ >= '1.2':
            self.figure.tight_layout()
Exemple #17
0
    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_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 ($\mathsf{dB/\sqrt{Hz}}$)')
        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)
        self.set_colourmap_use(self.settings.colourMapUse)

        self.__setup_measure()
        self.__setup_overflow()
        self.hide_measure()
Exemple #19
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]')
Exemple #20
0
    def __init__(self, cmap, vmin, vmax=None, label=True, label_position=None,
                 label_rotation=None,
                 clipmin=None, clipmax=None, orientation='horizontal',
                 unit=None, contours=(), width=None, ticks=None, threshold=None,
                 ticklocation='auto', background='white', tight=True,
                 h=None, w=None, *args, **kwargs):
        # get Colormap
        if isinstance(cmap, np.ndarray):
            if threshold is not None:
                raise NotImplementedError("threshold parameter with cmap=array")
            if cmap.max() > 1:
                cmap = cmap / 255.
            cm = mpl.colors.ListedColormap(cmap, 'LUT')
        else:
            cm = mpl.cm.get_cmap(cmap)

        # prepare layout
        if orientation == 'horizontal':
            if h is None and w is None:
                h = 1
            ax_aspect = 4
        elif orientation == 'vertical':
            if h is None and w is None:
                h = 4
            ax_aspect = 0.3
        else:
            raise ValueError("orientation=%s" % repr(orientation))

        layout = Layout(1, ax_aspect, 2, tight, False, h, w, *args, **kwargs)
        EelFigure.__init__(self, cm.name, layout)
        ax = self._axes[0]

        # translate between axes and data coordinates
        if isinstance(vmin, Normalize):
            norm = vmin
        else:
            vmin, vmax = fix_vlim_for_cmap(vmin, vmax, cm.name)
            norm = Normalize(vmin, vmax)

        # value ticks
        if ticks is False:
            ticks = ()
            tick_labels = None
        elif isinstance(ticks, dict):
            tick_dict = ticks
            ticks = sorted(tick_dict)
            tick_labels = [tick_dict[t] for t in ticks]
        else:
            tick_labels = None

        if orientation == 'horizontal':
            axis = ax.xaxis
            contour_func = ax.axhline
        else:
            axis = ax.yaxis
            contour_func = ax.axvline

        if label is True:
            if unit:
                label = unit
            else:
                label = cm.name
        elif not label:
            label = ''

        # show only part of the colorbar
        if clipmin is not None or clipmax is not None:
            if isinstance(norm, SymmetricNormalize):
                raise NotImplementedError(
                    "clipmin or clipmax with SymmetricNormalize")
            boundaries = norm.inverse(np.linspace(0, 1, cm.N + 1))
            if clipmin is None:
                start = None
            else:
                start = np.digitize(clipmin, boundaries, True)
            if clipmax is None:
                stop = None
            else:
                stop = np.digitize(clipmax, boundaries) + 1
            boundaries = boundaries[start:stop]
        else:
            boundaries = None

        colorbar = ColorbarBase(ax, cm, norm, boundaries=boundaries,
                                orientation=orientation,
                                ticklocation=ticklocation, ticks=ticks,
                                label=label)

        # fix tick location
        if isinstance(norm, SymmetricNormalize) and ticks is not None:
            tick_norm = Normalize(norm.vmin, norm.vmax, norm.clip)
            axis.set_ticks(tick_norm(ticks))

        # unit-based tick-labels
        if unit and tick_labels is None:
            formatter, label = find_axis_params_data(unit, label)
            tick_labels = tuple(map(formatter, colorbar.get_ticks()))

        if tick_labels is not None:
            if clipmin is not None:
                tick_labels = [l for l, t in zip(tick_labels, ticks) if t >= clipmin]
            axis.set_ticklabels(tick_labels)

        # label position/rotation
        if label_position is not None:
            axis.set_label_position(label_position)
        if label_rotation is not None:
            axis.label.set_rotation(label_rotation)
            if orientation == 'vertical':
                if (label_rotation + 10) % 360 < 20:
                    axis.label.set_va('center')
        elif orientation == 'vertical' and len(label) <= 3:
            axis.label.set_rotation(0)
            axis.label.set_va('center')

        self._contours = [contour_func(c, c='k') for c in contours]
        self._draw_hooks.append(self.__fix_alpha)
        self._draw_hooks.append(self.__update_bar_tickness)

        self._background = background
        self._colorbar = colorbar
        self._orientation = orientation
        self._width = width
        self._show()
class Plotter3d(object):
    def __init__(self, notify, figure, settings):
        self.notify = notify
        self.figure = figure
        self.settings = settings
        self.axes = None
        self.bar = None
        self.barBase = None
        self.plot = None
        self.extent = None
        self.threadPlot = None
        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 ($\mathsf{dB/\sqrt{Hz}}$)')
        colour = hex2color(self.settings.background)
        colour += (1, )
        self.axes.w_xaxis.set_pane_color(colour)
        self.axes.w_yaxis.set_pane_color(colour)
        self.axes.w_zaxis.set_pane_color(colour)
        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(utc_to_mpl(now), utc_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))

    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, EventThread(Event.DRAW))

    def get_axes(self):
        return self.axes

    def get_axes_bar(self):
        return self.barBase.ax

    def get_plot_thread(self):
        return self.threadPlot

    def set_title(self, title):
        self.axes.set_title(title, fontsize='medium')

    def set_plot(self, spectrum, extent, annotate=False):
        self.extent = extent
        self.threadPlot = ThreadPlot(self, self.settings, self.axes, spectrum,
                                     self.extent, 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_line" 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
Exemple #22
0
        #To incorporate difference between Map State Name and Data Loc Name
        if statename == "Telangana":
            statename = "Telengana"
        if statename in color_dict:
            pop = color_dict[statename]
            colors[statename] = mapper.to_rgba(pop)
            statenames.append(statename)

    for nshape, seg in enumerate(m.INDIA):
        color = rgb2hex(colors[statenames[nshape]])
        poly = Polygon(seg, facecolor=color, edgecolor=color)
        ax.add_patch(poly)
    plt.title('Confirmed Cases on ' + data['data'][ind]['day'])

    cax = fig.add_axes([0.27, 0.1, 0.5, 0.05])  # posititon
    cb = ColorbarBase(cax, cmap=cmap, norm=norm, orientation='horizontal')
    cb.ax.set_xlabel('Number of Cases')
    fig1 = plt.gcf()
    plt.show()
    fig1.savefig(folder + "/file%02d.png" % ind)

video_name = 'time_map.avi'

images = [img for img in os.listdir(folder) if img.endswith(".png")]
frame = cv2.imread(os.path.join(folder, images[0]))
height, width, layers = frame.shape

#0.7 is the fps (frame per second)
video = cv2.VideoWriter(video_name, 0, 0.7, (width, height))

for image in sorted(images):
Exemple #23
0
def axplot_ChangeProbs(ax,
                       change_probs,
                       wt_colors,
                       ttl='',
                       vmin=0,
                       vmax=1,
                       cmap='Blues',
                       cbar_ttl=''):
    'axes plot cluster change probabilities'

    num_clusters = change_probs.shape[0]

    # clsuter transition plot
    pc = ax.pcolor(
        change_probs,
        cmap=cmap,
        vmin=vmin,
        vmax=vmax,
    )

    # add colorbar
    cbar = plt.colorbar(pc, ax=ax)
    cbar.ax.tick_params(labelsize=8)
    if vmin != 0 or vmax != 1:
        cbar.set_ticks(np.linspace(vmin, vmax, 6))
    cbar.ax.set_ylabel(cbar_ttl, rotation=270, labelpad=20)

    # customize axes
    ax.set_xticks(np.arange(num_clusters) + 0.5)
    ax.set_yticks(np.arange(num_clusters) + 0.5)
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.set_title(ttl, {'fontsize': 10, 'fontweight': 'bold'})

    # add custom color axis
    ccmap = mcolors.ListedColormap([tuple(r) for r in wt_colors])

    # custom color axis positions
    ax_pos = ax.get_position()
    cax_x_pos = [ax_pos.x0, ax_pos.y0 - 0.03, ax_pos.width, 0.02]
    cax_y_pos = [
        ax_pos.x0 - 0.03 / _faspect, ax_pos.y0, 0.02 / _faspect, ax_pos.height
    ]

    # custom color axis X
    cax_x = ax.figure.add_axes(cax_x_pos)
    cbar_x = ColorbarBase(
        cax_x,
        cmap=ccmap,
        orientation='horizontal',
        norm=mcolors.Normalize(vmin=0, vmax=num_clusters),
    )
    cbar_x.set_ticks([])

    # custom color axis Y
    cax_y = ax.figure.add_axes(cax_y_pos)
    cbar_y = ColorbarBase(
        cax_y,
        cmap=ccmap,
        orientation='vertical',
        norm=mcolors.Normalize(vmin=0, vmax=num_clusters),
    )
    cbar_y.set_ticks([])
Exemple #24
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()

    '''
Exemple #25
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)
def plot_us_data(fig, ax, m, m_, data, label_text, title_text):

    #%% -------- choose a color for each state based on population density. -------
    colors = {}
    statenames = []
    cmap = plt.cm.hot_r  # use 'reversed hot' colormap
    #find max/min.  Then round to 2 dp.

    vmin = round(np.nanmin(data.values), 2)
    vmax = round(np.nanmax(data.values), 2)  # set range.

    norm = Normalize(vmin=vmin, vmax=vmax)
    for shapedict in m.states_info:
        statename = shapedict['NAME']
        # skip DC and Puerto Rico.
        if statename not in ['District of Columbia', 'Puerto Rico']:
            pop = data[statename]
            # calling colormap with value between 0 and 1 returns
            # rgba value.  Invert color range (hot colors are high
            # population), take sqrt root to spread out colors more.
            if np.isnan(pop):
                pop = vmin
            colors[statename] = cmap(((pop - vmin) / (vmax - vmin)))[:3]
        statenames.append(statename)

    #%% ---------  cycle through state names, color each one.  --------------------
    for nshape, seg in enumerate(m.states):
        # skip DC and Puerto Rico.
        if statenames[nshape] not in ['Puerto Rico', 'District of Columbia']:
            color = rgb2hex(colors[statenames[nshape]])
            poly = Polygon(seg, facecolor=color, edgecolor=color)
            ax.add_patch(poly)
    AREA_1 = 0.005  # exclude small Hawaiian islands that are smaller than AREA_1
    AREA_2 = AREA_1 * 30.0  # exclude Alaskan islands that are smaller than AREA_2
    AK_SCALE = 0.19  # scale down Alaska to show as a map inset
    HI_OFFSET_X = -1900000  # X coordinate offset amount to move Hawaii "beneath" Texas
    HI_OFFSET_Y = 250000  # similar to above: Y offset for Hawaii
    AK_OFFSET_X = -250000  # X offset for Alaska (These four values are obtained
    AK_OFFSET_Y = -750000  # via manual trial and error, thus changing them is not recommended.)

    for nshape, shapedict in enumerate(
            m_.states_info):  # plot Alaska and Hawaii as map insets
        if shapedict['NAME'] in ['Alaska', 'Hawaii']:
            seg = m_.states[int(shapedict['SHAPENUM'] - 1)]
            if shapedict['NAME'] == 'Hawaii' and float(
                    shapedict['AREA']) > AREA_1:
                seg = [(x + HI_OFFSET_X, y + HI_OFFSET_Y) for x, y in seg]
                color = rgb2hex(colors[statenames[nshape]])
            elif shapedict['NAME'] == 'Alaska' and float(
                    shapedict['AREA']) > AREA_2:
                seg = [(x*AK_SCALE + AK_OFFSET_X, y*AK_SCALE + AK_OFFSET_Y)\
                       for x, y in seg]
                color = rgb2hex(colors[statenames[nshape]])
            poly = Polygon(seg,
                           facecolor=color,
                           edgecolor='gray',
                           linewidth=.45)
            ax.add_patch(poly)

    #%% ---------  Plot bounding boxes for Alaska and Hawaii insets  --------------
    light_gray = [0.8] * 3  # define light gray color RGB
    x1, y1 = m_([-190, -183, -180, -180, -175, -171, -171],
                [29, 29, 26, 26, 26, 22, 20])
    x2, y2 = m_([-180, -180, -177],
                [26, 23, 20])  # these numbers are fine-tuned manually
    m_.plot(x1, y1, color=light_gray,
            linewidth=0.8)  # do not change them drastically
    m_.plot(x2, y2, color=light_gray, linewidth=0.8)

    ax.set_title(title_text)
    #%% ---------   Show color bar  ---------------------------------------
    ax_c = fig.add_axes([0.9, 0.1, 0.03, 0.8])
    cb = ColorbarBase(ax_c,
                      cmap=cmap,
                      norm=norm,
                      orientation='vertical',
                      label=label_text)
    plt.show()
Exemple #27
0
                  linewidth=1.0)
    ax[s].axvline(x=2.0,
                  ymin=0,
                  ymax=len(picks),
                  color='black',
                  linestyle='dashed',
                  linewidth=1.0)

    colormap = cm.get_cmap('RdBu_r')
    orientation = 'vertical'
    norm = Normalize(vmin=-5.0, vmax=5.0)
    divider = make_axes_locatable(ax[s])
    cax = divider.append_axes('right', size='2.5%', pad=0.2)
    cbar = ColorbarBase(cax,
                        cm.get_cmap('RdBu_r'),
                        ticks=[-5.0, 0., 5.0],
                        norm=norm,
                        label=r'Difference B-A ($\mu$V)',
                        orientation=orientation)
    cbar.outline.set_visible(False)
    cbar.ax.set_frame_on(True)
    label = r'Difference B-A (in $\mu V$)'
    for key in ('left', 'top',
                'bottom' if orientation == 'vertical' else 'right'):
        cbar.ax.spines[key].set_visible(False)

    fig.subplots_adjust(left=0.05,
                        right=0.95,
                        bottom=0.15,
                        wspace=0.3,
                        hspace=0.25)
Exemple #28
0
def _draw_colorbar(stat_map_img, axes,
	threshold=.1,
	nb_ticks=5,
	edge_color="0.5",
	edge_alpha=1,
	aspect=40,
	fraction=0.025,
	anchor=(10.0,0.5),
	cut_coords=None,
	positive_only=False,
	negative_only=False,
	cmap=None,
	really_draw=True,
	bypass_cmap=False,
	pad=0.05,
	panchor=(10.0, 0.5),
	shrink=1.0,
	):
	if bypass_cmap:
		bypass_cmap = cmap
	if isinstance(stat_map_img, str):
		stat_map_img = path.abspath(path.expanduser(stat_map_img))
		stat_map_img = nib.load(stat_map_img)
		stat_map_img_dat = _safe_get_data(stat_map_img, ensure_finite=True)
	else:
		stat_map_img_dat = stat_map_img
	cbar_vmin,cbar_vmax,vmin, vmax = _get_colorbar_and_data_ranges(stat_map_img_dat,None,"auto","")

	if cmap:
		try:
			cmap = plt.cm.get_cmap(cmap)
		except TypeError:
			cmap = mcolors.LinearSegmentedColormap.from_list('SAMRI cmap from list', cmap*256, N=256)
		colors = cmap(np.linspace(0,1,256))
		if positive_only:
			cmap_plus = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors[0:255,:])
		elif negative_only:
			cmap_minus = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors[0:255,:])
		else:
			cmap_minus = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors[0:128,:])
			cmap_plus = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors[128:255,:])
	else:
		cmap_minus = MYMAP_MINUS
		cmap_plus = MYMAP_PLUS
		cmap = MYMAP

	if cbar_vmin is not None or positive_only:
		vmin = 0
		colmap = cmap_plus
	elif cbar_vmax is not None or negative_only:
		vmax = 0
		colmap = cmap_minus
	else:
		colmap = cmap

	ticks = np.linspace(vmin, vmax, nb_ticks)
	bounds = np.linspace(vmin, vmax, colmap.N)
	norm = mcolors.Normalize(vmin=vmin, vmax=vmax)
	# some colormap hacking
	cmaplist = [colmap(i) for i in range(colmap.N)]
	istart = int(norm(-threshold, clip=True) * (colmap.N - 1))
	istop = int(norm(threshold, clip=True) * (colmap.N - 1))
	for i in range(istart, (istop+1)):
		# just an average gray color
		cmaplist[i] = (0.5, 0.5, 0.5, 1.)
	try:
		our_cmap = colmap.from_list('Custom cmap', cmaplist, colmap.N)
	except AttributeError:
		pass

	if really_draw:
		cbar_ax, p_ax = make_axes(axes,
			fraction=fraction,
			pad=pad,
			shrink=shrink,
			aspect=aspect,
			anchor=anchor,
			panchor=panchor,
			)
		cbar = ColorbarBase(
			cbar_ax,
			ticks=ticks,
			norm=norm,
			orientation="vertical",
			cmap=our_cmap,
			boundaries=bounds,
			spacing="proportional",
			format="%.2g",
			)

		cbar.outline.set_edgecolor(edge_color)
		cbar.outline.set_alpha(edge_alpha)

		cbar_ax.yaxis.tick_left()
		tick_color = 'k'
		for tick in cbar_ax.yaxis.get_ticklabels():
			tick.set_color(tick_color)
		cbar_ax.yaxis.set_tick_params(width=0)
	else:
		cbar_ax = None
		p_ax = None

	if bypass_cmap:
		colmap = bypass_cmap

	return cbar_ax, p_ax,vmin,vmax,colmap
Exemple #29
0
def plotter(fdict):
    """ Go """
    ctx = get_autoplot_context(fdict, get_description())
    df = get_data(ctx)

    cmap = 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
Exemple #30
0
def _colormap_plot_beamforming_polar(cmaps):
    """
    Plot for illustrating colormaps: beamforming.

    :param cmaps: list of :class:`~matplotlib.colors.Colormap`
    :rtype: None
    """
    import matplotlib.pyplot as plt
    from matplotlib.colorbar import ColorbarBase
    from matplotlib.colors import Normalize

    from obspy import UTCDateTime
    from obspy.signal.array_analysis import array_processing
    # Execute array_processing
    kwargs = dict(
        # slowness grid: X min, X max, Y min, Y max, Slow Step
        sll_x=-3.0,
        slm_x=3.0,
        sll_y=-3.0,
        slm_y=3.0,
        sl_s=0.03,
        # sliding window properties
        win_len=1.0,
        win_frac=0.05,
        # frequency properties
        frqlow=1.0,
        frqhigh=8.0,
        prewhiten=0,
        # restrict output
        semb_thres=-1e9,
        vel_thres=-1e9,
        stime=UTCDateTime("20080217110515"),
        etime=UTCDateTime("20080217110545"))
    st = _get_beamforming_example_stream()
    out = array_processing(st, **kwargs)
    # make output human readable, adjust backazimuth to values between 0 and
    # 360
    t, rel_power, abs_power, baz, slow = out.T
    baz[baz < 0.0] += 360
    # choose number of fractions in plot (desirably 360 degree/N is an
    # integer!)
    num = 36
    num2 = 30
    abins = np.arange(num + 1) * 360. / num
    sbins = np.linspace(0, 3, num2 + 1)
    # sum rel power in bins given by abins and sbins
    hist, baz_edges, sl_edges = \
        np.histogram2d(baz, slow, bins=[abins, sbins], weights=rel_power)
    # transform to radian
    baz_edges = np.radians(baz_edges)
    dh = abs(sl_edges[1] - sl_edges[0])
    dw = abs(baz_edges[1] - baz_edges[0])
    for cmap in cmaps:
        # add polar and colorbar axes
        fig = plt.figure(figsize=(8, 8))
        cax = fig.add_axes([0.85, 0.2, 0.05, 0.5])
        ax = fig.add_axes([0.10, 0.1, 0.70, 0.7], polar=True)
        ax.set_theta_direction(-1)
        ax.set_theta_zero_location("N")
        # circle through backazimuth
        for i, row in enumerate(hist):
            ax.bar((i * dw) * np.ones(num2),
                   height=dh * np.ones(num2),
                   width=dw,
                   bottom=dh * np.arange(num2),
                   color=cmap(row / hist.max()))
        ax.set_xticks(np.linspace(0, 2 * np.pi, 4, endpoint=False))
        ax.set_xticklabels(['N', 'E', 'S', 'W'])
        # set slowness limits
        ax.set_ylim(0, 3)
        [i.set_color('grey') for i in ax.get_yticklabels()]
        ColorbarBase(cax,
                     cmap=cmap,
                     norm=Normalize(vmin=hist.min(), vmax=hist.max()))
    plt.show()
Exemple #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.decode(),
                                  "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', end=' ')
    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')
Exemple #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
Exemple #33
0
def main(infold, mns_path, epsg_code, outfile, titre):
    """Main plotting function."""
    files = {}
    for file in infold.iterdir():
        files.update({file.name: file})

    # Extract the info
    nb = list(files.keys())[0].split("_")[-1].split(".")[0]
    width = list(files.keys())[0].split("_")[-3]
    azi = list(files.keys())[0].split("_")[-5]

    # Open gdal raster
    MNS_data, MNS_gt, MNS_ds = open_large_raster(str(mns_path))

    # Open transect
    data_tr = {}
    for fname, pth in files.items():
        if "transect" in fname:
            with open(pth, "rb") as f:
                transects = pickle.load(f)
        else:
            data_tr.update({"_".join(fname.split("_")[0:2]): pd.read_hdf(pth)})

    # Get very approximate center of transects
    midishline = transects[int(len(transects) / 2)]
    mid_point = midishline.interpolate(0.5, normalized=True)
    midpoint_buffer = mid_point.buffer(midishline.length / 2)
    envelope = midpoint_buffer.envelope

    # Turn interactive plotting off
    plt.ioff()

    # Create figure
    fig = plt.figure(figsize=(15.4, 6.6))
    fig.suptitle(titre)

    # Epsg
    proj_code = ccrs.epsg(epsg_code)

    # 2 by 2 grid
    gs = GridSpec(ncols=3, nrows=2, figure=fig, width_ratios=[0.1, 1.5, 4])
    ax = plt.subplot(gs[0, 1], projection=proj_code)
    ax1 = plt.subplot(gs[:, 0])
    ax2 = plt.subplot(gs[-1, 1], projection=proj_code)
    ax3 = plt.subplot(gs[:, -1])

    # AX
    mns_masked = np.ma.masked_where(MNS_data < 0, MNS_data)
    extent = (
        MNS_gt[0],
        MNS_gt[0] + MNS_ds.RasterXSize * MNS_gt[1],
        MNS_gt[3] + MNS_ds.RasterYSize * MNS_gt[5],
        MNS_gt[3],
    )

    ax.imshow(
        mns_masked, extent=extent, origin="upper", cmap="gist_earth"
    )

    ax.plot(
        [midishline.coords[0][0], midishline.coords[-1][0]],
        [midishline.coords[0][1], midishline.coords[-1][1]],
        linestyle="-",
        color="red",
        linewidth=1,
    )

    norm = Normalize(vmin=np.min(mns_masked), vmax=np.max(mns_masked))
    cbar = ColorbarBase(
        ax1, cmap=plt.get_cmap("gist_earth"), norm=norm, orientation="vertical"
    )
    cbar.ax.yaxis.set_label_position("left")
    cbar.ax.set_ylabel("Altitude / m")

    # AX2
    ax2.imshow(
        mns_masked, extent=extent, origin="upper", cmap="gist_earth"
    )

    for line in transects:
        ax2.plot(
            [line.coords[0][0], line.coords[-1][0]],
            [line.coords[0][1], line.coords[-1][1]],
            linestyle="-",
            color="black",
            alpha=0.6,
            linewidth=0.5,
        )

    ax2.set_extent(
        [
            envelope.bounds[0],
            envelope.bounds[2],
            envelope.bounds[1],
            envelope.bounds[-1],
        ],
        crs=ccrs.epsg(epsg_code),
    )

    ax2.set_title("Zoom on transects", y=-0.2)
    # AX3

    # Plot MNT/ MNS ground
    data_tr["MNT_solnu"].T.plot(
        ax=ax3, color="sienna", alpha=0.1, legend=False
    )
    data_tr["MNT_solnu"].T.mean(axis=1).plot(
        ax=ax3, color="sienna", legend=True, label="Mean summer DTM"
    )

    data_tr["MNS_solnu"].T.plot(
        ax=ax3, color="lightgreen", alpha=0.1, legend=False
    )
    data_tr["MNS_solnu"].T.mean(axis=1).plot(
        ax=ax3, color="lightgreen", legend=True, label="Mean summer DSM"
    )

    # Plot MNS neige
    data_tr["MNS_neige"].T.plot(
        ax=ax3, color="midnightblue", alpha=0.2, legend=False
    )
    data_tr["MNS_neige"].T.mean(axis=1).plot(
        ax=ax3, color="midnightblue", legend=True, label="Mean winter DSM"
    )

    ax3.set_title(
        "Azimuth: %s°, Width: %sm, # of transects: %s" % (azi, width, nb)
    )
    ax3.set_xlabel("Distance along transect / m")
    ax3.set_ylabel("Altitude / m")
    ax3.set_xlim(0, midishline.length)
    ax3.set_ylim(
        np.nanmin(data_tr["MNT_solnu"].T.mean(axis=1)) - 5,
        np.nanmax(data_tr["MNS_neige"].T.mean(axis=1)) + 5,
    )

    ax3.xaxis.set_major_locator(MultipleLocator(10))
    ax3.xaxis.set_minor_locator(MultipleLocator(5))
    ax3.yaxis.set_major_locator(MultipleLocator(1))
    ax3.yaxis.set_minor_locator(MultipleLocator(0.5))
    ax3.xaxis.set_ticks_position("both")
    ax3.yaxis.set_ticks_position("both")
    ax3.tick_params(direction="inout", which="both")

    fig.savefig(infold.joinpath(outfile), bbox_inches="tight", dpi=300)
Exemple #34
0
def plot_heatmap(dataframe,
                 vmin=None,
                 vmax=None,
                 cmap=None,
                 center=None,
                 robust=False,
                 annot=None,
                 fmt='.2g',
                 annot_kws=None,
                 linewidths=0,
                 linecolor='white',
                 cbar=False,
                 cbar_kws=None,
                 cbar_ax=None,
                 square=False,
                 xticklabels=False,
                 yticklabels=False,
                 mask=None,
                 figure_size=FIGURE_SIZE,
                 data_type='continuous',
                 normalization_method=None,
                 normalization_axis=0,
                 max_std=3,
                 axis_to_sort=None,
                 cluster=False,
                 row_annotation=(),
                 column_annotation=(),
                 annotation_colors=(),
                 title=None,
                 xlabel=None,
                 ylabel=None,
                 xlabel_rotation=0,
                 ylabel_rotation=90,
                 xtick_rotation=90,
                 ytick_rotation=0,
                 filepath=None,
                 file_extension='pdf',
                 dpi=DPI,
                 **kwargs):
    """
    Plot heatmap.
    :param dataframe:
    :param vmin:
    :param vmax:
    :param cmap:
    :param center:
    :param robust:
    :param annot:
    :param fmt:
    :param annot_kws:
    :param linewidths:
    :param linecolor:
    :param cbar:
    :param cbar_kws:
    :param cbar_ax:
    :param square:
    :param xticklabels:
    :param yticklabels:
    :param mask:
    :param figure_size:
    :param data_type:
    :param normalization_method:
    :param normalization_axis:
    :param max_std:
    :param axis_to_sort:
    :param cluster:
    :param row_annotation:
    :param column_annotation:
    :param annotation_colors: list; a list of matplotlib color specifications
    :param title:
    :param xlabel:
    :param ylabel:
    :param xlabel_rotation:
    :param ylabel_rotation:
    :param xtick_rotation:
    :param ytick_rotation:
    :param filepath:
    :param file_extension:
    :param dpi:
    :param kwargs:
    :return: None
    """

    df = dataframe.copy()

    if normalization_method:
        df = normalize_2d_or_1d(df,
                                normalization_method,
                                axis=normalization_axis).clip(
                                    -max_std, max_std)

    if len(row_annotation) or len(column_annotation):
        if len(row_annotation):
            if isinstance(row_annotation, Series):
                row_annotation = row_annotation.copy()
                if not len(row_annotation.index & df.index):  # Series
                    # but without proper index
                    row_annotation.index = df.index
            else:
                row_annotation = Series(row_annotation, index=df.index)

            row_annotation.sort_values(inplace=True)
            df = df.ix[row_annotation.index, :]

        if len(column_annotation):
            if isinstance(column_annotation, Series):
                column_annotation = column_annotation.copy()
                # Series but without proper index
                if not len(column_annotation.index & df.columns):
                    column_annotation.index = df.columns
            else:
                column_annotation = Series(column_annotation, index=df.columns)

            column_annotation.sort_values(inplace=True)
            df = df.ix[:, column_annotation.index]

    if axis_to_sort in (0, 1):
        a = array(df)
        a.sort(axis=axis_to_sort)
        df = DataFrame(a, index=df.index)

    elif cluster:
        row_indices, column_indices = get_dendrogram_leaf_indices(dataframe)
        df = df.iloc[row_indices, column_indices]
        if isinstance(row_annotation, Series):
            row_annotation = row_annotation.iloc[row_indices]
        if isinstance(column_annotation, Series):
            column_annotation = column_annotation.iloc[column_indices]

    figure(figsize=figure_size)

    gridspec = GridSpec(10, 10)

    ax_top = subplot(gridspec[0:1, 2:-2])
    ax_center = subplot(gridspec[1:8, 2:-2])
    ax_bottom = subplot(gridspec[8:10, 2:-2])
    ax_left = subplot(gridspec[1:8, 1:2])
    ax_right = subplot(gridspec[1:8, 8:9])

    ax_top.axis('off')
    ax_bottom.axis('off')
    ax_left.axis('off')
    ax_right.axis('off')

    if not cmap:
        if data_type == 'continuous':
            cmap = CMAP_CONTINUOUS
        elif data_type == 'categorical':
            cmap = CMAP_CATEGORICAL
        elif data_type == 'binary':
            cmap = CMAP_BINARY
        else:
            raise ValueError(
                'Target data type must be continuous, categorical, or binary.')

    heatmap(df,
            vmin=vmin,
            vmax=vmax,
            cmap=cmap,
            center=center,
            robust=robust,
            annot=annot,
            fmt=fmt,
            annot_kws=annot_kws,
            linewidths=linewidths,
            linecolor=linecolor,
            cbar=cbar,
            cbar_kws=cbar_kws,
            cbar_ax=cbar_ax,
            square=square,
            ax=ax_center,
            xticklabels=xticklabels,
            yticklabels=yticklabels,
            mask=mask,
            **kwargs)

    # Get values for making legend
    values = unique(df.values)
    values = values[~isnull(values)]
    if data_type == 'continuous':  # Plot colorbar
        # Get not-nan values for computing min, mean, & max
        min_ = values.min()
        mean_ = values.mean()
        max_ = values.max()
        cax, kw = make_axes(ax_bottom,
                            location='bottom',
                            fraction=0.16,
                            cmap=cmap,
                            norm=Normalize(min_, max_),
                            ticks=[min_, mean_, max_])
        ColorbarBase(cax, **kw)
        decorate(ax=cax, xtick_rotation=90)

    elif data_type in ('categorical', 'binary'):  # Plot category legends
        if len(values) < 30:
            horizontal_span = ax_center.axis()[1]
            vertical_span = ax_center.axis()[3]

            colors = assign_colors_to_states(values, colors=cmap)

            columns = df.columns.tolist()
            if isinstance(columns[0], str):
                max_len_c = max([len(c) for c in columns])
            else:
                max_len_c = 10
            vertical_offset = 0.016 * max_len_c

            for i, v in enumerate(values):
                x = (horizontal_span / len(values) / 2) + \
                    i * horizontal_span / len(values)
                y = 0 - vertical_span * vertical_offset
                c = colors[v]
                ax_center.plot(x,
                               y,
                               'o',
                               color=c,
                               markersize=16,
                               aa=True,
                               clip_on=False)
                ax_center.text(x,
                               y - vertical_span * 0.05,
                               v,
                               horizontalalignment='center',
                               **FONT_STANDARD)

    decorate(title=title,
             xlabel=xlabel,
             ylabel=ylabel,
             xlabel_rotation=xlabel_rotation,
             ylabel_rotation=ylabel_rotation,
             xtick_rotation=xtick_rotation,
             ytick_rotation=ytick_rotation,
             ax=ax_center)

    if len(row_annotation):
        if len(set(row_annotation)) <= 2:
            cmap = CMAP_BINARY
        else:
            if len(annotation_colors):
                cmap = ListedColormap(annotation_colors)
            else:
                cmap = CMAP_CATEGORICAL
        heatmap(DataFrame(row_annotation),
                ax=ax_right,
                cbar=False,
                xticklabels=False,
                yticklabels=False,
                cmap=cmap)

    if len(column_annotation):
        if len(set(column_annotation)) <= 2:
            cmap = CMAP_BINARY
        else:
            if len(annotation_colors):
                cmap = ListedColormap(annotation_colors)
            else:
                cmap = CMAP_CATEGORICAL
        heatmap(DataFrame(column_annotation).T,
                ax=ax_top,
                cbar=False,
                xticklabels=False,
                yticklabels=False,
                annot=True,
                cmap=cmap)

    if filepath:
        save_plot(filepath, file_extension=file_extension, dpi=dpi)
            time_hrs,
            results[theta][var],
            color=str(lightest_grey - theta * lightest_grey),
        )

    # Shrink margins
    ax.set_ylim((90, 310) if var.startswith("Q") else (-2.5, 2))
    ax.set_ylabel(
        "Flow Rate [m³/s]" if var.startswith("Q") else "Water Level [m]")
    ax.set_xlabel("Time [hrs]")

    fig.tight_layout()

    # Output Plot
    plt.savefig(f"{var}.{file_type}")

# Generate a Bar Scale Legend
width = 4
height = 2
fig, axarr = plt.subplots(1, 5, figsize=(width, height))

for i, ax in enumerate(axarr):
    if i != 2:
        ax.set_axis_off()

cmap = ListedColormap(np.linspace(lightest_grey, 0.0, 256, dtype=str))
norm = Normalize(vmin=0.0, vmax=1.0)
cb = ColorbarBase(axarr[2], cmap=cmap, norm=norm, orientation="vertical")

plt.savefig(f"colorbar.{file_type}")
# 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()
Exemple #37
0
def calendarplot(
    data,
    how="sum",
    yearlabels=True,
    yearascending=True,
    yearlabel_kws=None,
    subplot_kws=None,
    gridspec_kws=None,
    fig_kws=None,
    fig_suptitle=None,
    vmin=0,
    vmax=16,
    cmap="YlGn",
    **kwargs
):
    """
    Plot a timeseries as a calendar heatmap.

    Parameters
    ----------
    data : Series
        Data for the plot. Must be indexed by a DatetimeIndex.
    how : string
        Method for resampling data by day. If `None`, assume data is already
        sampled by day and don't resample. Otherwise, this is passed to Pandas
        `Series.resample`.
    yearlabels : bool
       Whether or not to draw the year for each subplot.
    yearascending : bool
       Sort the calendar in ascending or descending order.
    yearlabel_kws : dict
       Keyword arguments passed to the matplotlib `set_ylabel` call which is
       used to draw the year for each subplot.
    subplot_kws : dict
        Keyword arguments passed to the matplotlib `add_subplot` call used to
        create each subplot.
    gridspec_kws : dict
        Keyword arguments passed to the matplotlib `GridSpec` constructor used
        to create the grid the subplots are placed on.
    fig_kws : dict
        Keyword arguments passed to the matplotlib `figure` call.
    vmin, vmax : floats
        Values to anchor the colormap. If `None`, min and max are used after
        resampling data by day.
    kwargs : other keyword arguments
        All other keyword arguments are passed to `yearplot`.

    Returns
    -------
    fig, axes : matplotlib Figure and Axes
        Tuple where `fig` is the matplotlib Figure object `axes` is an array
        of matplotlib Axes objects with the calendar heatmaps, one per year.

    Examples
    --------

    With `calendarplot` we can plot several years in one figure:

    .. plot::
        :context: close-figs

        calmap.calendarplot(events)

    """
    yearlabel_kws = yearlabel_kws or {}
    subplot_kws = subplot_kws or {}
    gridspec_kws = gridspec_kws or {}
    fig_kws = fig_kws or {}

    years = np.unique(data.index.year)
    if not yearascending:
        years = years[::-1]
    if gridspec_kws == {}:
        gridspec_kws = {'height_ratios': [5]*len(years)+[1]}

    fig, axes = plt.subplots(
        nrows=len(years)+1,
        ncols=1,
        squeeze=False,
        subplot_kw=subplot_kws,
        gridspec_kw=gridspec_kws,
        **fig_kws
    )
    axes = axes.T[0]
    plt.suptitle(fig_suptitle)
    # We explicitely resample by day only once. This is an optimization.
    if how is None:
        by_day = data
    else:
        if _pandas_18:
            by_day = data.resample("D").agg(how)
        else:
            by_day = data.resample("D", how=how)

    ylabel_kws = dict(
        fontsize=32,
        color=kwargs.get("fillcolor", "silver"),
        fontweight="bold",
        fontname="Arial",
        ha="center",
    )
    ylabel_kws.update(yearlabel_kws)

    max_weeks = 0

    for year, ax in zip(years, axes[:-1]):
        yearplot(by_day, year=year, how=None, ax=ax, cmap=cmap, vmin=vmin, vmax=vmax, **kwargs)
        max_weeks = max(max_weeks, ax.get_xlim()[1])

        if yearlabels:
            ax.set_ylabel(str(year), **ylabel_kws)

    # In a leap year it might happen that we have 54 weeks (e.g., 2012).
    # Here we make sure the width is consistent over all years.
    for ax in axes:
        ax.set_xlim(0, max_weeks)
    cmap = plt.get_cmap(cmap)
    bounds = range(vmin, vmax +1)
    norm = BoundaryNorm(bounds, cmap.N, extend='both')

    cb1 = ColorbarBase(axes[-1],
                       cmap=cmap,
                       norm=norm,
                       orientation='horizontal',
                       ticks=range(vmin, vmax + 1))
    cb1.set_label('CTimer clocks')

    # Make the axes look good.
    plt.tight_layout()

    return fig, axes
Exemple #38
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",
              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:
        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)
Exemple #39
0
def setup_axes(fig, cmap, norm):
    ax = fig.add_axes([0.92, 0.12, 0.04, 0.35])
    cbar = ColorbarBase(ax, cmap=cmap, norm=norm, orientation='vertical', drawedges=False)
    cbar.ax.tick_params(labelsize=8)
    return ax, cbar
Exemple #40
0
    for i in range(nrows):
        for j in range(ncols):
            axis = ax[i][j]
            axis.tick_params(labelbottom='off', labelleft='off')
            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,
#!/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()
Exemple #42
0
class WidgetPlot(FigureCanvas):
    def __init__(self, parent=None):
        FigureCanvas.__init__(self, Figure())

        self._telemetry = None
        self._resolution = None
        self._cmap = None
        self._wireframe = False

        self.setParent(parent)

        self.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.setFocus()

        colour = self.palette().color(self.backgroundRole()).getRgbF()
        self.figure.patch.set_facecolor(colour[:-1])

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

        self._axes = self.figure.add_subplot(gs[0], projection='3d')
        self._axes.set_title('3D Plot')
        self._axes.set_xlabel('Longitude')
        self._axes.set_ylabel('Latitude')
        self._axes.set_zlabel('Level (dB)')
        self._axes.tick_params(axis='both', which='major', labelsize='smaller')
        self._axes.grid(True)
        formatMaj = ScalarFormatter(useOffset=False)
        self._axes.xaxis.set_major_formatter(formatMaj)
        self._axes.yaxis.set_major_formatter(formatMaj)
        self._axes.zaxis.set_major_formatter(formatMaj)
        formatMinor = AutoMinorLocator(10)
        self._axes.xaxis.set_minor_locator(formatMinor)
        self._axes.yaxis.set_minor_locator(formatMinor)
        self._axes.zaxis.set_minor_locator(formatMinor)

        self._axesBar = self.figure.add_subplot(gs[1])
        self._axesBar.tick_params(axis='both',
                                  which='major',
                                  labelsize='smaller')
        self._bar = ColorbarBase(self._axesBar)

        if matplotlib.__version__ >= '1.2':
            self.figure.tight_layout()

    def set(self, telemetry):
        self._telemetry = telemetry

    def set_cmap(self, cmap):
        self._cmap = cmap

    def set_resolution(self, res):
        self._resolution = res

    def set_wireframe(self, wireframe):
        self._wireframe = wireframe

    def plot(self):
        self.clear()

        x, y, z = unique_locations(self._telemetry)

        east = max(x)
        west = min(x)
        north = max(y)
        south = min(y)

        width = east - west
        height = north - south

        if width != 0 and height != 0:
            xi = numpy.linspace(west, east, self._resolution)
            yi = numpy.linspace(south, north, self._resolution)
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                xSurf, ySurf = numpy.meshgrid(xi, yi)
                zSurf = mlab.griddata(x, y, z, xi=xi, yi=yi)

            vmin = numpy.min(zSurf)
            vmax = numpy.max(zSurf)
            zSurf[numpy.where(numpy.ma.getmask(zSurf) == True)] = vmin
            zSurf.mask = False

            if self._wireframe:
                self._axes.plot_wireframe(xSurf,
                                          ySurf,
                                          zSurf,
                                          linewidth=0.5,
                                          gid='plot')
                self._axesBar.set_visible(False)
            else:
                self._axes.plot_surface(xSurf,
                                        ySurf,
                                        zSurf,
                                        vmin=vmin,
                                        vmax=vmax,
                                        rstride=1,
                                        cstride=1,
                                        linewidth=0.1,
                                        cmap=self._cmap,
                                        gid='plot')
                self._bar.set_cmap(self._cmap)
                self._bar.set_clim(vmin, vmax)
                self._axesBar.set_ylim(vmin, vmax)
                self._axesBar.set_visible(True)

        self.draw()

    def clear(self):
        children = self._axes.get_children()
        for child in children:
            gid = child.get_gid()
            if gid is not None and gid == 'plot':
                child.remove()
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
AK_OFFSET_X = -250000   # X offset for Alaska (These four values are obtained
AK_OFFSET_Y = -750000   # via manual trial and error, thus changing them is not recommended.)

for nshape, shapedict in enumerate(m_.states_info):  # plot Alaska and Hawaii as map insets
    if shapedict['NAME'] in ['Alaska', 'Hawaii']:
        seg = m_.states[int(shapedict['SHAPENUM'] - 1)]
        if shapedict['NAME'] == 'Hawaii' and float(shapedict['AREA']) > AREA_1:
            seg = [(x + HI_OFFSET_X, y + HI_OFFSET_Y) for x, y in seg]
            color = rgb2hex(colors[statenames[nshape]])
        elif shapedict['NAME'] == 'Alaska' and float(shapedict['AREA']) > AREA_2:
            seg = [(x*AK_SCALE + AK_OFFSET_X, y*AK_SCALE + AK_OFFSET_Y)\
                   for x, y in seg]
            color = rgb2hex(colors[statenames[nshape]])
        poly = Polygon(seg, facecolor=color, edgecolor='gray', linewidth=.45)
        ax.add_patch(poly)

ax.set_title('Number of electors')

#%% ---------  Plot bounding boxes for Alaska and Hawaii insets  --------------
light_gray = [0.8]*3  # define light gray color RGB
x1,y1 = m_([-190,-183,-180,-180,-175,-171,-171],[29,29,26,26,26,22,20])
x2,y2 = m_([-180,-180,-177],[26,23,20])  # these numbers are fine-tuned manually
m_.plot(x1,y1,color=light_gray,linewidth=0.8)  # do not change them drastically
m_.plot(x2,y2,color=light_gray,linewidth=0.8)

#%% ---------   Show color bar  ---------------------------------------
ax_c = fig.add_axes([0.9, 0.1, 0.03, 0.8])
cb = ColorbarBase(ax_c,cmap=cmap,norm=norm,orientation='vertical',
                  label=r'[population per $\mathregular{km^2}$]')

plt.show()
Exemple #45
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
Exemple #46
0
    def corr_plot(x_cof,
                  x_name=None,
                  left_down="circle",
                  right_top="pie",
                  threshold_left=0.0,
                  threshold_right=0.0,
                  title=None,
                  label_axis="off",
                  front_raito=1):
        """
        相关系数图,比较耗时,不要超过25个特征。

        Examples
        -----------
        >>> data = load_boston(return_X_y=False)
        >>> name0 = data["feature_names"]
        >>> x = data["data"]
        >>> ys = data["target"]
        >>> x_cof = np.corrcoef(x.T)
        >>> #plot
        >>> plt = corr_plot(x_cof, name0, left_down="circle", right_top="text", threshold_right=0.7, label_axis="off")
        >>> plt.show()

        Parameters
        ----------
        x_cof:np.ndarray
            correlation coefficient matrix
        x_name:list,None
            feature names
        left_down:None,"pie","fill","text","circle"
            type for left_down
        right_top:None,"pie","fill","text","circle"
            type for right_top
        threshold_left:float
            threshold for show.
        threshold_right:float
            threshold for show.
        title:str
            picture title
        label_axis:"left","right","off"
            label_axis
        front_raito:float
            front scare for show
        """
        assert x_cof.shape[0] == x_cof.shape[1]

        x_cof = np.round(x_cof, 2)
        if x_name is None:
            name = ["$x_{{{i}}}$".format(i=i) for i in range(x_cof.shape[1])]

        size = x_cof
        or_size = np.nan_to_num((abs(size) / size) * (1 - abs(size)))

        n = size.shape[0]
        explode = (0, 0)
        gs = gridspec.GridSpec(n, n)
        gs.update(wspace=0, hspace=0)

        cmap = plt.get_cmap("bwr")  # args
        fill_colors = cmap(size / 2 + 0.5)  # args

        fig = plt.figure(figsize=(12, 12), frameon=True)  # args

        title_fontsize = round(22 * front_raito)  # c_args
        ax_fontsize = round(22 * front_raito)
        score_fontsize = round(16 * front_raito)
        circle_size = round(600 * front_raito)

        fig.text(0.5,
                 0.05,
                 title,
                 fontsize=title_fontsize,
                 horizontalalignment='center',
                 verticalalignment='center')  # zou, xia

        for i, j in product(range(n), range(n)):
            if j < i and abs(size[i, j]) >= threshold_left:
                types = left_down
            elif j > i and abs(size[i, j]) >= threshold_right:
                types = right_top
            else:
                types = None

            if types == "pie":
                ax = plt.subplot(gs[i, j])
                ax.pie(
                    (abs(size[i, j]), abs(or_size[i, j])),
                    explode=explode,
                    labels=None,
                    autopct=None,
                    shadow=False,
                    startangle=90,
                    colors=[fill_colors[i, j], 'w'],
                    wedgeprops=dict(width=1, edgecolor='black', linewidth=0.5),
                    counterclock=False,
                    frame=False,
                    center=(0, 0),
                )
                ax.set_xlim(-1, 1)
                ax.axis('equal')

            elif types == "fill":
                ax = plt.subplot(gs[i, j])
                ax.set_facecolor(fill_colors[i, j])
                [
                    ax.spines[_].set_color('w')
                    for _ in ['right', 'top', 'left', 'bottom']
                ]

                ax.set_xticks([])
                ax.set_yticks([])

            elif types == "fillandtext":
                ax = plt.subplot(gs[i, j])
                ax.set_facecolor(fill_colors[i, j])
                [
                    ax.spines[_].set_color('w')
                    for _ in ['right', 'top', 'left', 'bottom']
                ]

                ax.text(
                    0.5,
                    0.5,
                    size[i, j],
                    fontdict={"color": "black"},  # args
                    fontsize=score_fontsize,  # c_arg
                    horizontalalignment='center',
                    verticalalignment='center')
            elif types == "text":
                ax = plt.subplot(gs[i, j])
                ax.text(
                    0.5,
                    0.5,
                    size[i, j],
                    fontdict={"color": "b"},  # args
                    fontsize=score_fontsize,  # c_arg
                    horizontalalignment='center',
                    verticalalignment='center')
                ax.set_xticks([])
                ax.set_yticks([])
                # plt.axis('off')
            elif types == "circle":
                ax = plt.subplot(gs[i, j])
                ax.axis('equal')
                ax.set_xlim(-1, 1)
                ax.scatter(0,
                           0,
                           color=fill_colors[i, j],
                           s=circle_size * abs(size[i, j])**2)
                ax.set_xticks([])

                ax.set_yticks([])
                # plt.axis('off')

            else:
                pass

        for k in range(n):
            ax = plt.subplot(gs[k, k])

            # ax.axis('equal')
            # ax.set_xlim(-1, 1)
            # ax.scatter(0, 0, color=fill_colors[k, k], s=circle_size * abs(size[k, k]))
            # ax.set_xticks([])
            #
            # ax.set_yticks([])

            ax.text(0.5,
                    0.5,
                    name[k],
                    fontsize=ax_fontsize,
                    horizontalalignment='center',
                    verticalalignment='center')
            ax.set_xticks([])
            ax.set_yticks([])
            if label_axis == "left":
                color = ["w", "w", "b", "b"]
                [
                    ax.spines[i].set_color(j)
                    for i, j in zip(['right', 'top', 'left', 'bottom'], color)
                ]
            elif label_axis == "right":
                color = ["b", "b", "w", "w"]
                [
                    ax.spines[i].set_color(j)
                    for i, j in zip(['right', 'top', 'left', 'bottom'], color)
                ]
            else:
                plt.axis('off')

        @pyplot.FuncFormatter
        def fake_(x, pos):
            return round(2 * (x - 0.5), 1)

        fig.subplots_adjust(right=0.80)
        cbar_ax = fig.add_axes([0.85, 0.125, 0.03, 0.75])
        ColorbarBase(cbar_ax,
                     cmap=cmap,
                     ticks=[0, 0.25, 0.5, 0.75, 1],
                     format=fake_)
        fig.set_size_inches(9, 8.5, forward=True)
        return plt
Exemple #47
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()
Exemple #48
0
def change_cbar_text(cbar:ColorbarBase, tick:list, text:list):
    cbar.set_ticks(tick)
    cbar.set_ticklabels(text)
Exemple #49
0
    def plot(self, figname=None, db=True, **kwargs):
        """ Plot the HEALPix :attr:`~nenupy.astro.hpxsky.HpxSky.skymap`
            on an equatorial grid with a Elliptical frame.

            :param figname:
                Figure name, if ``None`` (default value), the
                figure is not saved.
            :type figname: `str`
            :param db:
                Sacle the data in decibel units. Default is
                ``True``.
            :type db: `bool`
            :param cmap:
                Name of the colormap. Default is ``'YlGnBu_r'``.
            :type cmap: `str`
            :param vmin:
                Minimum value to scale the figure. Default is
                min(:attr:`~nenupy.astro.hpxsky.HpxSky.skymap`).
            :type vmin: `float`
            :param vmax:
                Maximum value to scale the figure. Default is
                max(:attr:`~nenupy.astro.hpxsky.HpxSky.skymap`).
            :type vmax: `float`
            :param tickscol:
                Color of the RA ticks. Default is ``'black'``.
            :type tickscol: `str`
            :param title:
                Title of the plot. Default is ``None``.
            :type title: `str`
            :param cblabel:
                Colorbar label. Default is ``'Amp'`` if ``db=False``
                of ``'dB'`` if ``db=True``.
            :type cblabel: `str`
            :param grid:
                Show the equatorial grid.
            :type grid: `bool`
            :param cbar:
                Plot a colorbar.
            :type cbar: `bool`
            :param center:
                Center of the plot. Default is
                ``SkyCoord(0.*u.deg, 0.*u.deg)``.
            :type center: :class:`~astropy.coordinates.SkyCoord`
            :param size:
                Diameter of the cutout. Default is whole sky.
            :type size: `float` or :class:`~astropy.units.Quantity`
            :param figsize:
                Figure size in inches. Default is ``(15, 10)``.
            :type figsize: `tuple`
            :param indices:
                Default is ``None``. If not, a scatter plot is
                made on the desired HEALPix indices:
                ``(indices, size, color)``.
            :type indices: `tuple`
            :param scatter:
                Default is ``None``. If not, a scatter plot is
                made on the desired equatorial coordinates:
                ``(ra (deg), dec (deg), size, color)``.
            :type scatter: `tuple`
            :param text:
                Default is ``None``. If not, text is overplotted
                on the desired equatorial coordinates:
                ``(ra (deg), dec (deg), text, color)``.
            :type text: `tuple`
            :param curve:
                Default is ``None``. If not, a curve plot is
                made on the desired equatorial coordinates:
                ``(ra (deg), dec (deg), linestyle, color)``.
            :type curve: `tuple`

        """
        # Lot of imports for this one...
        from reproject import reproject_from_healpix
        from astropy.coordinates import ICRS
        from astropy.visualization.wcsaxes.frame import EllipticalFrame
        import matplotlib.pyplot as plt
        from matplotlib.colorbar import ColorbarBase
        from matplotlib.ticker import LinearLocator
        from matplotlib.colors import Normalize
        from matplotlib.cm import get_cmap
        from mpl_toolkits.axes_grid1.inset_locator import inset_axes

        # Cutout?
        raauto = True
        if 'center' not in kwargs.keys():
            kwargs['center'] = SkyCoord(0. * u.deg, 0. * u.deg)
        if not isinstance(kwargs['center'], SkyCoord):
            raise TypeError('center must be a SkyCoord object.')

        # Preparing WCS projection
        dangle = 0.675
        scale = int(dangle / self.resolution.deg)
        scale = 1 if scale <= 1 else scale
        nra = 480 * scale
        ndec = 240 * scale
        if 'size' in kwargs.keys():
            if isinstance(kwargs['size'], u.Quantity):
                kwargs['size'] = kwargs['size'].to(u.deg).value
            resol = dangle / scale
            nra = int(kwargs['size'] / resol)
            ndec = nra
            raauto = False

        wcs = WCS(naxis=2)
        wcs.wcs.crpix = [nra / 2 + 0.5, ndec / 2 + 0.5]
        wcs.wcs.cdelt = np.array([-dangle / scale, dangle / scale])
        wcs.wcs.crval = [kwargs['center'].ra.deg, kwargs['center'].dec.deg]
        wcs.wcs.ctype = ['RA---AIT', 'DEC--AIT']

        # Make an array out of HEALPix representation
        skymap = self.skymap.copy()
        if self.visible_sky:
            skymap[~self._is_visible] = np.nan
        array, fp = reproject_from_healpix((skymap, ICRS()),
                                           wcs,
                                           nested=False,
                                           shape_out=(ndec, nra))

        # Decibel or linear?
        if db:
            data = 10 * np.log10(array)
            cblabel = 'dB'
        else:
            data = array
            cblabel = 'Amp'
        mask = ~np.isnan(data) * ~np.isinf(data)

        # Make sure everything is correctly set up
        if 'cmap' not in kwargs.keys():
            kwargs['cmap'] = 'YlGnBu_r'
        if 'vmin' not in kwargs.keys():
            kwargs['vmin'] = np.min(data[mask])
        elif kwargs['vmin'] is None:
            kwargs['vmin'] = np.min(data[mask])
        else:
            pass
        if 'vmax' not in kwargs.keys():
            kwargs['vmax'] = np.max(data[mask])
        elif kwargs['vmax'] is None:
            kwargs['vmax'] = np.max(data[mask])
        else:
            pass
        if 'tickscol' not in kwargs.keys():
            kwargs['tickscol'] = 'black'
        if 'title' not in kwargs.keys():
            kwargs['title'] = None
        if 'cblabel' not in kwargs.keys():
            kwargs['cblabel'] = cblabel
        if 'grid' not in kwargs.keys():
            kwargs['grid'] = True
        if 'cbar' not in kwargs.keys():
            kwargs['cbar'] = True
        if 'figsize' not in kwargs.keys():
            kwargs['figsize'] = (15, 10)
        if 'indices' not in kwargs.keys():
            kwargs['indices'] = None
        if 'scatter' not in kwargs.keys():
            kwargs['scatter'] = None
        if 'curve' not in kwargs.keys():
            kwargs['curve'] = None
        if 'text' not in kwargs.keys():
            kwargs['text'] = None

        # Initialize figure
        fig = plt.figure(figsize=kwargs['figsize'])
        ax = plt.subplot(projection=wcs, frame_class=EllipticalFrame)

        # Full sky
        im = ax.imshow(data,
                       origin='lower',
                       interpolation='none',
                       cmap=kwargs['cmap'],
                       vmin=kwargs['vmin'],
                       vmax=kwargs['vmax'])
        axra = ax.coords[0]
        axdec = ax.coords[1]
        if kwargs['grid']:
            ax.coords.grid(color=kwargs['tickscol'], alpha=0.5)
            axra.set_ticks_visible(False)
            axra.set_ticklabel(color=kwargs['tickscol'])
            axra.set_axislabel('RA', color=kwargs['tickscol'])
            axra.set_major_formatter('d')
            if raauto:
                axra.set_ticks([0, 45, 90, 135, 225, 270, 315] * u.degree)
            else:
                axra.set_ticks(number=10)
            axdec.set_ticks_visible(False)
            axdec.set_axislabel('Dec')
            axdec.set_major_formatter('d')
            axdec.set_ticks(number=10)
        else:
            axra.set_ticks_visible(False)
            axdec.set_ticks_visible(False)
            axra.set_ticklabel_visible(False)
            axdec.set_ticklabel_visible(False)

        # Overplot
        if kwargs['indices'] is not None:
            ax.scatter(x=self.eq_coords[kwargs['indices'][0]].ra.deg,
                       y=self.eq_coords[kwargs['indices'][0]].dec.deg,
                       s=[kwargs['indices'][1]] * len(kwargs['indices'][0]),
                       color=kwargs['indices'][2],
                       transform=ax.get_transform('world'))
        if kwargs['scatter'] is not None:
            ax.scatter(x=kwargs['scatter'][0],
                       y=kwargs['scatter'][1],
                       s=[kwargs['scatter'][2]] * len(kwargs['scatter'][0]),
                       color=kwargs['scatter'][3],
                       transform=ax.get_transform('world'))
        if kwargs['curve'] is not None:
            ax.plot(kwargs['curve'][0],
                    kwargs['curve'][1],
                    linestyle=kwargs['curve'][2],
                    color=kwargs['curve'][3],
                    transform=ax.get_transform('world'))
        if kwargs['text'] is not None:
            for i in range(len(kwargs['text'][0])):
                ax.text(x=kwargs['text'][0][i],
                        y=kwargs['text'][1][i],
                        s=kwargs['text'][2][i],
                        color=kwargs['text'][3],
                        transform=ax.get_transform('world'))

        im.set_clip_path(ax.coords.frame.patch)
        ax.set_title(kwargs['title'], pad=25)

        # Colorbar
        if kwargs['cbar']:
            cax = inset_axes(
                ax,
                width='3%',
                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=kwargs['cmap']),
                              orientation='vertical',
                              norm=Normalize(vmin=kwargs['vmin'],
                                             vmax=kwargs['vmax']),
                              ticks=LinearLocator())
            cb.solids.set_edgecolor('face')
            cb.set_label(kwargs['cblabel'])
            cb.formatter.set_powerlimits((0, 0))

        # Save or show
        if figname is None:
            plt.show()
        elif figname.lower() == 'return':
            return fig, ax
        else:
            fig.savefig(figname,
                        dpi=300,
                        transparent=True,
                        bbox_inches='tight')
        plt.close('all')
        return
Exemple #50
0
def display_forces(simulation_folder, lower_percentile=97.5, upper_percentile=99, save_plot = True, arrow_factor=5):
    """
    show the force density field of the masked force components
    
    simulation_folder: path to simulation folder
    lower_percentile and upper_percentile give range of forces 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
    """    
     # load in forces and coordinates
    r =  np.genfromtxt(os.path.join(simulation_folder, "R.dat"))       # positions
    f =  np.genfromtxt(os.path.join(simulation_folder, "Fden.dat"))     # force densities  
    fabs = np.sqrt(np.sum(f ** 2., axis=1))   # absolute values for filtering    

    # filter 
    mask = (fabs > np.percentile(fabs, lower_percentile)) & (fabs < np.percentile(fabs, upper_percentile))
    r2 = r[mask]
    f2 = f[mask]
    fabs2 = fabs[mask]

    # Force
    fig2 = plt.figure()
    ax2 = fig2.gca(projection='3d', label='fitted-forces', rasterized=True)
    color_bounds2 = np.array([np.percentile(fabs2, 0.1), np.percentile(fabs2, 99.9)]) * 10 ** -6


    for r2i, f2i, fabs2i in tqdm(zip(r2 * 10 ** 6, f2 * 10 ** -6, fabs2 * (10 ** -6))):  #*f_scale
        color = plt.cm.hot(((fabs2i - color_bounds2[0]) / (color_bounds2[1] - color_bounds2[0])))
        # alpha = 1. - (r2i[0] - r2i[1]) / (270. * 1.25)
        # if alpha > 1:
        #     alpha = 1.
        alpha = 1.        
        ax2.quiver(r2i[0], r2i[1], r2i[2], f2i[0], f2i[1], f2i[2], length=fabs2i * arrow_factor ,
                    color=color, arrow_length_ratio=0, alpha=alpha, pivot='tip', linewidth=0.5)
    
    # plot colorbar   ---------------------------------------------------------
    cbaxes = fig2.add_axes([0.15, 0.1, 0.125, 0.010])
    cmap = plt.cm.hot
    norm = plt.Normalize(vmin=color_bounds2[0], vmax=color_bounds2[1])
    cb1 = ColorbarBase(cbaxes, cmap=cmap, norm=norm, orientation='horizontal')
    cb1.set_label('Force Den. [pN/µm³]')
    tick_locator = ticker.MaxNLocator(nbins=3)
    cb1.locator = tick_locator
    cb1.update_ticks()
    # -------------------------------------------------------------------------
    #ax2.set_xlim([-150, 150])   can be used to make an individual plot
    #ax2.set_ylim([-150, 150])
    #ax2.set_zlim([-150, 150])
    #ax2.set_xticks([-100, -50, 0, 50, 100])
    #ax2.set_yticks([-100, -50, 0, 50, 100])
    #ax2.set_zticks([-100, -50, 0, 50, 100])
    # ax2.set_xticklabels(['']*5)
    # ax2.set_yticklabels(['']*5)
    # ax2.set_zticklabels(['']*5)
    ax2.w_xaxis.set_pane_color((0.2, 0.2, 0.2, 1.0))
    ax2.w_yaxis.set_pane_color((0.2, 0.2, 0.2, 1.0))
    ax2.w_zaxis.set_pane_color((0.2, 0.2, 0.2, 1.0))

    if save_plot:
     plt.savefig( os.path.join(simulation_folder,'force_density_plot_lower_{}_upper_{}.png'.format(lower_percentile, upper_percentile)), dpi=500 , bbox_inches="tight", pad_inches=0)
  
    return
class Plotter(object):
    def __init__(self, notify, figure, settings):
        self.notify = notify
        self.figure = figure
        self.settings = settings
        self.colourMap = self.settings.colourMap
        self.axes = None
        self.bar = None
        self.barBase = None
        self.threadPlot = None
        self.extent = None
        self.lines = {}
        self.labels = {}
        self.overflowLabels = {}
        self.overflow = {'left': [],
                         'right': [],
                         'top': [],
                         'bottom': []}

        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 ($\mathsf{dB/\sqrt{Hz}}$)')
        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)
        self.set_colourmap_use(self.settings.colourMapUse)

        self.__setup_measure()
        self.__setup_overflow()
        self.hide_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.lines[Markers.MIN] = Line2D([0, 0], [0, 0], linestyle='--',
                                         color='black')
        self.lines[Markers.MAX] = Line2D([0, 0], [0, 0], linestyle='-.',
                                         color='black')
        self.lines[Markers.AVG] = Line2D([0, 0], [0, 0], dashes=dashesAvg,
                                         color='magenta')
        self.lines[Markers.GMEAN] = Line2D([0, 0], [0, 0], dashes=dashesGM,
                                           color='green')
        self.lines[Markers.HP] = Line2D([0, 0], [0, 0], dashes=dashesHalf,
                                        color='purple')
        self.lines[Markers.HFS] = Line2D([0, 0], [0, 0], dashes=dashesHalf,
                                         color='purple')
        self.lines[Markers.HFE] = Line2D([0, 0], [0, 0], dashes=dashesHalf,
                                         color='purple')
        self.lines[Markers.OP] = Line2D([0, 0], [0, 0], dashes=dashesHalf,
                                        color='#996600')
        self.lines[Markers.OFS] = Line2D([0, 0], [0, 0], dashes=dashesHalf,
                                         color='#996600')
        self.lines[Markers.OFE] = 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.lines[Markers.MIN].set_path_effects([effect])
            self.lines[Markers.MAX].set_path_effects([effect])
            self.lines[Markers.AVG].set_path_effects([effect])
            self.lines[Markers.GMEAN].set_path_effects([effect])
            self.lines[Markers.HP].set_path_effects([effect])
            self.lines[Markers.HFS].set_path_effects([effect])
            self.lines[Markers.HFE].set_path_effects([effect])
            self.lines[Markers.OP].set_path_effects([effect])
            self.lines[Markers.OFS].set_path_effects([effect])
            self.lines[Markers.OFE].set_path_effects([effect])

        for line in self.lines.itervalues():
            self.axes.add_line(line)

        bbox = self.axes.bbox
        box = dict(boxstyle='round', fc='white', ec='black', clip_box=bbox)
        self.labels[Markers.MIN] = Text(0, 0, 'Min', fontsize='xx-small',
                                        ha="right", va="bottom", bbox=box,
                                        color='black')
        self.labels[Markers.MAX] = Text(0, 0, 'Max', fontsize='xx-small',
                                        ha="right", va="top", bbox=box,
                                        color='black')
        box['ec'] = 'magenta'
        self.labels[Markers.AVG] = Text(0, 0, 'Mean', fontsize='xx-small',
                                        ha="right", va="center", bbox=box,
                                        color='magenta')
        box['ec'] = 'green'
        self.labels[Markers.GMEAN] = Text(0, 0, 'GMean', fontsize='xx-small',
                                          ha="right", va="center", bbox=box,
                                          color='green')
        box['ec'] = 'purple'
        self.labels[Markers.HP] = Text(0, 0, '-3dB', fontsize='xx-small',
                                       ha="right", va="center", bbox=box,
                                       color='purple')
        self.labels[Markers.HFS] = Text(0, 0, '-3dB Start', fontsize='xx-small',
                                        ha="center", va="top", bbox=box,
                                        color='purple')
        self.labels[Markers.HFE] = Text(0, 0, '-3dB End', fontsize='xx-small',
                                        ha="center", va="top", bbox=box,
                                        color='purple')
        box['ec'] = '#996600'
        self.labels[Markers.OP] = Text(0, 0, 'OBW', fontsize='xx-small',
                                       ha="right", va="center", bbox=box,
                                       color='#996600')
        self.labels[Markers.OFS] = Text(0, 0, 'OBW Start', fontsize='xx-small',
                                        ha="center", va="top", bbox=box,
                                        color='#996600')
        self.labels[Markers.OFE] = Text(0, 0, 'OBW End', fontsize='xx-small',
                                        ha="center", va="top", bbox=box,
                                        color='#996600')

        for label in self.labels.itervalues():
            self.axes.add_artist(label)

    def __setup_overflow(self):
        bbox = self.axes.bbox
        box = dict(boxstyle='round', fc='white', ec='black', alpha=0.5,
                   clip_box=bbox)
        self.overflowLabels['left'] = Text(0, 0.9, '', fontsize='xx-small',
                                           ha="left", va="top", bbox=box,
                                           transform=self.axes.transAxes,
                                           alpha=0.5)
        self.overflowLabels['right'] = Text(1, 0.9, '', fontsize='xx-small',
                                            ha="right", va="top", bbox=box,
                                            transform=self.axes.transAxes,
                                            alpha=0.5)
        self.overflowLabels['top'] = Text(0.9, 1, '', fontsize='xx-small',
                                          ha="right", va="top", bbox=box,
                                          transform=self.axes.transAxes,
                                          alpha=0.5)
        self.overflowLabels['bottom'] = Text(0.9, 0, '', fontsize='xx-small',
                                             ha="right", va="bottom", bbox=box,
                                             transform=self.axes.transAxes,
                                             alpha=0.5)

        for label in self.overflowLabels.itervalues():
            self.axes.add_artist(label)

    def __clear_overflow(self):
        for label in self.overflowLabels:
            self.overflow[label] = []

    def __draw_hline(self, marker, y):
        line = self.lines[marker]
        label = self.labels[marker]
        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)
        elif y is not None and y < yLim[0]:
            self.overflow['bottom'].append(marker)
        elif y is not None and y > yLim[1]:
            self.overflow['top'].append(marker)

    def __draw_vline(self, marker, x):
        line = self.lines[marker]
        label = self.labels[marker]
        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)
        elif x is not None and x < xLim[0]:
            self.overflow['left'].append(marker)
        elif x is not None and x > xLim[1]:
            self.overflow['right'].append(marker)

    def __draw_overflow(self):
        for pos, overflow in self.overflow.iteritems():
            if len(overflow) > 0:
                text = ''
                for measure in overflow:
                    if len(text) > 0:
                        text += '\n'
                    text += self.labels[measure].get_text()

                label = self.overflowLabels[pos]
                if pos == 'top':
                    textMath = '$\\blacktriangle$\n' + text
                elif pos == 'bottom':
                    textMath = '$\\blacktriangledown$\n' + text
                elif pos == 'left':
                    textMath = '$\\blacktriangleleft$\n' + text
                elif pos == 'right':
                    textMath = '$\\blacktriangleright$\n' + text

                label.set_text(textMath)
                label.set_visible(True)
                self.axes.draw_artist(label)

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

        self.hide_measure()
        self.__clear_overflow()

        if show[Measure.MIN]:
            y = measure.get_min_p()[1]
            self.__draw_hline(Markers.MIN, y)

        if show[Measure.MAX]:
            y = measure.get_max_p()[1]
            self.__draw_hline(Markers.MAX, y)

        if show[Measure.AVG]:
            y = measure.get_avg_p()
            self.__draw_hline(Markers.AVG, y)

        if show[Measure.GMEAN]:
            y = measure.get_gmean_p()
            self.__draw_hline(Markers.GMEAN, y)

        if show[Measure.HBW]:
            xStart, xEnd, y = measure.get_hpw()
            self.__draw_hline(Markers.HP, y)
            self.__draw_vline(Markers.HFS, xStart)
            self.__draw_vline(Markers.HFE, xEnd)

        if show[Measure.OBW]:
            xStart, xEnd, y = measure.get_obw()
            self.__draw_hline(Markers.OP, y)
            self.__draw_vline(Markers.OFE, xStart)
            self.__draw_vline(Markers.OFE, xEnd)

        self.__draw_overflow()

    def hide_measure(self):
        for line in self.lines.itervalues():
            line.set_visible(False)
        for label in self.labels.itervalues():
            label.set_visible(False)
        for label in self.overflowLabels.itervalues():
            label.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())
                if self.settings.plotFunc == PlotFunc.VAR and len(self.axes.collections) > 0:
                    norm = self.axes.collections[0].norm
                    self.barBase.set_clim((norm.vmin, norm.vmax))
                else:
                    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, EventThread(Event.DRAW))

    def get_axes(self):
        return self.axes

    def get_axes_bar(self):
        return self.barBase.ax

    def get_plot_thread(self):
        return self.threadPlot

    def set_title(self, title):
        self.axes.set_title(title, fontsize='medium')

    def set_plot(self, spectrum, extent, annotate=False):
        self.extent = extent
        self.threadPlot = ThreadPlot(self, self.settings,
                                     self.axes,
                                     spectrum,
                                     self.extent,
                                     self.barBase,
                                     annotate)
        self.threadPlot.start()

        return self.threadPlot

    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_bar(self, on):
        self.barBase.ax.set_visible(on)
        if on:
            self.axes.change_geometry(1, 2, 1)
            self.axes.get_subplotspec().get_gridspec().set_width_ratios([9.5, 0.5])
        else:
            self.axes.change_geometry(1, 1, 1)

        self.figure.subplots_adjust()

    def set_axes(self, on):
        if on:
            self.axes.set_axis_on()
            self.bar.set_axis_on()
        else:
            self.axes.set_axis_off()
            self.bar.set_axis_off()

    def set_colourmap_use(self, on):
        self.set_bar(on)
        if on:
            colourMap = self.settings.colourMap
        else:
            colourMap = ' Pure Blue'

        self.set_colourmap(colourMap)

    def set_colourmap(self, colourMap):
        self.colourMap = colourMap
        for collection in self.axes.collections:
            collection.set_cmap(colourMap)

        if colourMap.startswith(' Pure'):
            self.bar.set_visible(False)
        else:
            self.bar.set_visible(True)
        self.barBase.set_cmap(colourMap)
        try:
            self.barBase.draw_all()
        except:
            pass

    def close(self):
        self.figure.clear()
        self.figure = None
Exemple #52
0
    def plot(self, **kwargs):
        r""" Display the selected content of the :attr:`~nenupy.astro.sky.Sky.value`
            attribute belonging to a :class:`~nenupy.astro.sky.Sky` instance as
            a celestial map in equatorial coordinates.

            This method is available on a :class:`~nenupy.astro.sky.SkySlice` instance,
            resulting from a selection upon a :class:`~nenupy.astro.sky.Sky` instance
            (using the indexing operator).

            Several parameters, listed below, can be tuned to adapt the plot
            to the user requirements:

            .. rubric:: Data display keywords

            :param center:
                Coordinates of the celestial map to be displayed
                at the center of the image.
                Default is ``(RA=0deg, Dec=0deg)``.
            :type center:
                :class:`~astropy.coordinates.SkyCoord`
            :param radius:
                Angular radius from the center of the image above
                which the plot should be cropped.
                Default is ``None`` (i.e., full sky image).
            :type radius:
                :class:`~astropy.units.Quantity`
            :param resolution:
                Set the pixel resolution. The upper threshold is 0.775 deg,
                any value above that does not affect the figure appearence.
                Default is ``astropy.units.Quantity(1, unit="deg")``.
            :type resolution:
                :class:`~astropy.units.Quantity`
            :param only_visible:
                If set to ``True`` only the sky above the horizon is displayed.
                Setting this parameter to ``False`` does not really make sense
                for :class:`~nenupy.astro.sky.Sky` instances representing antenna
                response for instance.
                Default is ``True``.
            :type only_visible:
                `bool`
            :param decibel:
                If set to ``True``, the data values are displayed at the decibel scale,
                i.e., :math:`10 \log( \rm{data} )`. 
                Default is ``False``.
            :type decibel:
                `bool`

            .. rubric:: Overplot keywords

            :param scatter:
                Add a scatter plot (as defined in `matplotlib.pyplot.scatter`).
                Expected syntax is ``(<SkyCoord>, <marker_size>, <color>)``.
                Default is ``None`` (i.e., no scatter overplot).
            :type scatter:
                `tuple`
            :param text:
                Add a text overlay (as defined in `matplotlib.pyplot.text`).
                Expected syntax is ``(<SkyCoord>, <[text]>, <color>)``.
                Default is ``None`` (i.e., no text overplot).
            :type text:
                `tuple`
            :param contour:
                Add a contour plot (as defined in `matplotlib.pyplot.contour`).
                Expected syntax is ``(<numpy.ndarray>, <[levels]>, <colormap>)``.
                Default is ``None`` (i.e., no contour overplot).
            :type contour:
                `tuple`

            .. rubric:: Plotting layout keywords
            
            :param altaz_overlay:
                If set to ``True``, the horizontal coordinates grid is overplotted
                in addition to the equatorial one.
                Default is ``False``.
            :type altaz_overlay:
                `bool`
            :param cmap:
                Color map applied while representing the data (see 
                `Matplotlib colormaps <https://matplotlib.org/stable/gallery/color/colormap_reference.html>`_).
                Default is ``"YlGnBu_r"``.
            :type cmap:
                `str`
            :param show_colorbar:
                Show or not the color bar.
                Default is ``True``.
            :type show_colorbar:
                `bool`
            :param colorbar_label:
                Set the label of the color bar.
                Default is ``""``.
            :type colorbar_label:
                `str`
            :param figname:
                Name of the file (absolute or relative path) to save the figure.
                If set to ``"return"``, the method returns the `tuple` ``(fig, ax)``
                (as defined by `matplotlib <https://matplotlib.org/>`_).
                Default is ``None`` (i.e., only show the figure).
            :type figname:
                `str`
            :param figsize:
                Set the figure size.
                Default is ``(15, 10)``.
            :type figsize:
                `tuple`
            :param ticks_color:
                Set the color of the equatorial grid and the Right Ascension ticks.
                Default is ``"0.9"`` (grey).
            :type ticks_color:
                `str`
            :param title:
                Set the figure title.
                Default is ``"<time>, <frequency>"``.
            :type title:
                `str`
            
        """
        # Parsing the keyword arguments
        resolution = kwargs.get("resolution", 1*u.deg)
        figname = kwargs.get("figname", None)
        cmap = kwargs.get("cmap", "YlGnBu_r")
        figsize = kwargs.get("figsize", (15, 10))
        center = kwargs.get("center", SkyCoord(0*u.deg, 0*u.deg))
        radius = kwargs.get("radius", None)
        ticks_color = kwargs.get("ticks_color", "0.9")
        colorbar_label = kwargs.get("colorbar_label", "")
        title = kwargs.get("title", f"{self.time.isot.split('.')[0]}, {self.frequency:.2f}")
        visible_sky = kwargs.get("only_visible", True)
        decibel = kwargs.get("decibel", False)
        altaz_overlay = kwargs.get("altaz_overlay", False)

        # Initialize figure
        wcs, shape = self._compute_wcs(
            center=center,
            resolution=getattr(self, "resolution", resolution),
            radius=radius
        )
        fig = plt.figure(figsize=figsize)
        ax = plt.subplot(
            projection=wcs,
            frame_class=EllipticalFrame
        )

        # Get the data projected on fullsky
        data = self._fullsky_projection(
            wcs=wcs,
            shape=shape,
            display_visible_sky=visible_sky
        )

        # Scale the data in decibel
        if decibel:
            data = 10 * np.log10(data)

        vmin = kwargs.get("vmin", np.nanmin(data))
        vmax = kwargs.get("vmax", np.nanmax(data))

        # Plot the data
        im = ax.imshow(
            data,
            origin="lower",
            interpolation="quadric",
            cmap=cmap,
            vmin=vmin,
            vmax=vmax
        )

        # Define ax ticks
        ax.coords.grid(color=ticks_color, alpha=0.5)
        path_effects=[patheffects.withStroke(linewidth=3, foreground='black')]

        ra_axis = ax.coords[0]
        dec_axis = ax.coords[1]
        ra_axis.set_ticks_visible(False)
        ra_axis.set_ticklabel_visible(True)
        ra_axis.set_ticklabel(color=ticks_color, exclude_overlapping=True, path_effects=path_effects)
        ra_axis.set_axislabel("RA", color=ticks_color, path_effects=path_effects)
        ra_axis.set_major_formatter("d")
        
        ra_axis.set_ticks(number=12)
        dec_axis.set_ticks_visible(False)
        dec_axis.set_ticklabel_visible(True)
        dec_axis.set_axislabel("Dec", minpad=2)
        dec_axis.set_major_formatter("d")
        dec_axis.set_ticks(number=10)

        if altaz_overlay:
            frame = AltAz(obstime=self.time, location=self.observer)
            overlay = ax.get_coords_overlay(frame)
            overlay.grid(color="tab:orange", alpha=0.5)
            az_axis = overlay[0]
            alt_axis = overlay[1]
            az_axis.set_axislabel("Azimuth", color=ticks_color, path_effects=path_effects)
            az_axis.set_ticks_visible(False)
            az_axis.set_ticklabel_visible(True)
            az_axis.set_ticklabel(color=ticks_color, path_effects=path_effects)
            az_axis.set_major_formatter("d")
            az_axis.set_ticks(number=12)
            alt_axis.set_axislabel("Elevation")
            alt_axis.set_ticks_visible(False)
            alt_axis.set_ticklabel_visible(True)
            alt_axis.set_major_formatter("d")
            alt_axis.set_ticks(number=10)

            # Add NSEW points
            nesw_labels = np.array(["N", "E", "S", "W"])
            nesw = SkyCoord(
                np.array([0, 90, 180, 270]),
                np.array([0, 0, 0, 0]),
                unit="deg",
                frame=frame
            ).transform_to(ICRS)
            for label, coord in zip(nesw_labels, nesw):
                ax.text(
                    x=coord.ra.deg,
                    y=coord.dec.deg,
                    s=label,
                    color="tab:orange",
                    transform=ax.get_transform("world"),
                    path_effects=path_effects,
                    verticalalignment="center",
                    horizontalalignment="center",
                    clip_on=True
                )

        # Colorbar
        if kwargs.get("show_colorbar", True):
            cax = inset_axes(
                ax,
                width='3%',
                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=cmap),
                orientation='vertical',
                norm=Normalize(
                    vmin=vmin,
                    vmax=vmax
                ),
                ticks=LinearLocator()
            )
            cb.solids.set_edgecolor("face")
            cb.set_label(colorbar_label)
            cb.formatter.set_powerlimits((0, 0))

        # Overplot
        # if kwargs.get("circle", None) is not None:
        #     from matplotlib.patches import Circle
        #     frame = AltAz(obstime=self.time, location=self.observer)
        #     c = Circle(
        #         (0, 75),
        #         20,
        #         edgecolor='yellow',
        #         linewidth=5,
        #         facecolor='none',
        #         #transform=ax.get_transform('world')
        #         #transform=ax.get_transform('fk5')
        #         transform=ax.get_transform(frame)
        #     )
        #     ax.add_patch(c)
        if kwargs.get("moc", None) is not None:
            # In order fo that to work; I had to comment #axis_viewport.set(ax, wcs)
            # from add_patches_to_mpl_axe() in mocpy/moc/plot/fill.py
            # OR re-set the limits (done here)
            try:
                frame = AltAz(obstime=self.time, location=self.observer)
                xlimits = ax.get_xlim()
                ylimits = ax.get_ylim()
                mocs = kwargs["moc"] if isinstance(kwargs["moc"], list) else [kwargs["moc"]]
                for moc, color in zip(mocs, ["tab:red", "tab:green"]):
                    moc.fill(
                        ax=ax,
                        wcs=wcs,
                        alpha=0.5,
                        fill=True,
                        color=color,
                        linewidth=0,
                    )
                ax.set_xlim(xlimits)
                ax.set_ylim(ylimits)
            except AttributeError:
                log.warning("A 'MOC' object, generated from mocpy is expected.")
                raise

        if kwargs.get("altaz_moc", None) is not None:
            xlimits = ax.get_xlim()
            ylimits = ax.get_ylim()
            altaz = self.horizontal_coordinates
            mask = kwargs["altaz_moc"].contains(altaz.az, altaz.alt)
            ax.scatter(
                x=self.coordinates[mask].ra.deg,
                y=self.coordinates[mask].dec.deg,
                s=0.1,#[marker_size]*coords.size,
                facecolor="red",
                edgecolor=None,
                alpha=0.5,
                transform=ax.get_transform("world")
            )
            ax.set_xlim(xlimits)
            ax.set_ylim(ylimits)

        if kwargs.get("scatter", None) is not None:
            parameters = kwargs["scatter"]
            if len(parameters) != 3:
                raise ValueError(
                    "'scatter' syntax should be: (<SkyCoord>, <size>, <color>)"
                )
            coords = parameters[0]
            if coords.isscalar:
                coords = coords.reshape((1,))
            marker_size = parameters[1]
            marker_color = parameters[2]
            ax.scatter(
                x=coords.ra.deg,
                y=coords.dec.deg,
                s=[marker_size]*coords.size,
                color=marker_color,
                transform=ax.get_transform("world")
            )

        if kwargs.get("text", None) is not None:
            parameters = kwargs["text"]
            if len(parameters) != 3:
                raise ValueError(
                    "'text' syntax should be: (<SkyCoord>, <[text]>, <color>)"
                )
            coords = parameters[0]
            if coords.isscalar:
                coords = coords.reshape((1,))
            text = parameters[1]
            text_color = parameters[2]

            for i in range(coords.size):
                ax.text(
                    x=coords[i].ra.deg,
                    y=coords[i].dec.deg,
                    s=text[i],
                    color=text_color,
                    transform=ax.get_transform("world"),
                    clip_on=True
                )

        if kwargs.get("contour", None) is not None:
            parameters = kwargs["contour"]
            data = parameters[0]
            if len(parameters) != 3:
                raise ValueError(
                    "'contour' syntax should be: (<numpy.ndarray>, <[levels]>, <colormap>)"
                )
            contour, _ = reproject_from_healpix(
                (data, ICRS()),
                wcs,
                nested=False,
                shape_out=shape#(ndec, nra)
            )
            ax.contour(
                contour,
                levels=parameters[1],
                cmap=parameters[2],
            )

        # Other
        im.set_clip_path(ax.coords.frame.patch)
        ax.set_title(title, pad=20)

        # Save or show
        if figname is None:
            plt.show()
        elif figname.lower() == "return":
            return fig, ax
        else:
            fig.savefig(
                figname,
                dpi=300,
                transparent=True,
                bbox_inches='tight'
            )
        plt.close('all')
Exemple #53
0
class Plotter3d():
    def __init__(self, notify, figure, settings):
        self.notify = notify
        self.figure = figure
        self.settings = settings
        self.axes = None
        self.bar = None
        self.barBase = 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 ($\mathsf{dB/\sqrt{Hz}}$)')
        colour = hex2color(self.settings.background)
        colour += (1,)
        self.axes.w_xaxis.set_pane_color(colour)
        self.axes.w_yaxis.set_pane_color(colour)
        self.axes.w_zaxis.set_pane_color(colour)
        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))

    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, EventThread(Event.DRAW))

    def get_axes(self):
        return self.axes

    def get_axes_bar(self):
        return self.barBase.ax

    def get_plot_thread(self):
        return self.threadPlot

    def set_title(self, title):
        self.axes.set_title(title, fontsize='medium')

    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
def plot_events_stations_map_depth(events,
                                   inv=None,
                                   figsize=(8, 8),
                                   out=None,
                                   show=True,
                                   dpi=300,
                                   convert_coords=False,
                                   plotall=True,
                                   colorbar=True,
                                   label=True,
                                   ms=9):
    id_, time, lon, lat, dep, mag, *_ = zip(
        *events2lists(events.filter('magnitude > 1.8')))
    _, _, lon2, lat2, dep2, _, *_ = zip(*events2lists(events))
    print(time[0], time[-1])

    fig = plt.figure(figsize=figsize)
    ax3 = fig.add_axes((0.1, 0.5, 0.4, 0.4))
    ax4 = fig.add_axes((0.52, 0.5, 0.35, 0.4), sharey=ax3)
    ax5 = fig.add_axes((0.1, 0.5 - 0.37, 0.4, 0.35), sharex=ax3)

    def _on_lims_changed(ax, boo=[True]):
        if boo[0]:
            boo[0] = False
            if ax == ax5:
                ax4.set_xlim(ax5.get_ylim()[::-1])
            if ax == ax4:
                ax5.set_ylim(ax4.get_xlim()[::-1])
            boo[0] = True

    mpl = [t.matplotlib_date for t in time]
    ax5.invert_yaxis()
    ax5.callbacks.connect('ylim_changed', _on_lims_changed)
    ax4.callbacks.connect('xlim_changed', _on_lims_changed)
    ax4.yaxis.tick_right()
    ax4.yaxis.set_label_position("right")
    ax3.xaxis.tick_top()
    ax3.xaxis.set_label_position("top")
    ax4.xaxis.tick_top()
    ax4.xaxis.set_label_position("top")

    if convert_coords:
        latlon0 = None if convert_coords == True else convert_coords
        x, y = zip(*convert_coords2km(list(zip(lat, lon)), latlon0=latlon0))
        x2, y2 = zip(
            *convert_coords2km(list(zip(lat2, lon2)), latlon0=latlon0))
    else:
        x, y = lon, lat
        x2, y2 = lon2, lat2
    mag = np.array(mag)

    cmap, norm = get_cmap()
    if plotall:
        ax3.scatter(x2, y2, 4, color='0.6')
        ax4.scatter(dep2, y2, 4, color='0.6')
        ax5.scatter(x2, dep2, 4, color='0.6')
    ax3.scatter(x, y, ms, mpl, cmap=cmap, norm=norm)
    ax4.scatter(dep, y, ms, mpl, cmap=cmap, norm=norm)
    ax5.scatter(x, dep, ms, mpl, cmap=cmap, norm=norm)
    if colorbar:
        ax7 = fig.add_axes([0.56, 0.42, 0.34, 0.02])
        cmap, norm = get_cmap(extend=True)
        cbar = ColorbarBase(ax7,
                            cmap=cmap,
                            norm=norm,
                            orientation='horizontal',
                            format=DateFormatter('%Y-%m-%d'),
                            extend='max',
                            spacing='proportional')  #, extendfrac=0.2)
        cbar.ax.set_xticklabels(cbar.ax.get_xticklabels()[:-1] +
                                ['until 2018-06-19'],
                                rotation=60,
                                ha='right',
                                rotation_mode='anchor')
        xticks = cbar.ax.get_xticks()
        xticks = np.mean([xticks[1:], xticks[:-1]], axis=0)
        for xpos, label in zip(xticks, 'abcde'):
            # this line only works for matplotlib 3.1 at the moment
            cbar.ax.annotate(label, (xpos, 0.1),
                             ha='center',
                             fontstyle='italic')

    ax4.set_xlabel('depth (km)')
    ax5.set_ylabel('depth (km)')
    if convert_coords:
        if label:
            ax3.set_xlabel('easting (km)')
            ax3.set_ylabel('northing (km)')
            ax5.set_xlabel('easting (km)')
            ax4.set_ylabel('northing (km)')
    else:
        if label:
            ax3.set_xlabel('longitude')
            ax3.set_ylabel('latitude')
            ax5.set_xlabel('longitude')
            ax4.set_ylabel('latitude')
    if out:
        plt.savefig(out, dpi=dpi)
    if show:
        plt.show()
    return fig
Exemple #55
0
class Spectrogram(object):
    def __init__(self, notify, figure, settings):
        self.notify = notify
        self.figure = figure
        self.settings = settings
        self.data = [[], [], []]
        self.axes = None
        self.plot = None
        self.extent = None
        self.bar = None
        self.barBase = None
        self.lines = {}
        self.labels = {}
        self.overflowLabels = {}
        self.overflow = {'left': [],
                         'right': []}

        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(utc_to_mpl(now), utc_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.__setup_measure()
        self.__setup_overflow()
        self.hide_measure()

    def __setup_measure(self):
        dashesHalf = [1, 5, 5, 5, 5, 5]
        self.lines[Markers.HFS] = Line2D([0, 0], [0, 0], dashes=dashesHalf,
                                         color='purple')
        self.lines[Markers.HFE] = Line2D([0, 0], [0, 0], dashes=dashesHalf,
                                         color='purple')
        self.lines[Markers.OFS] = Line2D([0, 0], [0, 0], dashes=dashesHalf,
                                         color='#996600')
        self.lines[Markers.OFE] = 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.lines[Markers.HFS].set_path_effects([effect])
            self.lines[Markers.HFE].set_path_effects([effect])
            self.lines[Markers.OFS].set_path_effects([effect])
            self.lines[Markers.OFE].set_path_effects([effect])

        for line in self.lines.itervalues():
            self.axes.add_line(line)

        bbox = self.axes.bbox
        box = dict(boxstyle='round', fc='white', ec='purple', clip_box=bbox)
        self.labels[Markers.HFS] = Text(0, 0, '-3dB', fontsize='xx-small',
                                        ha="center", va="top", bbox=box,
                                        color='purple')
        self.labels[Markers.HFE] = Text(0, 0, '-3dB', fontsize='xx-small',
                                        ha="center", va="top", bbox=box,
                                        color='purple')
        box['ec'] = '#996600'
        self.labels[Markers.OFS] = Text(0, 0, 'OBW', fontsize='xx-small',
                                        ha="center", va="top", bbox=box,
                                        color='#996600')
        self.labels[Markers.OFE] = Text(0, 0, 'OBW', fontsize='xx-small',
                                        ha="center", va="top", bbox=box,
                                        color='#996600')

        for label in self.labels.itervalues():
            self.axes.add_artist(label)

    def __setup_overflow(self):
        bbox = self.axes.bbox
        box = dict(boxstyle='round', fc='white', ec='black', alpha=0.5,
                   clip_box=bbox)
        self.overflowLabels['left'] = Text(0, 0.9, '', fontsize='xx-small',
                                           ha="left", va="top", bbox=box,
                                           transform=self.axes.transAxes,
                                           alpha=0.5)
        self.overflowLabels['right'] = Text(1, 0.9, '', fontsize='xx-small',
                                            ha="right", va="top", bbox=box,
                                            transform=self.axes.transAxes,
                                            alpha=0.5)

        for label in self.overflowLabels.itervalues():
            self.axes.add_artist(label)

    def __clear_overflow(self):
        for label in self.overflowLabels:
            self.overflow[label] = []

    def __draw_vline(self, marker, x):
        line = self.lines[marker]
        label = self.labels[marker]
        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)
        elif x is not None and x < xLim[0]:
            self.overflow['left'].append(marker)
        elif x is not None and x > xLim[1]:
            self.overflow['right'].append(marker)

    def __draw_overflow(self):
        for pos, overflow in self.overflow.iteritems():
            if len(overflow) > 0:
                text = ''
                for measure in overflow:
                    if len(text) > 0:
                        text += '\n'
                    text += self.labels[measure].get_text()

                label = self.overflowLabels[pos]
                if pos == 'left':
                    textMath = '$\\blacktriangleleft$\n' + text
                elif pos == 'right':
                    textMath = '$\\blacktriangleright$\n' + text

                label.set_text(textMath)
                label.set_visible(True)
                self.axes.draw_artist(label)

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

        self.hide_measure()
        self.__clear_overflow()

        if show[Measure.HBW]:
            xStart, xEnd, _y = measure.get_hpw()
            self.__draw_vline(Markers.HFS, xStart)
            self.__draw_vline(Markers.HFE, xEnd)

        if show[Measure.OBW]:
            xStart, xEnd, _y = measure.get_obw()
            self.__draw_vline(Markers.OFS, xStart)
            self.__draw_vline(Markers.OFE, xEnd)

        self.__draw_overflow()

    def hide_measure(self):
        for line in self.lines.itervalues():
            line.set_visible(False)
        for label in self.labels.itervalues():
            label.set_visible(False)
        for label in self.overflowLabels.itervalues():
            label.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, EventThread(Event.DRAW))

    def get_axes(self):
        return self.axes

    def get_axes_bar(self):
        return self.barBase.ax

    def get_plot_thread(self):
        return self.threadPlot

    def set_title(self, title):
        self.axes.set_title(title, fontsize='medium')

    def set_plot(self, spectrum, extent, annotate=False):
        self.extent = extent
        self.threadPlot = ThreadPlot(self, self.settings,
                                     self.axes,
                                     spectrum,
                                     self.extent,
                                     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_line" 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
def plot_events2018_interpretation(events):
    fig = plot_events_stations_map_depth(events,
                                         show=False,
                                         plotall=False,
                                         colorbar=False,
                                         label=False,
                                         ms=4)
    #    eqs = load_webnet(stations=False)
    #    color = 'gray'
    #    color = '#9bd7ff'
    #    fig.axes[0].scatter(eqs.lon.values, eqs.lat.values, 4, eqs.time.values, marker='o', zorder=-1)
    #    fig.axes[1].scatter(eqs.dep.values, eqs.lat.values, 4, eqs.time.values, marker='o', zorder=-1)
    #    fig.axes[2].scatter(eqs.lon.values, eqs.dep.values, 4, eqs.time.values, marker='o', zorder=-1)
    #    fig.axes[0].set_xlim(-2.5, 2.5)
    #    fig.axes[0].set_ylim(-2.3, 2.7)
    #    lon, lat, dep = 12.42396, 50.22187, 8.5
    #    lon, lat, dep = 12.45993, 50.27813, 8.5
    #    lon, lat, dep = 12.45993, 50.22187, 11.5
    lon, lat, dep = 12.45993, 50.22187, 8.5
    kw = dict(zorder=-1,
              vmin=3,
              vmax=4,
              cmap='Greys',
              edgecolors='face',
              linewidths=0.01)
    #    kw = dict(zorder=-1, vmin=5, vmax=6.5, cmap='Greys')
    #    kw = dict(zorder=-1, vmin=1.55, vmax=1.75, cmap='Greys')
    #    load_mousavi()
    try:
        plot_mousavi(2, dep, 0, 1, 4, ax=fig.axes[0], **kw)
        plot_mousavi(0, lon, 2, 1, 4, ax=fig.axes[1], **kw)
        im = plot_mousavi(1, lat, 0, 2, 4, ax=fig.axes[2], **kw)
    except OSError:
        import traceback
        print(traceback.format_exc())
        print('Mousavi model is not provided in this repository')
        im = None
    kw = dict(color='red', lw=2, zorder=0)
    kw = dict(color='C1', alpha=0.8, lw=2, zorder=0)
    ax0, ax1, ax2, *_ = fig.axes
    ax0.axhline(lat, **kw)
    ax0.axvline(lon, **kw)
    ax1.axvline(dep, **kw)
    ax2.axhline(dep, **kw)
    ax0.set_xlim(12.388, 12.53187)
    ax0.set_ylim(50.10935, 50.3344)
    ax1.set_xlim(0, 12)
    ax1.set_xticks(ax2.get_yticks())
    cax2 = fig.add_axes([0.56, 0.42, 0.34, 0.02])
    cmap, norm = get_cmap()
    cbar = ColorbarBase(cax2,
                        cmap=cmap,
                        norm=norm,
                        orientation='horizontal',
                        format=DateFormatter('%Y-%m-%d'))
    cax2.set_xticklabels([])
    cax2.set_xlabel('intra-cluster\nS wave velocity (km/s)', labelpad=12)
    for i, label in enumerate('abcde'):
        cax2.annotate(label, ((i + 0.5) / 5, 0.1),
                      xycoords='axes fraction',
                      ha='center',
                      fontstyle='italic')
    for i, label in enumerate([4.16, 3.49, 3.66, 3.85, 3.72]):
        cax2.annotate(label, ((i + 0.5) / 5, -1.2),
                      xycoords='axes fraction',
                      ha='center')
    lonticks = [12.40, 12.45, 12.50]
    latticks = [50.15, 50.20, 50.25, 50.30]
    add_ticklabels(ax0, lonticks, latticks, fmt='%.2f°')
    if im is not None:
        cax = fig.add_axes([0.56, 0.27, 0.34, 0.02])
        fig.colorbar(im, cax=cax, orientation='horizontal')
        for i, label in enumerate([4.16, 3.49, 3.66, 3.85, 3.72]):
            cax.annotate(
                '', (label - 3, 1.1), (label - 3, 2.5),
                xycoords='axes fraction',
                textcoords='axes fraction',
                arrowprops=dict(width=1,
                                headwidth=4,
                                headlength=6,
                                color=cmap(i)))  #, xycoords='axes fraction',
        cax.set_xlabel('S wave velocity (km/s)\nMousavi et al. (2015)')
    fig.savefig('figs/eventmap_interpretation.pdf',
                bbox_inches='tight',
                pad_inches=0.1)
    plt.show()
Exemple #57
0
    def draw(self):

        PlotBase.draw(self)
        self.x_formatter_cb(self.ax)

        if self.gdata.isEmpty():
            return None

        # Evaluate the bar width
        width = float(self.width)
        offset = 0.
        if self.gdata.key_type == 'time':
            width = width / 86400.0

        start_plot = 0
        end_plot = 0
        if "starttime" in self.prefs and "endtime" in self.prefs:
            start_plot = date2num(
                datetime.datetime.fromtimestamp(
                    to_timestamp(self.prefs['starttime'])))
            end_plot = date2num(
                datetime.datetime.fromtimestamp(
                    to_timestamp(self.prefs['endtime'])))

        labels = self.gdata.getLabels()
        nKeys = self.gdata.getNumberOfKeys()
        tmp_b = []
        tmp_x = []
        tmp_y = []

        self.bars = []
        labels = self.gdata.getLabels()
        nLabel = 0
        labelNames = []
        colors = []
        xmin = None
        xmax = None
        for label, _num in labels:
            labelNames.append(label)
            for key, value, _error in self.gdata.getPlotNumData(label):

                if xmin is None or xmin > (key + offset):
                    xmin = key + offset
                if xmax is None or xmax < (key + offset):
                    xmax = key + offset

                if value is not None:
                    colors.append(self.getQualityColor(value))
                    tmp_x.append(key + offset)
                    tmp_y.append(1.)
                    tmp_b.append(float(nLabel))

            nLabel += 1

        self.bars += self.ax.bar(tmp_x,
                                 tmp_y,
                                 bottom=tmp_b,
                                 width=width,
                                 color=colors)

        dpi = self.prefs.get('dpi', 100)
        setp(self.bars, linewidth=pixelToPoint(0.5, dpi), edgecolor='#AAAAAA')

        #pivots = keys
        #for idx in range(len(pivots)):
        #    self.coords[ pivots[idx] ] = self.bars[idx]

        ymax = float(nLabel)
        self.ax.set_xlim(xmin=0., xmax=xmax + width + offset)
        self.ax.set_ylim(ymin=0., ymax=ymax)
        if self.gdata.key_type == 'time':
            if start_plot and end_plot:
                self.ax.set_xlim(xmin=start_plot, xmax=end_plot)
            else:
                self.ax.set_xlim(xmin=min(tmp_x), xmax=max(tmp_x))
        self.ax.set_yticks([i + 0.5 for i in range(nLabel)])
        self.ax.set_yticklabels(labelNames)
        setp(self.ax.get_xticklines(), markersize=0.)
        setp(self.ax.get_yticklines(), markersize=0.)

        cax, kw = make_axes(self.ax, orientation='vertical', fraction=0.07)
        cb = ColorbarBase(
            cax,
            cmap=cm.RdYlGn,
            norm=self.norms,  #pylint: disable=no-member
            boundaries=self.cbBoundaries,
            values=self.cbValues,
            ticks=self.cbTicks)
        cb.draw_all()
Exemple #58
0
def Plot_Compare_PerpYear(num_clusters,
                          bmus_values_sim,
                          bmus_dates_sim,
                          bmus_values_hist,
                          bmus_dates_hist,
                          n_sim=1,
                          month_ini=1,
                          show=True):
    '''
    Plot simulated - historical bmus comparison in a perpetual year

    bmus_dates requires 1 day resolution time
    bmus_values set min value has to be 1 (not 0)
    '''

    # check dates have 1 day time resolution
    td_h = bmus_dates_hist[1] - bmus_dates_hist[0]
    td_s = bmus_dates_sim[1] - bmus_dates_sim[0]
    if td_h.days != 1 or td_s.days != 1:
        print('PerpetualYear bmus comparison skipped.')
        print('timedelta (days): Hist - {0}, Sim - {1})'.format(
            td_h.days, td_s.days))
        return

    # plot figure
    fig, (ax_hist, ax_sim) = plt.subplots(2,
                                          1,
                                          figsize=(_faspect * _fsize, _fsize))

    # historical perpetual year
    axplot_PerpYear(
        ax_hist,
        num_clusters,
        bmus_values_hist,
        bmus_dates_hist,
        num_sim=1,
        month_ini=month_ini,
    )
    ax_hist.set_title('Historical')

    # simulated perpetual year
    axplot_PerpYear(
        ax_sim,
        num_clusters,
        bmus_values_sim,
        bmus_dates_sim,
        num_sim=n_sim,
        month_ini=month_ini,
    )
    ax_sim.set_title('Simulation')

    # add custom colorbar
    np_colors_int = GetClusterColors(num_clusters)
    ccmap = mcolors.ListedColormap([tuple(r) for r in np_colors_int])
    cax = fig.add_axes([0.92, 0.125, 0.025, 0.755])
    cbar = ColorbarBase(
        cax,
        cmap=ccmap,
        norm=mcolors.Normalize(vmin=0, vmax=num_clusters),
        ticks=np.arange(num_clusters) + 0.5,
    )
    cbar.ax.tick_params(labelsize=8)
    cbar.set_ticklabels(range(1, num_clusters + 1))

    # text
    fig.suptitle('Perpetual Year', fontweight='bold', fontsize=12)

    # show and return figure
    if show: plt.show()
    return fig
Exemple #59
0
def setup_axes(fig:Any, cmap:Any, norm:Any) -> tuple:
    ax = fig.add_axes([0.92, 0.06, 0.045, 0.38])
    cbar = ColorbarBase(ax, cmap=cmap, norm=norm, orientation='vertical', drawedges=False)
    cbar.ax.tick_params(axis='both', which='both', length=0, labelsize=10)
    cbar.outline.set_visible(False)
    return ax, cbar
Exemple #60
0
def test_colorbarbase():
    # smoke test from #3805
    ax = plt.gca()
    ColorbarBase(ax, cmap=plt.cm.bone)