python类make_axes_locatable()的实例源码

plot.py 文件源码 项目:pyrsss 作者: butala 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def add_colorbar(ax, im, side='right', size='5%', pad=0.1, **kwds):
    """
    Add colorbar to the axes *ax* with colors corresponding to the
    color mappable object *im*. Place the colorbar at the *side* of
    *ax* (options are `'right'`, `'left'`, `'top'`, or
    `'bottom'`). The width (or height) of the colorbar is specified by
    *size* and is relative to *ax*. Add space *pad* between *ax* and
    the colorbar. The remaining keyword arguments *kwds* are passed to
    the call to :func:`colorbar`. Return the colorbar instance.

    Reference: http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html
    """
    divider = make_axes_locatable(ax)
    cax = divider.append_axes(side, size=size, pad=pad)
    cb = PL.colorbar(im, cax=cax, **kwds)
    PL.axes(ax)
    return cb
browser.py 文件源码 项目:gcMapExplorer 作者: rjdkmr 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def updateGenomicPlotAxes(self, resize=False):
        if self.genomicPlotAxes is None:    return

        if resize:
            self.divider = None

        if self.divider is None:
            self.divider = make_axes_locatable(self.ax)

        if resize:
            for obj in self.genomicPlotAxes:
                ax = self.divider.append_axes(obj.plotLocation, size=0.6, pad=self.verticalSpace, sharex=self.ax)
                obj.updatePlot(ax)
        else:
            ax = self.divider.append_axes(self.genomicPlotAxes[-1].plotLocation, size=0.6, pad=self.verticalSpace, sharex=self.ax)
            self.genomicPlotAxes[-1].updatePlot(ax)

        for obj in self.genomicPlotAxes:
            if self.lowerMostGenomicPlotAxes  != obj.index:
                obj.axes_props.xLabel['Show Label'] = 'none'
                obj.axes_props.xTickLabel['Label Position'] = 'none'
                obj.axes_props.set_to_axes()
topomap.py 文件源码 项目:decoding_challenge_cortana_2016_3rd 作者: kingjr 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def _plot_topomap_multi_cbar(data, pos, ax, title=None, unit=None,
                             vmin=None, vmax=None, cmap='RdBu_r',
                             colorbar=False, cbar_fmt='%3.3f'):
    """Aux Function"""
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable

    _hide_frame(ax)
    vmin = np.min(data) if vmin is None else vmin
    vmax = np.max(data) if vmax is None else vmax

    if title is not None:
        ax.set_title(title, fontsize=10)
    im, _ = plot_topomap(data, pos, vmin=vmin, vmax=vmax, axes=ax,
                         cmap=cmap, image_interp='bilinear', contours=False,
                         show=False)

    if colorbar is True:
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="10%", pad=0.25)
        cbar = plt.colorbar(im, cax=cax, format=cbar_fmt)
        cbar.set_ticks((vmin, vmax))
        if unit is not None:
            cbar.ax.set_title(unit, fontsize=8)
        cbar.ax.tick_params(labelsize=8)
agent_viz.py 文件源码 项目:options 作者: xanderdunn 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __init__(self, agent, num_options):
        self.agent = agent
        self.num_options = num_options
        fig, self.samples = plt.subplots(1, 1, figsize=(3, 3))
        self.subplots = {}
        fig, subplots = plt.subplots(3, num_options+1, figsize=(22, 12))
        self.subplots['reward'] = subplots[0]
        self.subplots['vf'] = subplots[1]
        self.subplots['policy'] = subplots[2]

        self.vf_divs = []
        self.reward_divs = []
        for i in range(num_options+1):
            self.vf_divs.append(make_axes_locatable(self.subplots['vf'][i]).append_axes("right", size="5%", pad=0.1))
            self.reward_divs.append(make_axes_locatable(self.subplots['reward'][i]).append_axes("right", size="5%", pad=0.1))

        self.make_grid_samples()
        self.set_titles()
        plt.ion()
        plt.show()
