예제 #1
0
def plot_map_w_scalebar2(ax, train_imgs, im_num, mask=True, colorbar=True):
    im_lims = train_imgs['longlat_bounds']['img_{:02d}'.format(im_num)][...]
    plt.imshow(train_imgs['input_images'][im_num][...],
               extent=im_lims,
               origin='upper',
               cmap='YlGn',
               aspect='equal')  #, vmin=50, vmax=150
    if colorbar:
        plt.colorbar()
    if mask:
        plt.imshow(1 - train_imgs['target_masks'][im_num][...],
                   alpha=0.2,
                   extent=im_lims,
                   origin='upper',
                   cmap='Greys_r',
                   aspect='equal')


# np.cos(np.deg2rad(im_lims[2:].mean()))
    plt.title('Image #{} with target masks'.format(im_num))
    l, r = plt.xlim()
    barlength = 0.3 * (r - l)
    bartext = '{:2.1f} km'.format(barlength * kmperdeg)
    bar = AnchoredSizeBar(ax.transData, barlength, bartext, 4)
    ax.add_artist(bar)
    ax.grid()
    return im_lims
예제 #2
0
def get_scalebar(trace, list_ax):
    trace.x_tick_length = int(trace.x_range / 2)
    trace.y_stim_tick_length = trace.y_stim_range / 5
    #trace.y_rec_tick_length = trace.y_rec_range / 0.005

    x_label = str(trace.x_tick_length) + ' ' + trace.x_tick_units
    # needs to be individualized for each ax ------------------------------------------------------------------------------------------------
    y_label1 = ' ' + str(y_tick_length1) + ' ' + y_tick_units1
    #y_label2 = ' ' + str(y_tick_length2) + ' ' + y_tick_units2

    x_scalebar = AnchoredSizeBar(list_ax[0].transData,
                                 trace.x_tick_length,
                                 '',
                                 'center right',
                                 pad=0,
                                 color='black',
                                 frameon=False,
                                 size_vertical=.2)
    #y_scalebar1 = AnchoredSizeBar(ax1.transData, 1.4, '', 'lower right', pad=0, color='black', frameon=False, size_vertical= y_tick_length1)
    list_ax[0].add_artist(x_scalebar)
    #list_ax[0].add_artist(y_scalebar1)(self, parameter_list)

    # Add scale and units to error bars
    list_ax[0].text(trace.x_max + 75,
                    trace.y_stim_max - trace.y_stim_range / 2 - 1,
                    x_label,
                    size=6)
예제 #3
0
    def plot_scalebar(self, length=1, title=None, loc='upper right'):
        """
        Plot a scalebar on the cross section.

        Parameters:
        -----------
            length : number, default=1
                The length of the scale bar in world units (e.g. meters)
            title: string, default="{length} world units"
                The title/label for the scale bar
            loc: int or string
                The position of the scale bar. Valid parameters are:
                    'upper right'  : 1,
                    'upper left'   : 2,
                    'lower left'   : 3,
                    'lower right'  : 4,
                    'right'        : 5,
                    'center left'  : 6,
                    'center right' : 7,
                    'lower center' : 8,
                    'upper center' : 9,
                    'center'       : 10,
        Returns:
        --------
            A matplotlib AnchoredSizeBar artist.
        """
        if title is None:
            title = '{} world units'.format(length)
        self.sizebar = AnchoredSizeBar(self.ax.transData, length,
                                       title, loc=loc, pad=0.5, 
                                       borderpad=0.5, sep=5, frameon=True)
        self.ax.add_artist(self.sizebar)
        return self.sizebar
예제 #4
0
def add_scalebar(pseudoimg,
                 pixelresolution,
                 barwidth,
                 barlocation='lower center',
                 fontprops=None,
                 scalebar=None):
    if fontprops is None:
        fontprops = fm.FontProperties(size=16, weight='bold')

    ax = pseudoimg.gca()

    if scalebar is None:
        scalebar = AnchoredSizeBar(ax.transData,
                                   barwidth / pixelresolution,
                                   '2 cm',
                                   barlocation,
                                   pad=0.5,
                                   sep=5,
                                   color='white',
                                   frameon=False,
                                   size_vertical=barwidth / pixelresolution /
                                   30,
                                   fontproperties=fontprops)

    ax.add_artist(scalebar)

    return ax.get_figure()
예제 #5
0
def add_scalebar(
    ax: mpl.axes.Axes,
    scalebar_size: float,
    pixel_size: float,
    unit: str = "µm",
    edgecolor: str = None,
    **kwargs,
) -> None:
    """Add a scalebar to the axis."""
    # NOTE: this is to be moved to dphtools when the package is ready
    scalebar_length = scalebar_size / pixel_size
    default_scale_bar_kwargs = dict(
        loc="lower right",
        pad=0.5,
        color="white",
        frameon=False,
        size_vertical=scalebar_length / 10,
        fontproperties=fm.FontProperties(weight="bold"),
    )
    default_scale_bar_kwargs.update(kwargs)
    if unit is not None:
        label = f"{scalebar_size} {unit}"
    else:
        label = ""
        if "lower" in default_scale_bar_kwargs["loc"]:
            default_scale_bar_kwargs["label_top"] = True
    scalebar = AnchoredSizeBar(ax.transData, scalebar_length, label, **default_scale_bar_kwargs)
    if edgecolor:
        scalebar.size_bar.get_children()[0].set_edgecolor(edgecolor)
        scalebar.txt_label.get_children()[0].set_path_effects(
            [path_effects.Stroke(linewidth=2, foreground=edgecolor), path_effects.Normal()]
        )
    # add the scalebar
    ax.add_artist(scalebar)
