Esempio n. 1
0
def plot_colormap(cmap, continuous=True, discrete=True, ndisc=9):
    """
    Make a figure displaying the color map in continuous and/or discrete form
    """
    nplots = int(continuous) + int(discrete)
    fig, axx = plt.subplots(figsize=(6, .5 * nplots),
                            nrows=nplots,
                            frameon=False)
    axx = np.asarray(axx)
    i = 0
    if continuous:
        norm = mcolors.Normalize(vmin=0, vmax=1)
        ColorbarBase(axx.flat[i],
                     cmap=cmap,
                     norm=norm,
                     orientation='horizontal')
    if discrete:
        colors = cmap(np.linspace(0, 1, ndisc))
        cmap_d = mcolors.ListedColormap(colors, name=cmap.name)
        norm = mcolors.BoundaryNorm(np.linspace(0, 1, ndisc + 1), len(colors))
        ColorbarBase(axx.flat[i],
                     cmap=cmap_d,
                     norm=norm,
                     orientation='horizontal')
    for ax in axx.flat:
        ax.set_axis_off()
    fig.text(0.95, 0.5, cmap.name, va='center', ha='left', fontsize=12)
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)
Esempio n. 3
0
    def get_colorbar(self, title, label, min, max):
        '''Create a colorbar from given data.  Returns a png image as a string.'''

        fig = pylab.figure(figsize=(2, 5))
        ax = fig.add_axes([0.35, 0.03, 0.1, 0.9])
        norm = self.get_norm(min, max)
        formatter = self.get_formatter()
        if formatter:
            cb1 = ColorbarBase(ax,
                               norm=norm,
                               format=formatter,
                               spacing='proportional',
                               orientation='vertical')
        else:
            cb1 = ColorbarBase(ax,
                               norm=norm,
                               spacing='proportional',
                               orientation='vertical')
        cb1.set_label(label, color='1')
        ax.set_title(title, color='1')
        for tl in ax.get_yticklabels():
            tl.set_color('1')
        im = cStringIO.StringIO()
        fig.savefig(im, dpi=300, format='png', transparent=True)
        pylab.close(fig)
        s = im.getvalue()
        im.close()
        return s
Esempio n. 4
0
def ax_colorbar(vmin, vmax, ax=None, label=None, ticks=None):
    """Draw a color bar

    Draws a color bar on an existing axes. The range of the colors is
    defined by ``vmin`` and ``vmax``.

    .. note::

        Unlike the colorbar method from matplotlib, this method does not
        automatically create a new axis for the colorbar. It will paint
        in the currently active axis instead, overwriting any existing
        plots in that axis. Make sure to create a new axis for the
        colorbar.

    Parameters
    ----------
    vmin, vmax : float
        The minimum and maximum values for the colorbar.
    ax : Axes, optional
        The axes to draw the scalp plot on. If not provided, the
        currently activated axes (i.e. ``gca()``) will be taken
    label : string, optional
        The label for the colorbar
    ticks : list, optional
        The tick positions

    Returns
    -------
    ax : Axes
        the axes on which the plot was drawn
    """
    if ax is None:
        ax = plt.gca()
    ColorbarBase(ax, norm=Normalize(vmin, vmax), label=label, ticks=ticks)
def make_plot(crime_counts, crime, hood_map, df, title, label, filename):
    print "Making plot for " + str(crime) + " in Chicago 2016"
    number_of_crime = get_list_of_crime_counts(crime_counts, hood_map, crime)
    fig = plt.figure()
    fig.set_size_inches(18.5, 10.5, forward=True)
    ax = fig.add_subplot(111)
    mymap = getMap(df.crimes)
    mymap.drawmapboundary(fill_color='#46bcec')
    mymap.fillcontinents(color='#f2f2f2', lake_color='#46bcec')
    mymap.drawcoastlines()
    ax.set_title(title)
    cax = fig.add_axes([0.73, 0.1, 0.04, 0.8])
    cmap = cm.get_cmap('YlOrRd')
    norm = Normalize(vmin=0,
                     vmax=max(number_of_crime) + 0.15 * max(number_of_crime))
    cb = ColorbarBase(cax, cmap=cmap, norm=norm)
    drawNeighborhoods(mymap, ax, hood_map, crime_counts, crime, cmap, norm)
    cb.set_label(label)
    oname = filename + ".png"
    onameref = filename + "_RefTowns.png"
    fig.savefig(oname, dpi=200)
    plt.sca(ax)
    drawRefPoints(mymap, refpoints)
    fig.savefig(onameref, dpi=200)
    print "Made " + oname
    print "Made " + onameref