tredplot.py 文件源码 项目:tredparse 作者: humanlongevity 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def ax_imshow(ax, P_h1h2, cmap, label, h1_hat, h2_hat, samplekey,
              r=4, draw_circle=True, ticks=True):
    im = ax.imshow(P_h1h2, cmap=cmap, origin="lower")

    from mpl_toolkits.axes_grid1 import make_axes_locatable
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=.05)
    cb = plt.colorbar(im, cax)
    cb.set_label(label)
    if not ticks:
        cb.set_ticks([])

    if draw_circle:
        circle = plt.Circle((h1_hat, h2_hat), r, ec='w', fill=False)
        ax.add_artist(circle)

    annotation = "$\hat{h_1}=%d, \hat{h_2}=%d$" % (h1_hat, h2_hat)
    ax.text(200, 100, annotation, color=lsg, ha="center", va="center")

    ax.set_xlabel(r"$h_1$")
    ax.set_ylabel(r"$h_2$")
    title = "Joint probability density for $h_1$ and $h_2$ ({})"\
            .format(samplekey)
    ax.set_title(title)
metrics.py 文件源码 项目:mindpark 作者: danijar 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _process_metric(self, ax, metric):
        if not metric.data.size:
            ax.tick_params(colors=(0, 0, 0, 0))
            ax.set_axis_bgcolor(cm.get_cmap('viridis')(0))
            divider = make_axes_locatable(ax)
            divider.append_axes('right', size='7%', pad=0.1).axis('off')
            return
        domain = self._domain(metric)
        categorical = self._is_categorical(metric.data)
        if metric.data.shape[1] == 1 and not categorical:
            self._plot_scalar(ax, domain, metric.data[:, 0])
        elif metric.data.shape[1] == 1:
            indices = metric.data[:, 0].astype(int)
            min_, max_ = indices.min(), indices.max()
            count = np.eye(max_ - min_ + 1)[indices - min_]
            self._plot_distribution(ax, domain, count)
        elif metric.data.shape[1] > 1:
            self._plot_counts(ax, domain, metric.data)
plotting.py 文件源码 项目:devito 作者: opesci 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def plot_shotrecord(rec, model, t0, tn, colorbar=True):
    """
    Plot a shot record (receiver values over time).

    :param rec: Receiver data with shape (time, points)
    :param model: :class:`Model` object that holds the velocity model.
    :param t0: Start of time dimension to plot
    :param tn: End of time dimension to plot
    """
    scale = np.max(rec) / 10.
    extent = [model.origin[0], model.origin[0] + 1e-3*model.domain_size[0],
              1e-3*tn, t0]

    plot = plt.imshow(rec, vmin=-scale, vmax=scale, cmap=cm.gray, extent=extent)
    plt.xlabel('X position (km)')
    plt.ylabel('Time (s)')

    # Create aligned colorbar on the right
    if colorbar:
        ax = plt.gca()
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(plot, cax=cax)
    plt.show()
plotting.py 文件源码 项目:devito 作者: opesci 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def plot_image(data, vmin=None, vmax=None, colorbar=True, cmap="gray"):
    """
    Plot image data, such as RTM images or FWI gradients.

    :param data: Image data to plot
    :param cmap: Choice of colormap, default is gray scale for images as a
    seismic convention
    """
    plot = plt.imshow(np.transpose(data),
                      vmin=vmin or 0.9 * np.min(data),
                      vmax=vmax or 1.1 * np.max(data),
                      cmap=cmap)

    # Create aligned colorbar on the right
    if colorbar:
        ax = plt.gca()
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(plot, cax=cax)
    plt.show()