예제 #6
0
def share_maps_cb(df,
                  year_var,
                  year,
                  variable,
                  color,
                  title,
                  source,
                  vmin,
                  vmax,
                  share=True):
    '''
    Create a map for Peru with regional yearly data. Must give min max for
    scale bar, year, variable, color, title and source 
    df must be geodataframe merged with the regional shape
    '''
    df = df.to_crs({'init': 'epsg:3857'})
    fig_, ax = plt.subplots(1, figsize=(10, 10))
    if share: df[variable] = df[variable] * 100
    fig = df[df[year_var].astype(int) == year].plot(column=variable,
                                                    cmap=color,
                                                    ax=ax,
                                                    figsize=(10, 10),
                                                    linewidth=0.8,
                                                    edgecolor='0.8',
                                                    vmin=vmin,
                                                    vmax=vmax,
                                                    legend=True,
                                                    norm=plt.Normalize(
                                                        vmin=vmin, vmax=vmax))
    ax.axis('off')

    #title and source
    ax.set_title(title, fontdict={'fontsize': '15', 'fontweight': '3'})
    plt.figtext(0.28, 0.13, source)

    #arrow
    x_arr, y_arr, arrow_length = 0.90, 0.99, 0.065
    fig.annotate('N',
                 xy=(x_arr, y_arr),
                 xytext=(x_arr, y_arr - arrow_length),
                 arrowprops=dict(facecolor='black', width=2, headwidth=9),
                 ha='center',
                 va='center',
                 fontsize=20,
                 xycoords=fig.transAxes)

    #scale bar
    scalebar = AnchoredSizeBar(fig.transData,
                               500000,
                               '500 km',
                               'lower right',
                               pad=0.1,
                               color='black',
                               frameon=False,
                               size_vertical=1,
                               fontproperties=fm.FontProperties(size=10))
    ax.add_artist(scalebar)

    return fig_
예제 #7
0
def add_sizebar(ax, size):
    asb = AnchoredSizeBar(ax.transData,
                          size,
                          str(size),
                          loc=8,
                          pad=0.1, borderpad=0.5, sep=5,
                          frameon=False)
    ax.add_artist(asb)
예제 #8
0
def plot_geospace_results_grid():
    global geo_data
    global geo_headers
    global som_data
    for i in range(0, len(som_data[0])-3): 
        x=geo_data[:,0]
        y=geo_data[:,1]
        z=geo_data[:,(len(som_data[0])+1+i)]
        df = pd.DataFrame.from_dict(np.array([x,y,z]).T)
        df.columns = ['X_value','Y_value','Z_value']
        df['Z_value'] = pd.to_numeric(df['Z_value'])
        pivotted= df.pivot('Y_value','X_value','Z_value')
        #pivotted=pivotted.fillna(value='nan')
        sns.set_style("ticks", {"xtick.major.size": 8, "ytick.major.size": 8})
        ax=sns.heatmap(pivotted,cmap='jet', square=True, linewidths=0, xticklabels="auto", yticklabels="auto")
        scalebar = AnchoredSizeBar(ax.transData, 3.4, str(geo_data[4][0] - geo_data[0][0]), 1, pad=0.4,
                                    sep=5, borderpad=0.1,
                                    size_vertical=0.2)
        #ax.add_artist(scalebar)
        # Set tick labels to integers:
        fmt = '{:0.0f}'
        xticklabels = []
        for item in ax.get_xticklabels():
            item.set_text(fmt.format(float(item.get_text())))
            xticklabels += [item]
        yticklabels = []
        for item in ax.get_yticklabels():
            item.set_text(fmt.format(float(item.get_text())))
            yticklabels += [item]
        ax.set_xticklabels(xticklabels)
        ax.set_yticklabels(yticklabels)

        every_nth = round((len(ax.xaxis.get_ticklabels()))/2)
        if(every_nth==0):#temp solution, for data sets with only 1 x coordinate
            every_nth=1
        every_nth_y = round((len(ax.yaxis.get_ticklabels()))/2)
        if(every_nth_y==0):#temp solution, for data sets with only 1 x coordinate
            every_nth_y=1
        for n, label in enumerate(ax.xaxis.get_ticklabels()):
            if n % every_nth != 0:
                label.set_visible(False)
        for n, label in enumerate(ax.yaxis.get_ticklabels()):
            if n % every_nth_y != 0:
                label.set_visible(False)
        ax.xaxis.get_ticklabels()[-1].set_visible(True)
        ax.yaxis.get_ticklabels()[-1].set_visible(True)
        plt.yticks(rotation=90)
        plt.yticks(ha='right')
        plt.yticks(va='bottom')
        plt.xticks(rotation=0)
        plt.xticks(ha='left')
        ax.invert_yaxis()
        ax.set_title(geo_headers[len(som_data[0])+i+2])
        plt.tight_layout()
        ax.figure.savefig(working_dir+'/Geo/geoplot_'+str(i+2)+'.png', dpi=300)
        plt.clf()
        plt.cla()
        plt.close()