def plot_elevation_hr_multi(track, data):
    """Plot the elevation profile with heart rate annotations."""
    fig = plt.figure()
    ncol = 20
    grid = gridspec.GridSpec(1, ncol)
    ax1 = fig.add_subplot(grid[:, :ncol - 1])
    ax1.set_title('{}: {}'.format(track['name'][0], track['type'][0]))
    cbarax = fig.add_subplot(grid[:, ncol - 1])
    ax1.set_facecolor('0.90')
    xdata = data['delta-seconds']
    ydata = data['ele']
    ax1.plot(xdata, ydata, color='#262626', lw=3)
    poly, _, cmap, norm = make_patches(xdata,
                                       ydata,
                                       data['pulse'],
                                       cmap_name='viridis')
    _ = ColorbarBase(cbarax, cmap=cmap, norm=norm, label='Heart rate / bpm')
    ax1.add_collection(poly)
    ax1.set_ylim(min(ydata) - 2, max(ydata) + 2)
    label_pos, label_lab = _make_time_labels(xdata, 5)
    ax1.set_xticks(label_pos)
    ax1.set_xticklabels(label_lab, rotation=25)
    ax1.set_xlabel('Time')
    ax1.set_ylabel('Elevation / m')
    fig.tight_layout()
    return fig
Esempio n. 7
0
    def getLegendImage(self, orientation='vertical', renderOpts={}):
        if 'vert' in orientation:
            figsize = (1, 5)
            rect = (0.05, 0.05, 0.4, 0.9)
        else:
            figsize = (5, 1)
            rect = (0.05, 0.55, 0.9, 0.4)

        fig = Figure(figsize=figsize, dpi=100)
        ax = fig.add_axes(rect)
        boundaries = arange(self.minValue, self.maxValue,
                            float(self.maxValue - self.minValue) / 256)
        loc = LinearLocator()
        loc.set_bounds(self.minValue, self.maxValue)
        ColorbarBase(ax,
                     boundaries=boundaries,
                     orientation=orientation,
                     ticks=loc(),
                     cmap=get_cmap(renderOpts.get('cmap', 'Paired')))

        if 'vert' in orientation:
            ax.set_ylabel(self.units)
        else:
            ax.set_xlabel(self.units)

        c = FigureCanvas(fig)
        c.draw()
        buf = StringIO()
        c.print_png(buf)
        buf.seek(0)
        img = Image.open(buf)

        return img
Esempio n. 8
0
def plot(n, x, v):
    fig, (ax, colorbar) = plt.subplots(1,
                                       2,
                                       gridspec_kw={'width_ratios': [10, 1]})
    ax.grid(True)
    ax.set_xlabel('X (condensation)')
    ax.set_ylabel('V (deformation)')
    ax.set_xscale('log')
    ax.set_yscale('log')

    # Choose a color map, loop through the colors, and assign them to the color
    # cycle. You need n-1 colors, because you'll plot that many lines
    # between pairs. In other words, your line is not cyclic, so there's
    # no line from end to beginning.
    # Colormaps: https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html
    cm = plt.get_cmap('Spectral')
    cycle = cycler(color=[cm(1. * i / (n - 1)) for i in range(n - 1)])
    ax.set_prop_cycle(cycle)
    for i in range(n - 1):
        ax.plot(x[i:i + 2], v[i:i + 2])

    norm = Normalize(vmin=0, vmax=n)
    ColorbarBase(colorbar, cmap=cm, norm=norm)
    colorbar.set_xlabel('step')
    fig.tight_layout()
    plt.savefig(out)