matrix_animator.py 文件源码 项目:openanalysis 作者: OpenWeavers 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __init_animation(self):
        masked_array = np.ma.array(self.frames[0], mask=np.isinf(self.frames[0]))
        vmin = 0
        vmax = np.max(np.ma.array(self.frames[-1], mask=np.isinf(self.frames[-1])))
        from mpl_toolkits.axes_grid1 import make_axes_locatable
        div = make_axes_locatable(self.ax2)
        cax = div.append_axes('right', '5%', '5%')
        cax.axis('off')
        div = make_axes_locatable(self.ax3)
        cax = div.append_axes('right', '5%', '5%')
        self.img = self.ax3.imshow(masked_array, interpolation='nearest', vmin=vmin, vmax=vmax, alpha=0.7)
        if self.matrix_labels:
            self.lables = self.__plot_matrix_labels(self.frames[0], self.ax3)
        else:
            self.lables = []
        self.fig.colorbar(self.img, cax=cax)
        self.active_cells.append(self.ax3.add_patch(
            patches.Rectangle((0, 0), 1, 1, fill=False, linestyle='--', color='k', linewidth=3)
        ))
        self.active_cells.append(self.ax3.add_patch(
            patches.Rectangle((0, 0), 1, 1, fill=False, linestyle='--', color='k', linewidth=3)
        ))
        self.active_cells.append(self.ax3.add_patch(
            patches.Rectangle((0, 0), 1, 1, fill=False, linestyle='-', color='k', linewidth=3)
        ))
        return self.lables + [self.img]
dutils.py 文件源码 项目:AIND-VUI-quizzes 作者: udacity 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def plot_mfcc_feature(vis_mfcc_feature):
    # plot the MFCC feature
    fig = plt.figure(figsize=(12,5))
    ax = fig.add_subplot(111)
    im = ax.imshow(vis_mfcc_feature, cmap=plt.cm.jet, aspect='auto')
    plt.title('Normalized MFCC')
    plt.ylabel('Time')
    plt.xlabel('MFCC Coefficient')
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    plt.colorbar(im, cax=cax)
    ax.set_xticks(np.arange(0, 13, 2), minor=False);
    plt.show()
dutils.py 文件源码 项目:AIND-VUI-quizzes 作者: udacity 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def plot_spectrogram_feature(vis_spectrogram_feature):
    # plot the normalized spectrogram
    fig = plt.figure(figsize=(12,5))
    ax = fig.add_subplot(111)
    im = ax.imshow(vis_spectrogram_feature, cmap=plt.cm.jet, aspect='auto')
    plt.title('Normalized Spectrogram')
    plt.ylabel('Time')
    plt.xlabel('Frequency')
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    plt.colorbar(im, cax=cax)
    plt.show()
extinction_plot.py 文件源码 项目:extinction 作者: kbarbary 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def extinction_figure(wave, a_lambda, residual_from, residual_lims=(-0.1, 0.4), title_text='$R_V = 3.1$'):

    names = list(a_lambda.keys())  # consistent ordering between panels
    fig = plt.figure(figsize=(8.5, 6.))

    ax = plt.axes()
    for name in names:
        plt.plot(wave, a_lambda[name], label=name)
    plt.axvline(x=2700., ls=':', c='k')
    plt.axvline(x=3030.3030, ls=':', c='k')
    plt.axvline(x=9090.9091, ls=':', c='k')
    plt.axvspan(wave[0], 1150., fc='0.8', ec='none', zorder=-1000)
    plt.axvspan(1150., 1250., fc='0.9', ec='none', zorder=-1000)    
    plt.text(0.65, 0.95, title_text, transform=ax.transAxes, va='top',
             ha='right', size='x-large')
    plt.ylabel('Extinction ($A(\lambda)$ / $A_V$)')
    plt.legend()
    plt.setp(ax.get_xticklabels(), visible=False)

    divider = make_axes_locatable(ax)
    axresid = divider.append_axes("bottom", size=2.0, pad=0.2, sharex=ax)
    for name in names:
        plt.plot(wave, a_lambda[name] - a_lambda[residual_from])
    plt.axvline(x=2700., ls=':', c='k')
    plt.axvline(x=3030.3030, ls=':', c='k')
    plt.axvline(x=9090.9091, ls=':', c='k')
    plt.axvspan(wave[0], 1150., fc='0.8', ec='none', zorder=-1000)
    plt.axvspan(1150., 1250., fc='0.9', ec='none', zorder=-1000)
    plt.xlim(wave[0], wave[-1])
    plt.ylim(ymin=residual_lims[0], ymax=residual_lims[1])
    plt.ylabel('residual from ' + residual_from)
    plt.xlabel(r'Wavelength ($\mathrm{\AA}$)')

    ax.set_xscale('log')
    axresid.set_xscale('log')
    plt.tight_layout()

    return fig