예제 #9
0
def share_maps(df, year, variable, color, k, title, source, leg):
    '''
    Create a map for Peru with regional yearly data and proportion 
    variable in format [0-1]. Does Natural Breaks Clustering.
    '''
    #create maps
    df = df.to_crs({'init': 'epsg:3857'})
    fig_, ax = plt.subplots(1, figsize=(15, 8))
    df[variable] = df[variable] * 100
    fig = df[df['anio'].astype(int) == year].plot(column=variable,
                                                  cmap=color,
                                                  linewidth=0.5,
                                                  ax=ax,
                                                  edgecolor='0.2',
                                                  scheme='naturalbreaks',
                                                  k=k,
                                                  legend=True)
    #title and source
    ax.set_title(title, fontdict={'fontsize': '15', 'fontweight': '3'})
    plt.figtext(0.38, 0.13, source)

    #legend
    ax.axis('off')
    ax.get_legend().set_bbox_to_anchor((0.40, 0.26))
    ax.get_legend().set_title(leg)
    leg = fig.get_legend()
    for lbl in leg.get_texts():
        label_text = lbl.get_text()
        lower = label_text.split()[0]
        upper = label_text.split()[2]
        new_text = f'{float(lower):,.1f} - {float(upper):,.1f}'
        lbl.set_text(new_text)

    #arrow
    x_arr, y_arr, arrow_length = 0.90, 0.99, 0.065
    ax.annotate('N',
                xy=(x_arr, y_arr),
                xytext=(x_arr, y_arr - arrow_length),
                arrowprops=dict(facecolor='black', width=2, headwidth=9),
                ha='center',
                va='center',
                fontsize=20,
                xycoords=ax.transAxes)

    #scale bar
    scalebar = AnchoredSizeBar(ax.transData,
                               500000,
                               '500 km',
                               'lower right',
                               pad=0.1,
                               color='black',
                               frameon=False,
                               size_vertical=1,
                               fontproperties=fm.FontProperties(size=10))
    ax.add_artist(scalebar)
    return fig_
예제 #10
0
    def render(self, ax):
        # Remove the white patch behind each axes
        ax.patch.set_facecolor('none')

        # Add scale bar -- code is placed here so a scale bar can be drawn on any track instance
        if self.options['scale_bar'] is not None:
            bar = AnchoredSizeBar(ax.transData,
                                  self.options['scale_bar'],
                                  label="%d nt" % self.options['scale_bar'],
                                  loc=self.options['scale_bar_loc'],
                                  frameon=False)
            ax.add_artist(bar)
예제 #11
0
def add_scalebar(pseudoimg,
                 pixelresolution,
                 barwidth,
                 barlabel,
                 barlocation='lower center',
                 fontprops=None,
                 scalebar=None):
    """Add scalebar to matplotlib false color image

    Parameters
    ----------
    pseudoimg : matplotlib figure
        false color image
    pixelresolution : int
        physical size represented by a pixel in mm
    barwidth : float
        size of the scale bar in mm
    barlabel : str
        text for the bar label
    barlocation : str or tuple
        position of scale bar in figure, optional
    fontprops : mpl.fm
        font properties as specified by matplotlib.font_manager, optional
    scalebar : mpl axis object
        a preestablished scale bar, optional

    Returns
    -------
    pseudoimg with a scalebar : matplotlib figure

    """

    if fontprops is None:
        fontprops = fm.FontProperties(size=8, weight='bold')

    ax = pseudoimg.gca()

    if scalebar is None:
        scalebar = AnchoredSizeBar(ax.transData,
                                   barwidth / pixelresolution,
                                   barlabel,
                                   barlocation,
                                   pad=0.15,
                                   sep=3,
                                   color='white',
                                   frameon=False,
                                   size_vertical=barwidth / pixelresolution /
                                   40,
                                   fontproperties=fontprops)

    ax.add_artist(scalebar)

    return ax.get_figure()
예제 #12
0
파일: plotting.py 프로젝트: sbliven/focus
def addScaleBar(axes):
    "adds a scale bar to the figure and removes the ticks"
    axes.get_xaxis().set_visible(False)
    axes.get_yaxis().set_visible(False)
    bar = AnchoredSizeBar(axes.transData,
                          20,
                          '',
                          loc=4,
                          sep=5,
                          borderpad=0.5,
                          frameon=False)
    axes.add_artist(bar)
예제 #13
0
def test_inset_axes():
    def get_demo_image():
        from matplotlib.cbook import get_sample_data
        import numpy as np

        f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
        z = np.load(f)
        # z is a numpy array of 15x15
        return z, (-3, 4, -4, 3)

    fig, ax = plt.subplots(figsize=[5, 4])

    # prepare the demo image
    Z, extent = get_demo_image()
    Z2 = np.zeros([150, 150], dtype="d")
    ny, nx = Z.shape
    Z2[30 : 30 + ny, 30 : 30 + nx] = Z

    # extent = [-3, 4, -4, 3]
    ax.imshow(Z2, extent=extent, interpolation="nearest", origin="lower")

    # creating our inset axes with a bbox_transform parameter
    axins = inset_axes(
        ax, width=1.0, height=1.0, bbox_to_anchor=(1, 1), bbox_transform=ax.transAxes
    )

    axins.imshow(Z2, extent=extent, interpolation="nearest", origin="lower")
    axins.yaxis.get_major_locator().set_params(nbins=7)
    axins.xaxis.get_major_locator().set_params(nbins=7)
    # sub region of the original image
    x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
    axins.set_xlim(x1, x2)
    axins.set_ylim(y1, y2)

    plt.xticks(visible=False)
    plt.yticks(visible=False)

    # draw a bbox of the region of the inset axes in the parent axes and
    # connecting lines between the bbox and the inset axes area
    mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

    asb = AnchoredSizeBar(
        ax.transData,
        0.5,
        "0.5",
        loc="lower center",
        pad=0.1,
        borderpad=0.5,
        sep=5,
        frameon=False,
    )
    ax.add_artist(asb)
예제 #14
0
def draw_sizebar(ax):
    from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
    # draw a horizontal bar with length of 0.1 in Data coordinate
    # (ax.transData) with a label underneath.
    asb = AnchoredSizeBar(ax.transData,
                          0.1,
                          r"1$^{\prime}$",
                          loc=8,
                          pad=0.1,
                          borderpad=0.5,
                          sep=5,
                          frameon=False)
    ax.add_artist(asb)