Esempio n. 9
0
    def __setup_plot(self):
        gs = GridSpec(1, 2, width_ratios=[9.5, 0.5])
        self.axes = self.figure.add_subplot(gs[0],
                                            facecolor=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()
Esempio n. 10
0
 def render(self):
     cbar = ColorbarBase(self.ax,
                         cmap=self.cmap,
                         norm=self.norm,
                         orientation=self.orient)
     self.fmt(cbar)
     return cbar
Esempio n. 11
0
def _colorbar_extension_length(spacing):
    '''
    Produce 12 colorbars with variable length extensions for either
    uniform or proportional spacing.

    Helper function for test_colorbar_extension_length.
    '''
    # Get a colormap and appropriate norms for each extension type.
    cmap, norms = _get_cmap_norms()
    # Create a figure and adjust whitespace for subplots.
    fig = plt.figure()
    fig.subplots_adjust(hspace=.6)
    for i, extension_type in enumerate(('neither', 'min', 'max', 'both')):
        # Get the appropriate norm and use it to get colorbar boundaries.
        norm = norms[extension_type]
        boundaries = values = norm.boundaries
        for j, extendfrac in enumerate((None, 'auto', 0.1)):
            # Create a subplot.
            cax = fig.add_subplot(12, 1, i * 3 + j + 1)
            # Turn off text and ticks.
            for item in cax.get_xticklabels() + cax.get_yticklabels() +\
                    cax.get_xticklines() + cax.get_yticklines():
                item.set_visible(False)
            # Generate the colorbar.
            cb = ColorbarBase(cax,
                              cmap=cmap,
                              norm=norm,
                              boundaries=boundaries,
                              values=values,
                              extend=extension_type,
                              extendfrac=extendfrac,
                              orientation='horizontal',
                              spacing=spacing)
    # Return the figure to the caller.
    return fig
Esempio n. 12
0
def getImages(filename,vname):
    file=NetCDF.NetCDFFile(filename,'r')
    vdata=file.variables[vname] 
    vsize=vdata.shape[0]
	# create empty files subdirectory for output images
    try:
        shutil.rmtree('colorbarImages')
    except:
        pass
    os.makedirs('colorbarImages')
	# go through the whole dataset and generate a color bar image for each step
    for i in range(vsize):
        varray = vdata[i,:,:,]
        data=pylab.flipud(varray)
        pylab.imshow(data, norm=LogNorm())
        imgNum = 'TimeStep_'+ str(i)	
    	if len(data[data>0])>0:
	    #make a new figure that contains the colorbar
    	    fig=pylab.figure(figsize=(2,5))
    	    ax1 = fig.add_axes([0.35, 0.03, 0.1, 0.9])
    	    vmin=data[data>0].min()
    	    vmax=data.max()
    	    norm = LogNorm(vmin,vmax)
	    #make the colorbar in log scale
    	    logFormatter=LogFormatter(10, labelOnlyBase=False)
    	    cb1 = ColorbarBase(ax1,norm=norm,format=logFormatter,spacing='proportional', orientation='vertical')
	    imgName='colorbarImages/%s.png' %imgNum
    	    fig.savefig(imgName, bbox_inches='tight')
Esempio n. 13
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(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))
Esempio n. 14
0
def plot_colorbar(cax,
                  cmap,
                  hue_norm,
                  cnorm=None,
                  label=None,
                  orientation='vertical',
                  labelsize=4,
                  linewidth=0.5):
    if isinstance(cmap, str):
        cmap = copy.copy(get_cmap(cmap))
    if cnorm is None:
        cnorm = Normalize(vmin=hue_norm[0], vmax=hue_norm[1])
    from .utilities import smart_number_format

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

    colorbar.set_label(label, fontsize=labelsize)
    colorbar.outline.set_linewidth(linewidth)
    colorbar.ax.tick_params(size=labelsize,
                            labelsize=labelsize,
                            width=linewidth)
    return cax
Esempio n. 15
0
    def plot(self, data, scale='linear', colormap=plt.cm.jet):
        '''plot data
        
        data: a dictionary of data, whose key is the state name, either full name
        or abbrevation.
        '''
        self.add_states()
        colors, statenames, norm = self.assign_colors(data,
                                                      scale=scale,
                                                      colormap=colormap)
        self.add_patches(colors, statenames)
        self.add_text(statenames)

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

        #%% ---------   Show color bar  ---------------------------------------
        ax_c = self.fig.add_axes([1, 0.1, 0.03, 0.8])
        cb = ColorbarBase(ax_c,
                          cmap=colormap,
                          norm=norm,
                          orientation='vertical',
                          label=' ')