utils.py 文件源码 项目:nelpy 作者: nelpy 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def add_colorbar(img, ax=None):
    """
    TODO: get keywords from **kwargs, i.e. if they're there, then use
    them, but if not, then don't. This should go for orientation, etc.
    Some others might have good defaults, so use them!
    TODO this function is barebones for now
    """
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.15)
    cb=plt.colorbar(img, cax=cax, orientation="vertical")
    # cb.set_label('probability', labelpad=-10)
    # cb.set_ticks([0,1])
    return cb
example.py 文件源码 项目:PyShearlets 作者: grlee77 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def add_cbar(im, ax):
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="10%", pad=0.05)
    plt.colorbar(im, cax=cax)
plotting.py 文件源码 项目:evaluation-toolkit 作者: lightfield-analysis 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def add_colorbar(idx, cm, height, width, colorbar_bins=8, fontsize=None, img_width=1, scale=0.9):
    axis = plt.subplot(idx)
    plt.imshow(np.ones((height*scale, img_width)), alpha=0)

    # colorbar width must be given as a percentage of the img width,
    # both together should be equal to w/wscale
    width_factor = 100 * (width - img_width) / float(img_width)

    divider = make_axes_locatable(axis)
    cax = divider.append_axes("right", size=str(width_factor)+"%", pad=0.0)
    create_colorbar(cm, cax, colorbar_bins, fontsize)
test_graphics.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_plain_axes(self):

        # supplied ax itself is a SubplotAxes, but figure contains also
        # a plain Axes object (GH11556)
        fig, ax = self.plt.subplots()
        fig.add_axes([0.2, 0.2, 0.2, 0.2])
        Series(rand(10)).plot(ax=ax)

        # suppliad ax itself is a plain Axes, but because the cmap keyword
        # a new ax is created for the colorbar -> also multiples axes (GH11520)
        df = DataFrame({'a': randn(8), 'b': randn(8)})
        fig = self.plt.figure()
        ax = fig.add_axes((0, 0, 1, 1))
        df.plot(kind='scatter', ax=ax, x='a', y='b', c='a', cmap='hsv')

        # other examples
        fig, ax = self.plt.subplots()
        from mpl_toolkits.axes_grid1 import make_axes_locatable
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        Series(rand(10)).plot(ax=ax)
        Series(rand(10)).plot(ax=cax)

        fig, ax = self.plt.subplots()
        from mpl_toolkits.axes_grid.inset_locator import inset_axes
        iax = inset_axes(ax, width="30%", height=1., loc=3)
        Series(rand(10)).plot(ax=ax)
        Series(rand(10)).plot(ax=iax)
utils.py 文件源码 项目:mimicry.ai 作者: fizerkhan 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def plot_matrix(data, ax):
    im = ax.imshow(
        data.T, aspect='auto', origin='lower', interpolation='nearest')
    cax = make_axes_locatable(ax).append_axes("right", size="1%", pad=0.05)
    cb = pyplot.colorbar(im, cax=cax)
    tick_locator = ticker.MaxNLocator(nbins=5)
    cb.locator = tick_locator
    cb.ax.yaxis.set_major_locator(ticker.AutoLocator())
    cb.update_ticks()
visu.py 文件源码 项目:keras-toolbox 作者: hadim 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def browse_images(images, manual_update=False):
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    from ipywidgets import interact

    n = len(images[list(images.keys())[0]])

    def nice_imshow(data, title, ax):
        im = ax.imshow(data, interpolation="none", cmap="gray")
        ax.set_title(title, fontsize=18)

        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.1)
        plt.colorbar(im, cax=cax)

    def view_image(i):

        fig = plt.figure(figsize=(16, 8))

        n_ax = len(images)

        for j, (label, data) in enumerate(images.items()):

            ax = plt.subplot(1, n_ax, j+1)

            if data[i].ndim == 3:
                nice_imshow(data[i, 0], label, ax)
            else:
                nice_imshow(data[i], label, ax)

    interact(view_image, i=(0, n - 1) , __manual=manual_update)