예제 #15
0
def draw_sizebar(ax):
    """
    Draw a horizontal bar with length of 0.1 in data coordinates,
    with a fixed label underneath.
    """
    from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
    asb = AnchoredSizeBar(ax.transData,
                          0.1,
                          r"1$^{\prime}$",
                          loc='lower center',
                          pad=0.1, borderpad=0.5, sep=5,
                          frameon=False)
    ax.add_artist(asb)
예제 #16
0
def add_scalebar(ax, bar_len, resolution, units = 'um', n_dec = 0, pad = 0.35, \
                 fontsize = 16, frameon = True, color = 'black', loc = 'lower center'):

    # bar_len      : float, length of bar, e.g. 100 micron
    # resolution   : float, pixel size, in units/pixel, e.g. 1.1 microns / pixel
    # units        : str, what units?
    # n_dec        : number of decimals in number displayed below scalebar

    fontprops = fm.FontProperties(size=fontsize)
    n_pix = bar_len / resolution
    scalebar = AnchoredSizeBar(ax.transData, n_pix, ("%."+ "%if"%n_dec)%bar_len + " " + units, loc, \
                               pad=pad, color=color, frameon=frameon, size_vertical=1, fontproperties=fontprops)
    ax.add_artist(scalebar)
    return ax
예제 #17
0
    def plot_scalebar(self, **kwargs):
        length = kwargs.pop('length', 1)
        title = kwargs.pop('title', '{} world units'.format(length))
        dat_bar_length = length / self.vol.dxW

        kwargs['loc'] = kwargs.get('loc', 1)
        kwargs['pad'] = kwargs.get('pad', 0.5)
        kwargs['borderpad'] = kwargs.get('borderpad', 0.5)
        kwargs['sep'] = kwargs.get('sep', 5)
        kwargs['frameon'] = kwargs.get('frameon', True)
        self.sizebar = AnchoredSizeBar(self.ax.transData, dat_bar_length,
                                       title, **kwargs)
        self.ax.add_artist(self.sizebar)
        return self.sizebar
def vis_clean(set, key, cmap, thick=False, cbar=True):
    title = key
    print("Plotting ", set.file_dat)
    data = np.load(set.file_dat + '.npz')

    fig, ax = plt.subplots(frameon=False)


    image = data[key]
    if thick:
        selem = morph.disk(5)
        image = morph.dilation(image, selem)
    image = np.ma.masked_where(image == 0, image)


    im = ax.imshow(image, cmap=cmap)

    scaling = set.pixel_scaling
    # correction of scalebar_size to get 1,10,50... um
    # used in pretty mode
    allowed_scalebars = np.append([10**i for i in range(10)],
                                [5* 10**i for i in range(10)] )
    scalebar_size = closest_number(allowed_scalebars,
                                    400 * scaling)
    pixels_scalebar = scalebar_size/scaling
    scalebar = AnchoredSizeBar(ax.transData,
                       pixels_scalebar, str(scalebar_size) + r' $\mu$m',
                       'lower right',
                       pad=0.3,
                       color='black',
                       frameon=False,
                       size_vertical=1)


    ax.add_artist(scalebar)
    ax.axis('off')

    ax.set_yticks([])
    ax.set_xticks([])
    # ax.set_title(title)

    cbar = fig.colorbar(im)
    fig.tight_layout()

    cbar.ax.get_yaxis().labelpad = 15
    cbar.ax.set_ylabel('intensity (a.u.)', rotation=270)

    plt.savefig(set.file_plot + title + '.pdf', dpi=600, bbox_inches='tight')
    plt.close()
예제 #19
0
    def plot_image(self, **kwargs):
        from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
        scale_bar = kwargs.pop('scale_bar', False)

        if len(self.dset.shape) > 2:
            self.axis.set_title(self.dset.title +
                                '_image {}'.format(self.image_number))
        else:
            self.axis.set_title(self.dset.title)

        self.img = self.axis.imshow(
            np.squeeze(self.dset[tuple(self.selection)]).T,
            extent=self.dset.get_extent(self.image_dims),
            **kwargs)
        self.axis.set_xlabel("{} [{}]".format(
            self.dset.axes[self.image_dims[0]].quantity,
            self.dset.axes[self.image_dims[0]].units))
        self.axis.set_ylabel("{} [{}]".format(
            self.dset.axes[self.image_dims[1]].quantity,
            self.dset.axes[self.image_dims[1]].units))
        if scale_bar:

            plt.axis('off')
            extent = self.dset.get_extent(self.image_dims)
            size_of_bar = int((extent[1] - extent[0]) / 10 + .5)
            if size_of_bar < 1:
                size_of_bar = 1
            scalebar = AnchoredSizeBar(
                plt.gca().transData,
                size_of_bar,
                '{} {}'.format(size_of_bar,
                               self.dset.axes[self.image_dims[0]].units),
                'lower left',
                pad=1,
                color='white',
                frameon=False,
                size_vertical=.2)

            plt.gca().add_artist(scalebar)

        else:
            cbar = self.fig.colorbar(self.img)
            cbar.set_label("{} [{}]".format(self.dset.quantity,
                                            self.dset.units))

            self.axis.ticklabel_format(style='sci', scilimits=(-2, 3))
            self.fig.tight_layout()
        self.img.axes.figure.canvas.draw_idle()
예제 #20
0
def plot_size_bar(ax,
                  value,
                  value_str,
                  loc=4,
                  pad=0.1,
                  borderpad=0.5,
                  sep=5,
                  frameon=False):
    asb = AnchoredSizeBar(ax.transData,
                          value,
                          value_str,
                          loc=loc,
                          pad=pad,
                          borderpad=borderpad,
                          sep=sep,
                          frameon=frameon)
    ax.add_artist(asb)