Esempio n. 16
0
def _colorbar_extension_shape(spacing):
    '''
    Produce 4 colorbars with rectangular extensions for either uniform
    or proportional spacing.

    Helper function for test_colorbar_extension_shape.
    '''
    # Get a colormap and appropriate norms for each extension type.
    cmap, norms = _get_cmap_norms()
    # Create a figure and adjust whitespace for subplots.
    fig = plt.figure()
    fig.subplots_adjust(hspace=4)
    for i, extension_type in enumerate(('neither', 'min', 'max', 'both')):
        # Get the appropriate norm and use it to get colorbar boundaries.
        norm = norms[extension_type]
        boundaries = values = norm.boundaries
        # Create a subplot.
        cax = fig.add_subplot(4, 1, i + 1)
        # Generate the colorbar.
        cb = ColorbarBase(cax,
                          cmap=cmap,
                          norm=norm,
                          boundaries=boundaries,
                          values=values,
                          extend=extension_type,
                          extendrect=True,
                          orientation='horizontal',
                          spacing=spacing)
        # Turn off text and ticks.
        cax.tick_params(left=False,
                        labelleft=False,
                        bottom=False,
                        labelbottom=False)
    # Return the figure to the caller.
    return fig
Esempio n. 17
0
        def serialize(dataset):
            fix_map_attributes(dataset)
            fig = Figure(figsize=figsize, dpi=dpi)
            fig.figurePatch.set_alpha(0.0)
            ax = fig.add_axes([0.05, 0.05, 0.45, 0.85])
            ax.axesPatch.set_alpha(0.5)

            # Plot requested grids.
            layers = [
                layer for layer in query.get('LAYERS', '').split(',') if layer
            ] or [var.id for var in walk(dataset, GridType)]
            layer = layers[0]
            names = [dataset] + layer.split('.')
            grid = reduce(operator.getitem, names)

            actual_range = self._get_actual_range(grid)
            norm = Normalize(vmin=actual_range[0], vmax=actual_range[1])
            cb = ColorbarBase(ax,
                              cmap=get_cmap(cmap),
                              norm=norm,
                              orientation='vertical')
            for tick in cb.ax.get_yticklabels():
                tick.set_fontsize(14)
                tick.set_color('white')
                #tick.set_fontweight('bold')

            # Save to buffer.
            canvas = FigureCanvas(fig)
            output = StringIO()
            canvas.print_png(output)
            if hasattr(dataset, 'close'): dataset.close()
            return [output.getvalue()]
Esempio n. 18
0
def axplot_bmus(ax, bmus, num_clusters, lab):
    'axes plot bmus series using colors'

    # colors
    wt_colors = GetClusterColors(num_clusters)

    # prepare nans as white
    bmus = bmus.fillna(num_clusters + 1)
    wt_colors = np.vstack([wt_colors, [0, 0, 0]])

    # bmus colors
    vp = wt_colors[bmus.astype(int) - 1]

    # listed colormap
    ccmap = mcolors.ListedColormap(vp)

    # color series
    cbar_x = ColorbarBase(
        ax,
        cmap=ccmap,
        orientation='horizontal',
        norm=mcolors.Normalize(vmin=0, vmax=num_clusters),
    )
    cbar_x.set_ticks([])

    # customize axes
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_ylabel(lab, rotation=0, fontweight='bold', labelpad=35)
Esempio n. 19
0
def _plot_colorbar(cmap, legend, legend_style, freq_domain, value_range, ax):
    cbar_height = "50%" if legend_style == "righthand" else "100%"
    cbar_loc = "lower left" if legend_style == "righthand" else "center left"
    axins = inset_axes(ax, width=0.1, height=cbar_height, loc=cbar_loc,
                       bbox_to_anchor=(1, 0, 1, 1), bbox_transform=ax.transAxes)
    ColorbarBase(axins, cmap=cmap, norm=plt.Normalize(-value_range, value_range))
    axins.set_ylabel(_get_legend_label(legend, freq_domain))