plotting.py 文件源码 项目:ugali 作者: DarkEnergySurvey 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def drawMembersSpatial(self,data):
        ax = plt.gca()
        if isinstance(data,basestring):
            filename = data
            data = pyfits.open(filename)[1].data

        xmin, xmax = -0.25,0.25
        ymin, ymax = -0.25,0.25
        xx,yy = np.meshgrid(np.linspace(xmin,xmax),np.linspace(ymin,ymax))

        x_prob, y_prob = sphere2image(self.ra, self.dec, data['RA'], data['DEC'])

        sel = (x_prob > xmin)&(x_prob < xmax) & (y_prob > ymin)&(y_prob < ymax)
        sel_prob = data['PROB'][sel] > 5.e-2
        index_sort = numpy.argsort(data['PROB'][sel][sel_prob])

        plt.scatter(x_prob[sel][~sel_prob], y_prob[sel][~sel_prob], 
                      marker='o', s=2, c='0.75', edgecolor='none')
        sc = plt.scatter(x_prob[sel][sel_prob][index_sort], 
                         y_prob[sel][sel_prob][index_sort], 
                         c=data['PROB'][sel][sel_prob][index_sort], 
                         marker='o', s=10, edgecolor='none', cmap='jet', vmin=0., vmax=1.) # Spectral_r

        drawProjImage(xx,yy,None,coord='C')

        #ax.set_xlim(xmax, xmin)
        #ax.set_ylim(ymin, ymax)
        #plt.xlabel(r'$\Delta \alpha_{2000}\,(\deg)$')
        #plt.ylabel(r'$\Delta \delta_{2000}\,(\deg)$')
        plt.xticks([-0.2, 0., 0.2])
        plt.yticks([-0.2, 0., 0.2])

        divider = make_axes_locatable(ax)
        ax_cb = divider.new_horizontal(size="7%", pad=0.1)
        plt.gcf().add_axes(ax_cb)
        pylab.colorbar(sc, cax=ax_cb, orientation='vertical', ticks=[0, 0.2, 0.4, 0.6, 0.8, 1.0], label='Membership Probability')
        ax_cb.yaxis.tick_right()
mnist_cnn_3layers_vis.py 文件源码 项目:dlcv05 作者: telecombcn-dl 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def nice_imshow(ax, data, vmin=None, vmax=None, cmap=None):
    """Wrapper around pl.imshow"""
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    im = ax.imshow(data, vmin=vmin, vmax=vmax, interpolation='nearest', cmap=cmap)
    pl.colorbar(im, cax=cax)
external_methods.py 文件源码 项目:SkinLesionNeuralNetwork 作者: Neurality 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def nice_imshow(ax, data, vmin=None, vmax=None, cmap=None):
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    """Wrapper around pl.imshow"""
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    im = ax.imshow(data, vmin=vmin, vmax=vmax, interpolation='nearest', cmap=cmap)
    pl.colorbar(im, cax=cax)
visu.py 文件源码 项目:SkinLesionNeuralNetwork 作者: Neurality 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def browse_images(images, manual_update=False):
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    from ipywidgets import interact

    n = len(images[list(images.keys())[0]])

    def nice_imshow(data, title, ax):
        im = ax.imshow(data, interpolation="none", cmap="gray")
        ax.set_title(title, fontsize=18)

        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.1)
        plt.colorbar(im, cax=cax)

    def view_image(i):

        fig = plt.figure(figsize=(16, 8))

        n_ax = len(images)

        for j, (label, data) in enumerate(images.items()):

            ax = plt.subplot(1, n_ax, j+1)

            if data[i].ndim == 3:
                nice_imshow(data[i, 0], label, ax)
            else:
                nice_imshow(data[i], label, ax)

    interact(view_image, i=(0, n - 1) , __manual=manual_update)