예제 #21
0
def draw_sizebar(obj,ax, scale, regrid=False):
    """
    Draw a horizontal bar with length of 0.1 in data coordinates,
    with a fixed label underneath.
    """
    if regrid:
        length = 0.1/obj.factor.to(u.Mpc/u.deg)/(scale[1]*obj.pix_size)
    else:
        length = 0.1/obj.factor.to(u.Mpc/u.deg)

    from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
    asb = AnchoredSizeBar(ax.transData,length.value*2.5,
                          r"250 kpc",
                          loc='lower center',
                          pad=0.1, borderpad=0.5, sep=5,
                          frameon=False, color='white')#, fontsize=labelsize)
    ax.add_artist(asb)
예제 #22
0
 def _add_scalebar_artist(self, axis, size_scaled=5):
     """ 
     Cheap scalebar, from matplotlib cook-book.
     """
     scalebar_size_pix = size_scaled / self._ps
     scalebar = AnchoredSizeBar(
         transform=axis.transData,
         size=scalebar_size_pix,
         label='{0:d} {1}'.format(int(round(size_scaled)), self._pu),
         loc='lower left',
         pad=1,
         color='white',
         frameon=False,
         label_top=True,
         size_vertical=8,
     )
     axis.add_artist(scalebar)
예제 #23
0
 def addSBar(self, ax, pos=3, scaleb=1000, hideax=False):
     bar = AnchoredSizeBar(ax.transData,
                           scaleb,
                           '',
                           loc=pos,
                           pad=1,
                           sep=1,
                           borderpad=0.01,
                           frameon=False)  #,prop=None)
     rect = bar.size_bar._children[0]
     rect.set_ec("white")
     rect.set_height(200)
     rect.set_fc('white')
     ax.add_artist(bar)
     if hideax:
         ax.xaxis.set_visible(False)
         ax.yaxis.set_visible(False)
예제 #24
0
def plot_heat_map_ticks_latex(data, filename, v_min, v_max, scale=(500/90.8), log=False):
	"""
	Function plots heat maps of data numpy 2d array and save result to filename.png.
	"""
	#heat map plotting
	x_phys_length = data.shape[1]*scale #physical length of x-axis
	y_phys_length = data.shape[0]*scale #physical length of y-axis
	
	fig, ax = plt.subplots(figsize=(20.0*data.shape[1]/1920.0, 10*data.shape[0]/1200.0), dpi=300)
	
	plt.rcParams['text.latex.preamble'] = [r'\boldmath']
	mpl.rcParams.update({'font.size': 22}) #fontsize
	#ax.set_xlabel(r'$x$, $\mu$\textbf{m}')
	#ax.set_ylabel(r'$y$, $\mu$\textbf{m}')
	#plt.minorticks_on()
	#plt.tick_params(axis='x', pad=7)
	#plt.tick_params(axis='y', pad=5)
	ax.get_xaxis().set_ticks([]) #unset labels
	ax.get_yaxis().set_ticks([])
	plt.grid(False)
	extent = (0, x_phys_length, 0, y_phys_length)
	
	####################################################################################
	### barbarbar!!! ###
	from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
	import matplotlib.font_manager as fm
	
	bar_label = r'$' + str(bar_length) + r'\,\mu$' + r'\textbf{m}'
	scalebar = AnchoredSizeBar(ax.transData, bar_length, bar_label, 'lower right', pad=0.5, sep=7.0, color='white', frameon=False, size_vertical=0, label_top=True)
	ax.add_artist(scalebar)
	
	####################################################################################

	if log==True:
		im = ax.imshow(data, cmap='jet', vmin=v_min, vmax=v_max, norm=mplc.LogNorm(), extent=extent)
		#plt.plot((100,297), (100, 100), 'k', color='w')
	else:
		im = ax.imshow(data, cmap='jet', vmin=v_min, vmax=v_max, extent=extent)
		
	fig.colorbar(im)
	plt.savefig(filename, bbox_inches='tight')

	plt.close()

	return True
예제 #25
0
def test_inset_axes():
    fig, ax = plt.subplots(figsize=[5, 4])

    # prepare the demo image
    # Z is a 15x15 array
    Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy", np_load=True)
    extent = (-3, 4, -4, 3)
    Z2 = np.zeros((150, 150))
    ny, nx = Z.shape
    Z2[30:30 + ny, 30:30 + nx] = Z

    # extent = [-3, 4, -4, 3]
    ax.imshow(Z2, extent=extent, interpolation="nearest", origin="lower")

    # creating our inset axes with a bbox_transform parameter
    axins = inset_axes(ax,
                       width=1.,
                       height=1.,
                       bbox_to_anchor=(1, 1),
                       bbox_transform=ax.transAxes)

    axins.imshow(Z2, extent=extent, interpolation="nearest", origin="lower")
    axins.yaxis.get_major_locator().set_params(nbins=7)
    axins.xaxis.get_major_locator().set_params(nbins=7)
    # sub region of the original image
    x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
    axins.set_xlim(x1, x2)
    axins.set_ylim(y1, y2)

    plt.xticks(visible=False)
    plt.yticks(visible=False)

    # draw a bbox of the region of the inset axes in the parent axes and
    # connecting lines between the bbox and the inset axes area
    mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

    asb = AnchoredSizeBar(ax.transData,
                          0.5,
                          '0.5',
                          loc='lower center',
                          pad=0.1,
                          borderpad=0.5,
                          sep=5,
                          frameon=False)
    ax.add_artist(asb)
    def add_anchored_size_bar(
            ax,
            transform,
            loc='center',
            color='k',
            horizontal_size=3,
            label=None,
            label_top=True,
            pad=0.3,
            fontproperties=None,
            borderpad=0.1,
            sep=0.2,
            bar_height=0.015,
            frameon=True,
            fill_bar=True,
            bbox_to_anchor=(0.5, 0.02, 1, 0.08),  # (x0, y0, x1, y1),
            bbox_transform='figure'):

        if bbox_transform == 'figure':
            bbox_transform = ax.figure.transFigure

        bar = AnchoredSizeBar(transform=transform,
                              loc=loc,
                              color=color,
                              size=horizontal_size,
                              size_vertical=bar_height,
                              label=label,
                              label_top=label_top,
                              pad=pad,
                              fontproperties=fontproperties,
                              borderpad=borderpad,
                              sep=sep,
                              frameon=frameon,
                              fill_bar=fill_bar,
                              bbox_to_anchor=Bbox.from_extents(bbox_to_anchor),
                              bbox_transform=bbox_transform)

        ax.add_artist(bar)

        #window_extent = bar.get_window_extent(ax.figure.canvas.get_renderer())

        #figure_window_extent = ax.figure.transFigure.inverted().transform(window_extent)

        #x0, y0, x1, x1 = figure_window_extent.ravel()
        return bar