Esempio n. 20
0
    def make_3panel(self,
                    center,
                    size=10,
                    pixelsize=0.02,
                    galactic=False,
                    scale=1,
                    label_1FGL=True,
                    labels=None,
                    separate_figures=False,
                    fignum_base=10):

        import pylab as P
        from matplotlib.colorbar import ColorbarBase
        from matplotlib.colors import Normalize
        from uw.utilities.image import ZEA

        cmap = P.cm.jet
        cmap.set_bad('white')

        if separate_figures:
            axes = []
            for i in xrange(1, 4):
                P.figure(i + fignum_base)
                axes += [P.gca()]
        else:
            axes = [P.subplot(1, 3, i) for i in xrange(1, 4)]
        zeas = [
            ZEA(center,
                size=size,
                pixelsize=pixelsize,
                galactic=galactic,
                axes=ax) for ax in axes
        ]
        mods = [1, 2, 0]
        for i in xrange(0, 3):
            self.set_mode(mods[i])
            zeas[i].fill(PySkyFunction(self))
            zeas[i].grid()
            axes[i].imshow(zeas[i].image**(0.5 if scale else 1), cmap=cmap)
        if label_1FGL:
            names, skydirs = self.get_1FGL_sources(zeas[0])
            for na, sd in zip(names, skydirs):
                for z in zeas:
                    z.plot_source(na, sd, color='white')
        if labels is not None:
            names, skydirs = labels
            for na, sd in zip(names, skydirs):
                for z in zeas:
                    z.plot_source(na, sd, color='white')
        if separate_figures:
            # basically a "show"
            for i in xrange(1, 4):
                P.figure(i + fignum_base)
                axes[i - 1].set_autoscale_on(True)
                cb = ColorbarBase(axes[i - 1],
                                  orientation='vertical',
                                  cmap=cmap)
                #P.colorbar()
        return axes, zeas
Esempio n. 21
0
    def plot(self, fn="beam_shifts.png"):
        stations = self.stations
        stations.append(self.station_c)
        res = to_cartesian(stations, self.station_c)
        center_xyz = res[self.station_c.nsl()[:2]]
        x = num.zeros(len(res))
        y = num.zeros(len(res))
        z = num.zeros(len(res))
        sizes = num.zeros(len(res))
        stat_labels = []
        i = 0
        for nsl, xyz in res.items():
            x[i] = xyz[0]
            y[i] = xyz[1]
            z[i] = xyz[2]

            try:
                sizes[i] = self.t_shifts[nsl[:2]]
                stat_labels.append("%s" % (".".join(nsl)))
            except AttributeError:
                self.fail("Run the snuffling first")
            except KeyError:
                stat_labels.append("%s" % (".".join(nsl)))
                continue
            finally:
                i += 1

        x /= 1000.0
        y /= 1000.0
        z /= 1000.0

        fig = plt.figure()
        cax = fig.add_axes([0.85, 0.2, 0.05, 0.5])
        ax = fig.add_axes([0.10, 0.1, 0.70, 0.7])
        ax.set_aspect("equal")
        cmap = cm.get_cmap("bwr")
        ax.scatter(
            x, y, c=sizes, s=200, cmap=cmap, vmax=num.max(sizes), vmin=-num.max(sizes)
        )
        for i, lab in enumerate(stat_labels):
            ax.text(x[i], y[i], lab, size=14)

        x = x[num.where(sizes == 0.0)]
        y = y[num.where(sizes == 0.0)]
        ax.scatter(x, y, c="black", alpha=0.4, s=200)

        ax.arrow(
            center_xyz[0] / 1000.0,
            center_xyz[1] / 1000.0,
            -num.sin(self.bazi / 180.0 * num.pi),
            -num.cos(self.bazi / 180.0 * num.pi),
            head_width=0.2,
            head_length=0.2,
        )
        ax.set_ylabel("N-S [km]")
        ax.set_xlabel("E-W [km]")
        ColorbarBase(cax, cmap=cmap, norm=Normalize(vmin=sizes.min(), vmax=sizes.max()))
        logger.debug("finished plotting %s" % fn)
        fig.savefig(fn)