misc.py 文件源码 项目:deep-learning-experiments 作者: raghakot 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def nice_imshow(ax, data, vmin=None, vmax=None, cmap=None):
    """Wrapper around pl.imshow"""
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    im = ax.imshow(data, vmin=vmin, vmax=vmax, interpolation='nearest', cmap=cmap)
    pl.colorbar(im, cax=cax)
other.py 文件源码 项目:mindpark 作者: danijar 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def add_color_bar(ax, img):
    divider = make_axes_locatable(ax)
    cax = divider.append_axes('right', size='7%', pad=0.1)
    bar = plt.colorbar(img, cax=cax)
    return bar
plotting.py 文件源码 项目:devito 作者: opesci 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def plot_perturbation(model, model1, colorbar=True):
    """
    Plot a two-dimensional velocity difference from two seismic :class:`Model`
    objects.

    :param model: :class:`Model` object of first velocity model.
    :param model1: :class:`Model` object of the second velocity model.
    :param source: Coordinates of the source point.
    :param receiver: Coordinates of the receiver points.
    """
    domain_size = 1.e-3 * np.array(model.domain_size)
    extent = [model.origin[0], model.origin[0] + domain_size[0],
              model.origin[1] + domain_size[1], model.origin[1]]
    dv = np.transpose(model.vp) - np.transpose(model1.vp)

    plot = plt.imshow(dv, animated=True, cmap=cm.jet,
                      vmin=min(dv.reshape(-1)), vmax=max(dv.reshape(-1)),
                      extent=extent)
    plt.xlabel('X position (km)')
    plt.ylabel('Depth (km)')

    # Create aligned colorbar on the right
    if colorbar:
        ax = plt.gca()
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        cbar = plt.colorbar(plot, cax=cax)
        cbar.set_label('Velocity perturbation (km/s)')
    plt.show()
plotting.py 文件源码 项目:devito 作者: opesci 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def plot_velocity(model, source=None, receiver=None, colorbar=True):
    """
    Plot a two-dimensional velocity field from a seismic :class:`Model`
    object. Optionally also includes point markers for sources and receivers.

    :param model: :class:`Model` object that holds the velocity model.
    :param source: Coordinates of the source point.
    :param receiver: Coordinates of the receiver points.
    """
    domain_size = 1.e-3 * np.array(model.domain_size)
    extent = [model.origin[0], model.origin[0] + domain_size[0],
              model.origin[1] + domain_size[1], model.origin[1]]

    plot = plt.imshow(np.transpose(model.vp), animated=True, cmap=cm.jet,
                      vmin=np.min(model.vp), vmax=np.max(model.vp), extent=extent)
    plt.xlabel('X position (km)')
    plt.ylabel('Depth (km)')

    # Plot source points, if provided
    if receiver is not None:
        plt.scatter(1e-3*receiver[:, 0], 1e-3*receiver[:, 1],
                    s=25, c='green', marker='D')

    # Plot receiver points, if provided
    if source is not None:
        plt.scatter(1e-3*source[:, 0], 1e-3*source[:, 1],
                    s=25, c='red', marker='o')

    # Ensure axis limits
    plt.xlim(model.origin[0], model.origin[0] + domain_size[0])
    plt.ylim(model.origin[1] + domain_size[1], model.origin[1])

    # Create aligned colorbar on the right
    if colorbar:
        ax = plt.gca()
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        cbar = plt.colorbar(plot, cax=cax)
        cbar.set_label('Velocity (km/s)')
    plt.show()