def vis_mask(set):
    title = 'mask'
    print("Plotting ", set.file_dat)
    data = np.load(set.file_dat + '.npz')

    fig, ax = plt.subplots(frameon=False)

    selem = morph.disk(5)
    thick_skeleton = morph.dilation(data['skeleton'], selem)
    image = data['mask'] + thick_skeleton
    image = np.ma.masked_where(image == 0, image)

    levels = [0, 1, 2,3]
    colors = ['white', '#8d8dbc' , '#51517c']
    cmap, norm = mpl.colors.from_levels_and_colors(levels, colors)

    ax.imshow(image, cmap=cmap, norm=norm, interpolation='none')

    scaling = set.pixel_scaling
    # correction of scalebar_size to get 1,10,50... um
    # used in pretty mode
    allowed_scalebars = np.append([10**i for i in range(10)],
                                [5* 10**i for i in range(10)] )
    scalebar_size = closest_number(allowed_scalebars,
                                    400 * scaling)
    pixels_scalebar = scalebar_size/scaling
    scalebar = AnchoredSizeBar(ax.transData,
                       pixels_scalebar, str(scalebar_size) + r' $\mu$m',
                       'lower right',
                       pad=0.3,
                       color='black',
                       frameon=False,
                       size_vertical=1)


    ax.add_artist(scalebar)

    ax.axis('off')
    ax.set_yticks([])
    ax.set_xticks([])
    # ax.set_title(title)

    fig.tight_layout()
    plt.savefig(set.file_plot + title + '.pdf', dpi=600, bbox_inches='tight')
    plt.close()
예제 #28
0
    def draw_scalebar(self, ax, img_shape, scale_bar_pos):
        # find closest standard size to bar length ~= 1/6 fig_width
        target_phy_bar_length = self.scale * img_shape[1] / 6
        diff = np.abs(self.phy_bar_lengths - target_phy_bar_length)
        phy_bar_length = self.phy_bar_lengths[np.argmin(diff)]
        px_bar_length = phy_bar_length / self.scale

        # scalebar https://stackoverflow.com/questions/39786714/how-to-insert-scale-bar-in-a-map-in-matplotlib
        scalebar = AnchoredSizeBar(ax.transData,
                                   px_bar_length,
                                   '{} μm'.format(phy_bar_length),
                                   scale_bar_pos,
                                   pad=0.5,
                                   color='white',
                                   frameon=False,
                                   size_vertical=min(10, px_bar_length / 10),
                                   fontproperties=fm.FontProperties(size=18))

        ax.add_artist(scalebar)
예제 #29
0
def create_scalebar(data, ax, scalebar_color):
    """
    Description:
      Compute and create an horizontal scalebar in kilometer or meter to be added to the map.
    -----
    Input:
      data: xarray to be mapped
      ax: matplotlib.axes to work on
      scalebar_color (OPTIONAL): scalebar color (e.g.'orangered')
                                 https://matplotlib.org/examples/color/named_colors.html)
    Output:
      Scalebar to be added
    """
    # Convert lenght at average latitude from decimal degree into kilometer
    ave_lat = ((min(data.latitude) + max(data.latitude)) / 2).values
    lon_km = dd2km(ave_lat,
                   min(data.longitude).values, ave_lat,
                   max(data.longitude).values)
    # Calculate the scalebar caracteristics (rounded value of 1/4 of lengths)
    lon_px = len(data.longitude)
    bar_len = lon_km * 0.25  # 25% of the map width
    if bar_len >= 1:
        units = 'kilometer'
        bar_len = round(bar_len)
        bar_px = round(lon_px * bar_len / lon_km)
    else:
        units = 'meter'
        bar_len = round(bar_len * 10) * 100
        bar_px = round(lon_px * bar_len / 1000 / lon_km)
    # add the scalebar
    fontprops = fm.FontProperties(size=18)
    scalebar = AnchoredSizeBar(ax.transData,
                               bar_px,
                               '%i %s' % (bar_len, units),
                               'lower right',
                               pad=0.1,
                               color=scalebar_color,
                               frameon=False,
                               size_vertical=1,
                               label_top=True,
                               fontproperties=fontprops)
    return (scalebar)