Esempio n. 22
0
def display_displacements(simulation_folder, lower_percentile=70, upper_percentile=99.7, save_plot = True, arrow_factor=4):
    """
    show the total displacement field or the masked range of displacements by size
    simulation_folder: path to simulation folder
    lower_percentile and upper_percentile give range of deformationsize which is used
    as a mask 
    save_plot: option to save the plot to the simulation folder
    arrow_factor: scales the arrow length in the plot
    To increase plotting speed you might increase the lower percentile (e.g 30 instead 0)
    """
    # load in deformations and coordinates
    r =  np.genfromtxt(os.path.join(simulation_folder, "R.dat"))       # positions
    u =  np.genfromtxt(os.path.join(simulation_folder, "Ufound.dat"))     #deformations  
    uabs = np.sqrt(np.sum(u ** 2., axis=1))   # absolute values for filtering
   
    # filter displacements by absolute size
    mask = (uabs > np.percentile(uabs, lower_percentile)) & (uabs < np.percentile(uabs, upper_percentile))
    r2 = r[mask]
    u2 = u[mask]
    uabs2 = uabs[mask]
    
    # plot the masked deformation
    fig = plt.figure()
    ax1 = fig.gca(projection='3d', label='fitted-displ', rasterized=True)

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

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

    ax1.w_xaxis.set_pane_color((0.2, 0.2, 0.2, 1.0))
    ax1.w_yaxis.set_pane_color((0.2, 0.2, 0.2, 1.0))
    ax1.w_zaxis.set_pane_color((0.2, 0.2, 0.2, 1.0))
    
    if save_plot:
        plt.savefig( os.path.join(simulation_folder,'deformations_plot_lower_{}_upper_{}.png'.format(lower_percentile, upper_percentile)), dpi=500, bbox_inches="tight", pad_inches=0)
         
    return
def scale(args):
    """
    Draws the variable scale that is placed over the map.
    Returns a BytesIO object.
    """

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

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

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

    cmap = colormap.find_colormap(variable_name)

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

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

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

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

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

    buf.seek(0)  # Move buffer back to beginning
    return buf
Esempio n. 24
0
 def __init__(self):
     self.data = np.zeros((80, 80))
     self.fig = plt.figure()
     self.ax = self.fig.add_subplot(111)
     self.im = self.ax.imshow(self.data)
     self.cax = self.fig.add_axes([.85, .05, .025, .9])
     norm = mpl.colors.Normalize(vmin=np.amin(self.data), vmax=np.amax(self.data))
     self.cbar = ColorbarBase(self.cax, cmap='viridis', norm=norm, orientation='vertical')
Esempio n. 25
0
def test_colorbar_lognorm_extension():
    # Test that colorbar with lognorm is extended correctly
    f, ax = plt.subplots()
    cb = ColorbarBase(ax,
                      norm=LogNorm(vmin=0.1, vmax=1000.0),
                      orientation='vertical',
                      extend='both')
    assert cb._values[0] >= 0.0
Esempio n. 26
0
def setup_axes(fig: Any, cmap: Any, norm: Any, position: List[Number_T]) -> tuple:
    ax = fig.add_axes(position)
    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 cbar
Esempio n. 27
0
def plot_color_bar(norm):
    # starts with x, y coordinates for start and then width and height in % of figure width
    ax_c0 = fig0.add_axes([0.9, 0.1, 0.022, 0.8])
    cb = ColorbarBase(ax_c0,
                      cmap=colormap,
                      norm=norm,
                      orientation='vertical',
                      label=r'[density per $\mathregular{km^2}$]')
Esempio n. 28
0
def test_colorbar_powernorm_extension():
    # Test that colorbar with powernorm is extended correctly
    f, ax = plt.subplots()
    cb = ColorbarBase(ax,
                      norm=PowerNorm(gamma=0.5, vmin=0.0, vmax=1.0),
                      orientation='vertical',
                      extend='both')
    assert cb._values[0] >= 0.0
Esempio n. 29
0
def plotter(fdict):
    """ Go """
    ctx = get_autoplot_context(fdict, get_description())
    station = ctx['station']
    days = ctx['days']
    varname = ctx['var']
    df = get_data(ctx)
    if df.empty:
        raise NoDataFound('Error, no results returned!')

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

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

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

    ax.set_xlim(df['doy'].min() - 10, df['doy'].max() + 10)
    lax.set_xlim(df['doy'].min() - 10, df['doy'].max() + 10)
    ax.yaxis.set_major_locator(MaxNLocator(prune='lower'))
    return fig, df
Esempio n. 30
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