network.py 文件源码 项目:psst 作者: power-system-simulation-toolbox 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def plot_line_power(obj, results, hour, ax=None):
    '''
    obj: case or network
    '''

    if ax is None:
        fig, ax = plt.subplots(1, 1, figsize=(16, 10))
        ax.axis('off')

    case, network = _return_case_network(obj)

    network.draw_buses(ax=ax)
    network.draw_loads(ax=ax)
    network.draw_generators(ax=ax)
    network.draw_connections('gen_to_bus', ax=ax)
    network.draw_connections('load_to_bus', ax=ax)

    edgelist, edge_color, edge_width, edge_labels = _generate_edges(results, case, hour)
    branches = network.draw_branches(ax=ax, edgelist=edgelist, edge_color=edge_color, width=edge_width, edge_labels=edge_labels)

    divider = make_axes_locatable(ax)
    cax = divider.append_axes('right', size='5%', pad=0.05)
    cb = plt.colorbar(branches, cax=cax, orientation='vertical')
    cax.yaxis.set_label_position('left')
    cax.yaxis.set_ticks_position('left')
    cb.set_label('Loading Factor')

    return ax
matrix_animator.py 文件源码 项目:openanalysis 作者: OpenWeavers 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def apply_to_graph(self, show_graph=True):
        """
        Applies the given algorithm to given graph and displays it

        :param show_graph: Weather to show the graph in final result or not
        """
        # Draw the original matrix
        if show_graph:
            if self.pos is None:
                self.pos = nx.nx_pydot.graphviz_layout(self.graph)
            nx.draw_networkx_nodes(self.graph, self.pos, ax=self.ax1, node_color='g', alpha=0.8,
                                   node_size=self.node_size).set_edgecolor('k')
            nx.draw_networkx_edges(self.graph, self.pos, ax=self.ax1, alpha=0.5)
            if self.weights:
                nx.draw_networkx_edge_labels(self.graph, self.pos, ax=self.ax1,
                                             edge_labels=nx.get_edge_attributes(self.graph, 'weight'))
            if self.lables:
                nx.draw_networkx_labels(self.graph, self.pos, ax=self.ax1)
        # Draw its adjacancy matrix
        result, adj = None, None
        for i, matrix in enumerate(self.fn(self.graph)):
            if i == 0:
                adj = matrix[0]
            result = matrix[0]
        # print(adj, result)
        cmap = plt.get_cmap('jet')
        cmap.set_bad('white', 1.)
        vmin = 0
        vmax = np.max(result)
        from mpl_toolkits.axes_grid1 import make_axes_locatable
        div = make_axes_locatable(self.ax2)
        cax = div.append_axes('right', '5%', '5%')
        cax.axis('off')
        masked_array = np.ma.array(adj, mask=np.isinf(adj))
        self.ax2.imshow(masked_array, interpolation='nearest', cmap=cmap, vmin=vmin, vmax=vmax)
        if self.matrix_labels:
            self.__plot_matrix_labels(adj, self.ax2)
        # Now draw the final matrix
        masked_array = np.ma.array(result, mask=np.isinf(result))
        div = make_axes_locatable(self.ax3)
        cax = div.append_axes('right', '5%', '5%')
        if self.matrix_labels:
            self.__plot_matrix_labels(result, self.ax3)
        self.img = self.ax3.imshow(masked_array, interpolation='nearest', cmap=cmap, vmin=vmin, vmax=vmax)
        self.fig.colorbar(self.img, cax=cax)
        plt.show()