예제 #30
0
 def show_image(self, image=None, cropped=True, title=None, colorbar=False, scalebar=False, scalebar_length=None):
     """
     Displays the most recently acquired image.
     """
     
     if image is None:
         if cropped:
             image = self.image_cropped
         else:
             image = self.image
         
     fig, ax = plt.subplots(figsize=(15,10))
     plt.imshow(image.T, origin='lower')
     
     if title:
         plt.title(title)
     
     if scalebar:
         scalebar = AnchoredSizeBar(ax.transData,
                            scalebar_length/self.scale[0],
                            f'{1e6*scalebar_length} um',
                            'upper right', 
                            pad=1,
                            color='white',
                            frameon=False,
                            size_vertical=0.5,
                            sep = 10,
                            fontproperties=fontprops)
 
         ax.add_artist(scalebar)
         
     plt.xlabel('x (px)')
     plt.ylabel('y (px)')
     fig.patch.set_facecolor('white')
     
     if colorbar:
         divider = make_axes_locatable(ax)
         cax = divider.append_axes("right", size="5%", pad=0.05)
         plt.colorbar(cax=cax, label='counts')
     
     plt.show()
예제 #31
0
파일: overlays.py 프로젝트: aplpy/aplpy
class Scalebar(object):

    def __init__(self, parent):

        # Retrieve info from parent figure
        self._ax = parent.ax
        self._wcs = parent._wcs
        self._figure = parent._figure
        self._dimensions = [parent.x, parent.y]

        # Initialize settings
        self._base_settings = {}
        self._scalebar_settings = {}
        self._label_settings = {}
        self._label_settings['fontproperties'] = FontProperties()

    # LAYOUT

    @auto_refresh
    def show(self, length, label=None, corner='bottom right', frame=False,
             borderpad=0.4, pad=0.5, **kwargs):
        """
        Overlay a scale bar on the image.

        Parameters
        ----------

        length : float, or quantity
            The length of the scalebar in degrees, an angular quantity, or angular unit

        label : str, optional
            Label to place below the scalebar

        corner : int, optional
            Where to place the scalebar. Acceptable values are:, 'left',
            'right', 'top', 'bottom', 'top left', 'top right', 'bottom
            left' (default), 'bottom right'

        frame : str, optional
            Whether to display a frame behind the scalebar (default is False)

        kwargs
            Additional arguments are passed to the matplotlib Rectangle and
            Text classes. See the matplotlib documentation for more details.
            In cases where the same argument exists for the two objects, the
            argument is passed to both the Text and Rectangle instance.
        """

        self._length = length
        self._base_settings['corner'] = corner
        self._base_settings['frame'] = frame
        self._base_settings['borderpad'] = borderpad
        self._base_settings['pad'] = pad

        if isinstance(length, u.Quantity):
            length = length.to(u.degree).value
        elif isinstance(length, u.Unit):
            length = length.to(u.degree)

        if self._wcs.is_celestial:
            pix_scale = proj_plane_pixel_scales(self._wcs)
            sx = pix_scale[self._dimensions[0]]
            sy = pix_scale[self._dimensions[1]]
            degrees_per_pixel = np.sqrt(sx * sy)
        else:
            raise ValueError("Cannot show scalebar when WCS is not celestial")

        length = length / degrees_per_pixel

        try:
            self._scalebar.remove()
        except Exception:
            pass

        if isinstance(corner, str):
            corner = corners[corner]

        self._scalebar = AnchoredSizeBar(self._ax.transData, length, label,
                                         corner, pad=pad, borderpad=borderpad,
                                         sep=5, frameon=frame)

        self._ax.add_artist(self._scalebar)

        self.set(**kwargs)

    @auto_refresh
    def _remove(self):
        self._scalebar.remove()

    @auto_refresh
    def hide(self):
        """
        Hide the scalebar.
        """
        try:
            self._scalebar.remove()
        except Exception:
            pass

    @auto_refresh
    def set_length(self, length):
        """
        Set the length of the scale bar.
        """
        self.show(length, **self._base_settings)
        self._set_scalebar_properties(**self._scalebar_settings)
        self._set_label_properties(**self._scalebar_settings)

    @auto_refresh
    def set_label(self, label):
        """
        Set the label of the scale bar.
        """
        self._set_label_properties(text=label)

    @auto_refresh
    def set_corner(self, corner):
        """
        Set where to place the scalebar.

        Acceptable values are 'left', 'right', 'top', 'bottom', 'top left',
        'top right', 'bottom left' (default), and 'bottom right'.
        """
        self._base_settings['corner'] = corner
        self.show(self._length, **self._base_settings)
        self._set_scalebar_properties(**self._scalebar_settings)
        self._set_label_properties(**self._scalebar_settings)

    @auto_refresh
    def set_frame(self, frame):
        """
        Set whether to display a frame around the scalebar.
        """
        self._base_settings['frame'] = frame
        self.show(self._length, **self._base_settings)
        self._set_scalebar_properties(**self._scalebar_settings)
        self._set_label_properties(**self._scalebar_settings)

    # APPEARANCE

    @auto_refresh
    def set_linewidth(self, linewidth):
        """
        Set the linewidth of the scalebar, in points.
        """
        self._set_scalebar_properties(linewidth=linewidth)

    @auto_refresh
    def set_linestyle(self, linestyle):
        """
        Set the linestyle of the scalebar.

        Should be one of 'solid', 'dashed', 'dashdot', or 'dotted'.
        """
        self._set_scalebar_properties(linestyle=linestyle)

    @auto_refresh
    def set_alpha(self, alpha):
        """
        Set the alpha value (transparency).

        This should be a floating point value between 0 and 1.
        """
        self._set_scalebar_properties(alpha=alpha)
        self._set_label_properties(alpha=alpha)

    @auto_refresh
    def set_color(self, color):
        """
        Set the label and scalebar color.
        """
        self._set_scalebar_properties(color=color)
        self._set_label_properties(color=color)

    @auto_refresh
    def set_font(self, family=None, style=None, variant=None, stretch=None,
                 weight=None, size=None, fontproperties=None):
        """
        Set the font of the tick labels

        Parameters
        ----------

        common: family, style, variant, stretch, weight, size, fontproperties

        Notes
        -----

        Default values are set by matplotlib or previously set values if
        set_font has already been called. Global default values can be set by
        editing the matplotlibrc file.
        """

        if family:
            self._label_settings['fontproperties'].set_family(family)

        if style:
            self._label_settings['fontproperties'].set_style(style)

        if variant:
            self._label_settings['fontproperties'].set_variant(variant)

        if stretch:
            self._label_settings['fontproperties'].set_stretch(stretch)

        if weight:
            self._label_settings['fontproperties'].set_weight(weight)

        if size:
            self._label_settings['fontproperties'].set_size(size)

        if fontproperties:
            self._label_settings['fontproperties'] = fontproperties

        self._set_label_properties(fontproperties=self._label_settings['fontproperties'])

    @auto_refresh
    def _set_label_properties(self, **kwargs):
        """
        Modify the scalebar label properties.

        All arguments are passed to the matplotlib Text class. See the
        matplotlib documentation for more details.
        """
        for kwarg, val in kwargs.items():
            try:
                # Only set attributes that exist
                kvpair = {kwarg: val}
                self._scalebar.txt_label.get_children()[0].set(**kvpair)
                self._label_settings[kwarg] = val
            except AttributeError:
                warnings.warn("Text labels do not have attribute {0}. Skipping.".format(kwarg))

    @auto_refresh
    def _set_scalebar_properties(self, **kwargs):
        """
        Modify the scalebar properties.

        All arguments are passed to the matplotlib Rectangle class. See the
        matplotlib documentation for more details.
        """
        for kwarg, val in kwargs.items():
            try:
                kvpair = {kwarg: val}
                self._scalebar.size_bar.get_children()[0].set(**kvpair)
                self._scalebar_settings[kwarg] = val
            except AttributeError:
                warnings.warn("Scalebar does not have attribute {0}. Skipping.".format(kwarg))

    @auto_refresh
    def set(self, **kwargs):
        """
        Modify the scalebar and scalebar properties.

        All arguments are passed to the matplotlib Rectangle and Text classes.
        See the matplotlib documentation for more details. In cases where the
        same argument exists for the two objects, the argument is passed to
        both the Text and Rectangle instance.
        """
        for kwarg in kwargs:
            kwargs_single = {kwarg: kwargs[kwarg]}
            try:
                self._set_label_properties(**kwargs_single)
            except (AttributeError, TypeError):
                pass
            try:
                self._set_scalebar_properties(**kwargs_single)
            except (AttributeError, TypeError):
                pass

    # DEPRECATED

    @auto_refresh
    def set_font_family(self, family):
        warnings.warn("scalebar.set_font_family is deprecated - use scalebar.set_font instead", DeprecationWarning)
        self.set_font(family=family)

    @auto_refresh
    def set_font_weight(self, weight):
        warnings.warn("scalebar.set_font_weight is deprecated - use scalebar.set_font instead", DeprecationWarning)
        self.set_font(weight=weight)

    @auto_refresh
    def set_font_size(self, size):
        warnings.warn("scalebar.set_font_size is deprecated - use scalebar.set_font instead", DeprecationWarning)
        self.set_font(size=size)

    @auto_refresh
    def set_font_style(self, style):
        warnings.warn("scalebar.set_font_style is deprecated - use scalebar.set_font instead", DeprecationWarning)
        self.set_font(style=style)
예제 #32
0
파일: overlays.py 프로젝트: aplpy/aplpy
    def show(self, length, label=None, corner='bottom right', frame=False,
             borderpad=0.4, pad=0.5, **kwargs):
        """
        Overlay a scale bar on the image.

        Parameters
        ----------

        length : float, or quantity
            The length of the scalebar in degrees, an angular quantity, or angular unit

        label : str, optional
            Label to place below the scalebar

        corner : int, optional
            Where to place the scalebar. Acceptable values are:, 'left',
            'right', 'top', 'bottom', 'top left', 'top right', 'bottom
            left' (default), 'bottom right'

        frame : str, optional
            Whether to display a frame behind the scalebar (default is False)

        kwargs
            Additional arguments are passed to the matplotlib Rectangle and
            Text classes. See the matplotlib documentation for more details.
            In cases where the same argument exists for the two objects, the
            argument is passed to both the Text and Rectangle instance.
        """

        self._length = length
        self._base_settings['corner'] = corner
        self._base_settings['frame'] = frame
        self._base_settings['borderpad'] = borderpad
        self._base_settings['pad'] = pad

        if isinstance(length, u.Quantity):
            length = length.to(u.degree).value
        elif isinstance(length, u.Unit):
            length = length.to(u.degree)

        if self._wcs.is_celestial:
            pix_scale = proj_plane_pixel_scales(self._wcs)
            sx = pix_scale[self._dimensions[0]]
            sy = pix_scale[self._dimensions[1]]
            degrees_per_pixel = np.sqrt(sx * sy)
        else:
            raise ValueError("Cannot show scalebar when WCS is not celestial")

        length = length / degrees_per_pixel

        try:
            self._scalebar.remove()
        except Exception:
            pass

        if isinstance(corner, str):
            corner = corners[corner]

        self._scalebar = AnchoredSizeBar(self._ax.transData, length, label,
                                         corner, pad=pad, borderpad=borderpad,
                                         sep=5, frameon=frame)

        self._ax.add_artist(self._scalebar)

        self.set(**kwargs)