matplotlib_renderer.py 文件源码 项目:MDT 作者: cbclab 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def _add_colorbar(self, axis, map_name, image_figure, colorbar_label, colorbar_position):
        """Add a colorbar to the axis

        Returns:
            axis: the image axis
            colorbar_position (str): one of 'left', 'right', 'top', 'bottom'
        """
        divider = make_axes_locatable(axis)

        show_colorbar = self._get_map_attr(map_name, 'show_colorbar', self._plot_config.show_colorbars)
        show_colorbar_global = self._plot_config.show_colorbars

        if show_colorbar_global:
            axis_kwargs = dict(size="5%", pad=0.1)

            if self._plot_config.show_axis and colorbar_position in ['bottom', 'left']:
                axis_kwargs['pad'] = 0.3

            if show_colorbar and colorbar_position in ('left', 'right'):
                colorbar_axis = divider.append_axes(colorbar_position, **axis_kwargs)
            else:
                fake_axis = divider.append_axes('right', **axis_kwargs)
                fake_axis.axis('off')

            if show_colorbar and colorbar_position in ('top', 'bottom'):
                colorbar_axis = divider.append_axes(colorbar_position, **axis_kwargs)
            else:
                fake_axis = divider.append_axes('bottom', **axis_kwargs)
                fake_axis.axis('off')

        if show_colorbar:
            kwargs = dict(cax=colorbar_axis, ticks=self._get_tick_locator(map_name))
            if colorbar_label:
                kwargs.update(dict(label=colorbar_label))

            if colorbar_position in ['top', 'bottom']:
                kwargs['orientation'] = 'horizontal'

            cbar = plt.colorbar(image_figure, **kwargs)
            cbar.formatter.set_powerlimits((-3, 4))
            colorbar_axis.yaxis.set_offset_position('left')

            if colorbar_position == 'left':
                colorbar_axis.yaxis.set_ticks_position('left')
                colorbar_axis.yaxis.set_label_position('left')

            if colorbar_position == 'top':
                colorbar_axis.xaxis.set_ticks_position('top')
                colorbar_axis.xaxis.set_label_position('top')

            cbar.update_ticks()

            if cbar.ax.get_yticklabels():
                cbar.ax.get_yticklabels()[-1].set_verticalalignment('top')

            self._apply_font_colorbar_axis(colorbar_axis)
spectral.py 文件源码 项目:interactive_mpl_tutorial 作者: tacaswell 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def plot_all_chan_spectrum(spectrum, bins, *, ax=None, **kwargs):

    def integrate_to_angles(spectrum, bins, lo, hi):
        lo_ind, hi_ind = bins.searchsorted([lo, hi])
        return spectrum[lo_ind:hi_ind].sum(axis=0)

    if ax is None:
        fig, ax = plt.subplots(figsize=(13.5, 9.5))
    else:
        fig = ax.figure

    div = make_axes_locatable(ax)
    ax_r = div.append_axes('right', 2, pad=0.1, sharey=ax)
    ax_t = div.append_axes('top', 2, pad=0.1, sharex=ax)

    ax_r.yaxis.tick_right()
    ax_r.yaxis.set_label_position("right")
    ax_t.xaxis.tick_top()
    ax_t.xaxis.set_label_position("top")

    im = ax.imshow(spectrum, origin='lower', aspect='auto',
                   extent=(-.5, 383.5,
                           bins[0], bins[-1]),
                   norm=LogNorm())

    e_line, = ax_r.plot(spectrum.sum(axis=1), bins[:-1] + np.diff(bins))
    p_line, = ax_t.plot(spectrum.sum(axis=0))
    label = ax_t.annotate('[0, 70] kEv', (0, 1), (10, -10),
                          xycoords='axes fraction',
                          textcoords='offset pixels',
                          va='top', ha='left')

    def update(lo, hi):
        p_data = integrate_to_angles(spectrum, bins, lo, hi)
        p_line.set_ydata(p_data)
        ax_t.relim()
        ax_t.autoscale(axis='y')

        label.set_text(f'[{lo:.1f}, {hi:.1f}] keV')
        fig.canvas.draw_idle()

    span = SpanSelector(ax_r, update, 'vertical', useblit=True,
                        rectprops={'alpha': .5, 'facecolor': 'red'},
                        span_stays=True)

    ax.set_xlabel('channel [#]')
    ax.set_ylabel('E [keV]')

    ax_t.set_xlabel('channel [#]')
    ax_t.set_ylabel('total counts')

    ax_r.set_ylabel('E [keV]')
    ax_r.set_xlabel('total counts')
    ax.set_xlim(-.5, 383.5)
    ax.set_ylim(bins[0], bins[-1])
    ax_r.set_xlim(xmin=0)

    return spectrum, bins, {'center': {'ax': ax, 'im': im},
                            'top': {'ax': ax_t, 'p_line': p_line},
                            'right': {'ax': ax_r, 'e_line': e_line,
                                      'span': span}}


问题


面经


文章

微信
公众号

扫码关注公众号