Python matplotlib.pyplot 模块,axes() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.axes()

项目:em_examples    作者:geoscixyz    | 项目源码 | 文件源码
def addLayer2Mod(zcLayer,dzLayer,mod,sigLayer):

    CCLocs = mesh.gridCC

    zmax = zcLayer + dzLayer/2.
    zmin = zcLayer - dzLayer/2.

    belowInd = np.where(CCLocs[:,1] <= zmax)[0]
    aboveInd = np.where(CCLocs[:,1] >= zmin)[0]
    layerInds = list(set(belowInd).intersection(aboveInd))

    # # Check selected cell centers by plotting
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # plt.scatter(CCLocs[layerInds,0],CCLocs[layerInds,1])
    # ax.set_xlim(-40,40)
    # ax.set_ylim(-35,0)
    # plt.axes().set_aspect('equal')
    # plt.show()

    mod[layerInds] = sigLayer
    return mod
项目:q2-coordinates    作者:nbokulich    | 项目源码 | 文件源码
def plot_basemap(latitude, longitude, image, color_palette=None):
    # define basemap, color palette
    cmap, tiler = get_map_params(image, color_palette)

    # Find min/max coordinates to set extent
    lat_0, lat_1, lon_0, lon_1 = get_max_extent(latitude, longitude)

    # Automatically focus resolution
    max_span = max((abs(lat_1) - abs(lat_0)), (abs(lon_1) - abs(lon_0)))
    res = int(-1.4 * math.log1p(max_span) + 13)

    # initiate tiler projection
    ax = plt.axes(projection=tiler.crs)
    # Define extents of any plotted data
    ax.set_extent((lon_0, lon_1, lat_0, lat_1), ccrs.Geodetic())
    # add terrain background
    ax.add_image(tiler, res)

    return ax, cmap
项目:fem    作者:mlp6    | 项目源码 | 文件源码
def play(self, timerange):
        """play an animation

        Strongly recommend not stepping though each timesteps; use some skips!

        :param timerange: range generator of time steps to animate
        """
        import matplotlib.pyplot as plt
        import matplotlib.animation as animation

        fig = plt.figure()

        plt.pcolormesh(self.lat, self.axial, self.arfidata[:, :, 0])
        plt.axes().set_aspect('equal')
        plt.gca().invert_yaxis()
        plt.xlabel('Lateral (mm)')
        plt.ylabel('Axial (mm)')

        anim = animation.FuncAnimation(fig, self.animate, frames=timerange,
                                       blit=False)

        plt.show()
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def transpose_axes(data, axes, asaxes='CTZYX'):
    """Return data with its axes permuted to match specified axes.

    A view is returned if possible.

    >>> transpose_axes(numpy.zeros((2, 3, 4, 5)), 'TYXC', asaxes='CTZYX').shape
    (5, 2, 1, 3, 4)

    """
    for ax in axes:
        if ax not in asaxes:
            raise ValueError("unknown axis %s" % ax)
    # add missing axes to data
    shape = data.shape
    for ax in reversed(asaxes):
        if ax not in axes:
            axes = ax + axes
            shape = (1,) + shape
    data = data.reshape(shape)
    # transpose axes
    data = data.transpose([axes.index(ax) for ax in asaxes])
    return data
项目:NuGridPy    作者:NuGrid    | 项目源码 | 文件源码
def set_nice_params():
    fsize=18

    params = {'axes.labelsize':  fsize,
    #    'font.family':       'serif',
    'font.family':        'Times New Roman',
    'figure.facecolor':  'white',
    'text.fontsize':     fsize,
    'legend.fontsize':   fsize,
    'xtick.labelsize':   fsize*0.8,
    'ytick.labelsize':   fsize*0.8,
    'ytick.minor.pad': 8,
    'ytick.major.pad': 8,
    'xtick.minor.pad': 8,
    'xtick.major.pad': 8,
    'text.usetex':       False,
    'lines.markeredgewidth': 0}
    pl.rcParams.update(params)
项目:psyplot    作者:Chilipp    | 项目源码 | 文件源码
def reinit(self, draw=None, clear=False):
        """
        Reinitializes the plot with the same data and on the same axes.

        Parameters
        ----------
        %(InteractiveBase.start_update.parameters.draw)s
        clear: bool
            Whether to clear the axes or not

        Warnings
        --------
        The axes may be cleared when calling this method (even if `clear` is
        set to False)!"""
        # call the initialize_plot method. Note that clear can be set to
        # False if any fmto has requires_clearing attribute set to True,
        # because this then has been cleared before
        self.initialize_plot(
            self.data, self._ax, draw=draw, clear=clear or any(
                fmto.requires_clearing for fmto in self._fmtos),
            remove=True)
项目:planetplanet    作者:rodluger    | 项目源码 | 文件源码
def __init__(self, **kwargs):
        '''

        '''

        self.kwargs = kwargs
        self.fig = pl.figure(figsize = (6,6))
        self.fig.subplots_adjust(bottom = 0.25)
        self.axtheta = pl.axes([0.3, 0.05, 0.44, 0.03])
        self.theta = Slider(self.axtheta, r'$\theta$', -180., 180., 
                            valinit = 90.)
        self.axphi = pl.axes([0.3, 0.1, 0.44, 0.03])
        self.phi = Slider(self.axphi, r'$\Phi$', -90, 90., valinit = 0.)
        self.axlam = pl.axes([0.3, 0.15, 0.44, 0.03])
        self.lam = Slider(self.axlam, r'$\Lambda$', -90, 90., valinit = 0.)
        self.theta.on_changed(self._update)
        self.phi.on_changed(self._update)
        self.lam.on_changed(self._update)
        self._update(90.)
        pl.show()
项目:pyumi    作者:jamiefarrell    | 项目源码 | 文件源码
def MakeChart(data, hour, coordinates, lineweights, codes):
    cmap = plt.cm.get_cmap('YlOrRd')
    fig = plt.figure(num=None, figsize=(15, 10), dpi=150, facecolor='w', edgecolor='k')
    ax = fig.add_subplot(111)
    ax.set_title('Winter Day: Hour '+str(hour), fontsize=20, fontweight='bold')
    for i in range(0,len(codes)):
        if coordinates[i] != "null":
            path = Path(coordinates[i], codes[i])
            color = np.random.random(10)
            patch = patches.PathPatch(path, facecolor=cmap(data), lw=lineweights[i])
            ax.add_patch(patch)
    ax.autoscale_view()
    plt.axes().set_aspect('equal', 'datalim')





################
项目:pyumi    作者:jamiefarrell    | 项目源码 | 文件源码
def time_map(jsonpath, hour, lineweights):
    data = js.loads(open(jsonpath).read())
    coordinates = getcoords(data)
    codes = polygonscode(coordinates)
    cmap = plt.cm.get_cmap('YlOrRd')
    fig = plt.figure(num=None, figsize=(15, 10), dpi=150, facecolor='w', edgecolor='k')
    ax = fig.add_subplot(111)
    ax.set_title('Winter Day: Hour '+str(hour), fontsize=20, fontweight='bold')
    for i in range(0,len(codes)):
        if coordinates[i] != "null":
            path = Path(coordinates[i], codes[i])
            color = np.random.random(10)
            patch = patches.PathPatch(path, facecolor=cmap(data), lw=lineweights[i])
            ax.add_patch(patch)
    ax.autoscale_view()
    plt.axes().set_aspect('equal', 'datalim')


################
项目:nanopores    作者:mitschabaude    | 项目源码 | 文件源码
def plot_streamlines(self, both=False, Hbot=None, Htop=None, R=None, **params):
        R = self.params.R if R is None else R
        Htop = self.params.Htop if Htop is None else Htop
        Hbot = self.params.Hbot if Hbot is None else Hbot
        #ax = plt.axes(xlim=(-R, R), ylim=(-Hbot, Htop))
        dolfin.parameters["allow_extrapolation"] = True
        if both:
            Fel, Fdrag = fields.get_functions("force_pointsize",
                                              "Fel", "Fdrag", **self.sim_params)
            streamlines(patches=[self.polygon_patches(), self.polygon_patches()],
                        R=R, Htop=Htop, Hbot=Hbot,
                        Nx=100, Ny=100, Fel=Fel, Fdrag=Fdrag, **params)
        else:
            streamlines(patches=[self.polygon_patches()],
                        R=R, Htop=Htop, Hbot=Hbot,
                        Nx=100, Ny=100, F=self.F, **params)
        dolfin.parameters["allow_extrapolation"] = False

#        for p in patches:
#            p.set_zorder(100)
#            plt.gca().add_patch(p)
        plt.xlim(-R, R)
        plt.ylim(-Hbot, Htop)
项目:auckland-ai-meetup-x-triage    作者:a-i-joe    | 项目源码 | 文件源码
def plot_crossval_auc(roc_curves):
    cmap = sns.cubehelix_palette(11)
    aucs = []
    ax = plt.axes()
    for fold in roc_curves.keys():
        (f, p) = roc_curves[fold]
        aucs.append(area_under_curve(f, p))
        label_str = "fold {}, roc auc: {:.2f}".format(fold, aucs[-1])
        ax.plot(f, p, label=label_str, color=cmap[fold])
    ax.plot([0, 1], [0, 1], label="random, roc auc: 0.5", color="black")
    ax.legend(loc="lower right")
    plt.xlabel("False positive rate")
    plt.ylabel("True positive rate")
    plt.title(
        "ROC curves across 10 different validation folds(tiny convnet "
        "trained on small datasets)")
    plt.show()
项目:Python_Study    作者:thsheep    | 项目源码 | 文件源码
def bin():
    labels = 'A', 'B', 'C', 'D'
    fracs = [15, 30.55, 44.44, 10]
    explode = [0, 0.1, 0, 0]  # 0.1 ??????
    plt.axes(aspect=1)  # set this , Figure is round, otherwise it is an ellipse
    # autopct ?show percet
    plt.pie(x=fracs, labels=labels, explode=explode, autopct='%3.1f %%',
            shadow=True, labeldistance=1.1, startangle=90, pctdistance=0.6

            )
    '''
    labeldistance?????????????1.1?1.1??????
    autopct??????????%3.1f%%?????????????????
    shadow???????
    startangle??????0????0?????????????????90???????
    pctdistance?????text??????
    patches, l_texts, p_texts????????????p_texts????????l_texts???label???
    '''
    plt.show()
项目:GeHG    作者:livibetter    | 项目源码 | 文件源码
def _blit_draw(self, artists, bg_cache):
    # Handles blitted drawing, which renders only the artists given instead
    # of the entire figure.
    updated_ax = []
    for a in artists:
        # If we haven't cached the background for this axes object, do
        # so now. This might not always be reliable, but it's an attempt
        # to automate the process.
        if a.axes not in bg_cache:
            # get bbox from a.axes.figure instead of a.axes
            bbox = a.axes.figure.bbox
            bg_cache[a.axes] = a.figure.canvas.copy_from_bbox(bbox)
        a.axes.draw_artist(a)
        updated_ax.append(a.axes)

    # After rendering all the needed artists, blit each axes individually.
    for ax in set(updated_ax):
        # get bbox from ax.figure instead of ax
        ax.figure.canvas.blit(ax.figure.bbox)

# MONKEY PATCH!!
项目:GeHG    作者:livibetter    | 项目源码 | 文件源码
def update_animated_heatmap(window, name, axes, im, footer, redraws):

    data = window['data']
    cbmax = window['cbmax']

    MAX = np.max(data)
    im.set_data(data / MAX)

    ax_im, ax = axes
    N = MAX / cbmax
    xlabels = list('{:%}'.format(x) for x in np.arange(5) / 4 * N)
    ax.xaxis.set_ticklabels(xlabels)

    footer.set_text(footer_text(name, *window['range']))

    return redraws
项目:GeHG    作者:livibetter    | 项目源码 | 文件源码
def plot_animated_heatmap(windows, title, ax_props=None, more_props=None):

    fig, im, footer = plot_heatmap(windows[0], title, ax_props, more_props)

    axes = fig.get_axes()
    ax1, ax2 = axes
    redraws = [im, footer, ax1.xaxis, ax1.yaxis, ax2.xaxis, ax2.yaxis]

    anim = animation.FuncAnimation(
        fig,
        update_animated_heatmap,
        frames=windows,
        fargs=(more_props['name'], axes, im, footer, redraws),
        interval=250,
        blit=True,
    )

    return anim,
项目:GeHG    作者:livibetter    | 项目源码 | 文件源码
def plot_barh(raw_data, title, ax_props=None, more_props=None):

    data = raw_data['data']

    fig = plt.figure()
    fig.suptitle(title, fontsize=18)
    rect = np.array(DEFAULT_RECT) + more_props['rect_adjust']
    ax = plt.axes(rect)

    ypos = np.arange(data.size)
    ax.barh(ypos, data, color=GENTOO_PURPLE1, edgecolor=GENTOO_PURPLE2,
            align='center')
    ax.invert_yaxis()
    ax.set(yticks=ypos, **ax_props)
    ax.grid(which='major', axis='x')

    plot_footer(ax, more_props['name'], *raw_data['range'])

    return fig,
项目:GeHG    作者:livibetter    | 项目源码 | 文件源码
def plot_histogram(raw_data, title, ax_props=None, more_props=None):

    data = raw_data['data']

    fig = plt.figure()
    fig.suptitle(title, fontsize=18)
    rect = np.array(DEFAULT_RECT) + more_props['rect_adjust']
    ax = plt.axes(rect)

    bins = [5, 10, 20, 30, 60, 120, 180, 300, 600, 1200, 1800, 3600, 7200,
            10800, 3600 * 5]
    ax.hist(data, bins=bins, normed=True, histtype='step',
            color=GENTOO_PURPLE1, cumulative=True)
    ax.set(**ax_props)
    ax.grid(which='both', axis='both')

    plot_footer(ax, more_props['name'], *raw_data['range'])

    return fig,
项目:radwatch-analysis    作者:bearing    | 项目源码 | 文件源码
def plot_xy(x, y, ax=None, xlabel='Energy [keV]', **kwargs):
    """
    Plot x and y as a spectrum.
    """

    if not ax:
        new_plot = True
        plt.figure()
        ax = plt.axes()
    else:
        new_plot = False

    plt.semilogy(x, y, axes=ax, drawstyle='steps-mid', **kwargs)

    if new_plot:
        plt.xlabel(xlabel)
        plt.ylabel('Counts')

    if 'label' in kwargs:
        plt.legend()
    plt.show()

    return ax
项目:pyEfi    作者:lucid281    | 项目源码 | 文件源码
def main():
    print('plotting data...')
    analogPlot = AnalogPlot(200)

    # set up animation
    fig = plt.figure()
    ax = plt.axes(xlim=(0, 200), ylim=(-1000, 8000))
    a0, = ax.plot([], [])
    a1, = ax.plot([], [])
    anim = animation.FuncAnimation(fig, analogPlot.update,
                                   fargs=(a0, a1),
                                   interval=40,
                                   frames=300,
                                   blit=True)

    plt.show()
    # anim.save('animation.mp4', fps=30,
    #           extra_args=['-vcodec', 'libx264'])

    print('exiting.')


# call main
项目:postlearn    作者:TomAugspurger    | 项目源码 | 文件源码
def plot_roc_curve(y_true, y_score, ax=None):
    '''
    Plot the Receiving Operator Characteristic curved, including the
    Area under the Curve (AUC) score.

    Parameters
    ----------
    y_true : array
    y_score : array
    ax : matplotlib.axes, defaults to new axes

    Returns
    -------
    ax : matplotlib.axes
    '''
    ax = ax or plt.axes()
    auc = metrics.roc_auc_score(y_true, y_score)
    fpr, tpr, _ = metrics.roc_curve(y_true, y_score)
    ax.plot(fpr, tpr)
    ax.annotate('AUC: {:.2f}'.format(auc), (.8, .2))
    ax.plot([0, 1], [0, 1], linestyle='--', color='k')
    return ax
项目:Price-Comparator    作者:Thejas-1    | 项目源码 | 文件源码
def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

    plt.locator_params(axis='y', nbins=3)
    axes = plt.axes()
    axes.yaxis.grid()
    plt.plot(x_values, y_values, 'ro', color='red')
    plt.ylim(ymin=-1.2, ymax=1.2)
    plt.tight_layout(pad=5)
    if x_labels:
        plt.xticks(x_values, x_labels, rotation='vertical')
    if y_labels:
        plt.yticks([-1, 0, 1], y_labels, rotation='horizontal')
    # Pad margins so that markers are not clipped by the axes
    plt.margins(0.2)
    plt.show()

#////////////////////////////////////////////////////////////
#{ Parsing and conversion functions
#////////////////////////////////////////////////////////////
项目:autoreject    作者:autoreject    | 项目源码 | 文件源码
def _epochs_navigation_onclick(event, params):
    """Aux function"""
    import matplotlib.pyplot as plt
    p = params
    here = None
    if event.inaxes == p['back'].ax:
        here = 1
    elif event.inaxes == p['next'].ax:
        here = -1
    elif event.inaxes == p['reject-quit'].ax:
        if p['reject_idx']:
            p['epochs'].drop(p['reject_idx'])
        plt.close(p['fig'])
        plt.close(event.inaxes.get_figure())

    if here is not None:
        p['idx_handler'].rotate(here)
        p['axes_handler'].rotate(here)
        this_idx = p['idx_handler'][0]
        _draw_epochs_axes(this_idx, p['good_ch_idx'], p['bad_ch_idx'],
                          p['data'][this_idx],
                          p['times'], p['axes'], p['title_str'],
                          p['axes_handler'])
        # XXX don't ask me why
        p['axes'][0].get_figure().canvas.draw()
项目:quantdigger    作者:andyzsf    | 项目源码 | 文件源码
def update(self, op):
        for ax in self.axes:
            self.fig.delaxes(ax)
        for c in self.cursors:
            del c
        if op == "scatter":
            print("scatter_analyze")
            self.axes, self.cursors = scatter_analyze(self.fig, self.data)
        elif op == "summary":
            print("summary_analyze")
            self.axes, self.cursors = summary_analyze(self.fig, self.data, self.nbar, 1)
        elif op == "summary2":
            print("summary2_analyze")
            self.axes, self.cursors = summary_analyze(self.fig, self.data, self.nbar, 2)
        elif op == "entry":
            print("entry_analyze") 
            self.axes, self.cursors = entry_analyze(self.fig, self.data, self.nbar)
        elif op == "exit":
            print("exit_analyze")
            self.axes, self.cursors = exit_analyze(self.fig, self.data, self.nbar)
        elif op == "simple":
            self.axes, self.cursors = simple_entry_analyze(self.fig, self.data, self.nbar)
        self.fig.canvas.draw()
项目:Sisyphus    作者:davidbrandfonbrener    | 项目源码 | 文件源码
def plot_hamming_dist(s,W,brec):
    masks = s[:,0,:].T>0
    x_hat = np.zeros(masks.shape)

    for ii in range(masks.shape[1]):
        Weff = W*masks[:,ii]
        x_hat[:,ii] = np.linalg.inv(np.eye(100)-Weff).dot(brec)

    fig = plt.figure()
    plt.pcolormesh(squareform(pdist(np.sign(x_hat[:,:]).T,metric='hamming'))) #,vmax=.3)
    plt.colorbar()
    plt.ylim([0,x_hat.shape[1]])
    plt.xlim([0,x_hat.shape[1]])

    plt.axes().set_aspect('equal')
    plt.title('Hamming Distance Between Putative FPs')
    plt.ylabel('Time')
    plt.xlabel('Time')

    return fig
项目:synchrony    作者:cknd    | 项目源码 | 文件源码
def eplotsetup(experiment,measurename=None,grid_as="graph",subgraph=False):
    """same as plotsetup(), but takes a complete experiment object for convenience"""
    if measurename:
        roi = experiment.measures[measurename].roi
    else:
        measures = set(experiment.measures)
        if len(measures) == 1:
            measurename = measures.pop()
            roi = experiment.measures[measurename].roi
        elif len(measures)>1:
            raise Exception("Experiment has multiple measures, need to supply a measure name.")
        else:
            roi = np.zeros(experiment.network.graph['grid_dimensions'])

    plt.clf()
    plotsetup(experiment.network,experiment.inputc,roi,plt.axes(),grid_as=grid_as,subgraph=subgraph)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

    plt.locator_params(axis='y', nbins=3)
    axes = plt.axes()
    axes.yaxis.grid()
    plt.plot(x_values, y_values, 'ro', color='red')
    plt.ylim(ymin=-1.2, ymax=1.2)
    plt.tight_layout(pad=5)
    if x_labels:
        plt.xticks(x_values, x_labels, rotation='vertical')
    if y_labels:
        plt.yticks([-1, 0, 1], y_labels, rotation='horizontal')
    # Pad margins so that markers are not clipped by the axes
    plt.margins(0.2)
    plt.show()

#////////////////////////////////////////////////////////////
#{ Parsing and conversion functions
#////////////////////////////////////////////////////////////
项目:zorro    作者:C-CINA    | 项目源码 | 文件源码
def printPlot( self, dpi_key = u"plot_dpi" ):
        """
        Any following commands shared amongst all plot functions go here for brevity.
        """
        if 'title' in self.plotDict: 
            self.axes.set_title( self.plotDict['title'] )

        try: self.canvas.updateGeometry()
        except: pass
        if u'plotFile' in self.plotDict and bool( self.plotDict['plotFile'] ):
            if self.plotDict[u'Transparent']:
                color = [0,0,0,0]
            else: 
                color = [1,1,1,1]

            self.canvas.print_figure( self.plotDict[u'plotFile'], dpi=self.plotDict[dpi_key], 
                                     facecolor=color, edgecolor=color ) 
            return self.plotDict[u'plotFile']
项目:zorro    作者:C-CINA    | 项目源码 | 文件源码
def plotPixmap( self ):
        self.fig.clear()
        self.axes = self.fig.add_axes( [0.0, 0.0, 1.0, 1.0] )
        self.axes.hold(True)
        if u'pixmap' in self.plotDict:
            mage = self.axes.imshow( self.plotDict[u'pixmap'], interpolation='sinc' )
            self.axes.set_axis_off()
            if u'boxMask' in self.plotDict and np.any(self.plotDict[u'boxMask']):
                print( "pixmap boxes" )
                #scaleDiff = np.array( self.plotDict['pixmap'].shape ) / np.array( self.plotDict['boxMask'].shape )

                self.axes.imshow( self.plotDict[u'boxMask'], 
                                 extent=mage.get_extent(), interpolation='lanczos' )

        else:
            print( "No pixmap" )

        self.axes.hold(False)
项目:zorro    作者:C-CINA    | 项目源码 | 文件源码
def plotImage( self ):
        self.fig.clear()
        self.axes = self.fig.add_axes( [0.0, 0.0, 1.0, 1.0] )

        if "lowPass" in self.plotDict:
            self.plotDict['image'] = ni.gaussian_filter( self.plotDict['image'], self.plotDict["lowPass"] )
        clim = zorro.util.histClim( self.plotDict['image'], cutoff=1E-4 )
        self.axes.hold(True)
        mage = self.axes.imshow( self.plotDict['image'], vmin=clim[0], vmax=clim[1], interpolation='nearest', 
                         cmap=self.plotDict['image_cmap'] )



        if 'pixelsize' in self.plotDict:
            zorro.util.plotScalebar( mage, self.plotDict['pixelsize'] )
        if bool(self.plotDict['colorbar']):
            self.fig.colorbar( mage, fraction=0.046, pad=0.04)
        self.axes.set_axis_off()
        self.axes.hold(False)

        return self.printPlot( dpi_key=u'image_dpi' )
项目:zorro    作者:C-CINA    | 项目源码 | 文件源码
def plotPolarFFT( self ):
        self.fig.clear()
        self.axes = self.fig.add_axes( [0.0, 0.0, 1.0, 1.0] )
        self.axes.hold(False)

        polarFFTimage = zorro.util.img2polar( np.log10( 1.0 + np.abs( np.fft.fftshift( np.fft.fft2( self.plotDict['image'] )))) )
        if "lowPass" in self.plotDict:
            polarFFTimage = ni.gaussian_filter( polarFFTimage, self.plotDict["lowPass"] )

        FFTclim = zorro.util.ciClim( polarFFTimage, sigma=2.0 )
        mage = self.axes.imshow( polarFFTimage, interpolation='bicubic', vmin=FFTclim[0], vmax=FFTclim[1], 
                         cmap=self.plotDict['image_cmap'] )
        if 'pixlsize' in self.plotDict:
            # Egh, this scalebar is sort of wrong, maybe I should transpose the plot?
            inv_ps = 1.0 / (polarFFTimage.shape[0] * self.plotDict['pixelsize'] )
            zorro.util.plotScalebar( mage, inv_ps, units=u'nm^{-1}' )
        self.axes.set_axis_off()
        if bool(self.plotDict['colorbar']):
            self.fig.colorbar( mage, fraction=0.046, pad=0.04)

        return self.printPlot( dpi_key=u'image_dpi' )                        
    # TODO: render Gautoauto outputs?  Maybe I should make the Gautomatch boxes seperately as a largely 
    # transparent plot, and just add it on top or not?
项目:zorro    作者:C-CINA    | 项目源码 | 文件源码
def plotTranslations( self ):
        # rect is [left,bottom,width,height]
        self.fig.clear()
        self.axes = self.fig.add_axes( [0.12, 0.1, 0.85, 0.85] )
        self.axes.hold(True)


        if 'errorX' in self.plotDict:
            self.axes.errorbar( self.plotDict['translations'][:,1], self.plotDict['translations'][:,0], fmt='k-',
                              xerr=self.plotDict['errorX'], yerr=self.plotDict['errorY'] )
        else:
            self.axes.plot( self.plotDict['translations'][:,1], self.plotDict['translations'][:,0], 'k.-',
                   linewidth=2.0, markersize=16 )
        self.axes.plot( self.plotDict['translations'][0,1], self.plotDict['translations'][0,0], 
                       '.', color='purple', markersize=16 )
        self.axes.set_xlabel( 'X-axis drift (pix)' )
        self.axes.set_ylabel( 'Y-axis drift (pix)' )
        self.axes.axis('equal')
        self.axes.hold(False)

        return self.printPlot( dpi_key=u'plot_dpi' )
项目:PyNIT    作者:dvm-shlee    | 项目源码 | 文件源码
def set_viewaxes(axes):
    """ Set View Axes

    :param axes:
    :return:
    """
    ylim = axes.get_ylim()
    xlim = axes.get_xlim()
    axes.set_ylabel('L', rotation=0, fontsize=20)
    axes.set_xlabel('I', fontsize=20)
    axes.set_facecolor('white')
    axes.tick_params(labeltop=True, labelright=True, labelsize=8)
    axes.grid(False)
    axes.text(xlim[1]/2, ylim[1] * 1.1, 'P', fontsize=20)
    axes.text(xlim[1]*1.1, sum(ylim)/2*1.05, 'R', fontsize=20)
    return axes
项目:BlueLines    作者:JacksYou    | 项目源码 | 文件源码
def scatter_unemployment_poverty_rplot():
    """reates a rplot using the values of Poverty Rate and Unemployment Rate
    iterates through the database and reads all the data in the given headers and creates plots for each data point
    """
    poverty = [(demo.loc[demo['number'] == num, "Poverty Rate"].values[0]) for num in numbers]
    unemployment = [(demo.loc[demo['number'] == num, "Unemployment Rate"].values[0]) for num in numbers]

    df["Unemployment Rate %"] = np.array([float(i.replace("%", "")) for i in unemployment])
    df["Poverty Rate %"] = np.array([float(i) for i in poverty], dtype="float32")

    plot = rplot.RPlot(data= df, x="Poverty Rate %", y="Unemployment Rate %")
    plot.add(rplot.GeomScatter())
    plot.add(rplot.GeomPolyFit(degree=2))
    plot.add(rplot.GeomDensity2D())

    plt.title("Poverty Rate vs. Unemployment Rate by Community")
    plot.render(plt.gcf())

    ax = plt.axes()
    for index, row in df.iterrows():
        ax.annotate(row["Community Name"], (row["Poverty Rate %"], row["Unemployment Rate %"]),
                    size=7,
                    color='darkslategrey')
    plt.show()
项目:spectroscopy    作者:jgoodknight    | 项目源码 | 文件源码
def animate1D(self, fileName, numberOfFrames):   
        "Animate a 1D nuclear wavefunction as it evolves in time"             
        d = self.mySpace.nuclearDimensionality
        if d != 1:
            raise NuclearWavefunction.unplotableNuclearWavefunction()

        plottingAmplitude = np.abs(self.timePositionAmplitude)
        yMin = np.min(plottingAmplitude)
        yMax = np.max(plottingAmplitude)

        fig = plt.figure()
        ax = plt.axes(xlim=(-self.mySpace.xMax, self.mySpace.xMax), ylim = (yMin, yMax))
        line, = ax.plot([], [])
        def init():
            line.set_data([], [])
            return line, 

        def animate(i):
            line.set_data(self.mySpace.xValues, plottingAmplitude[i])
            return line, 

        anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames = numberOfFrames, interval=20, blit=True)
        anim.save(fileName, fps=20)
项目:hylaa    作者:stanleybak    | 项目源码 | 文件源码
def add_aggregation_poly(self, poly_verts, mode_name):
        '''add a polygon that's an aggregation on the waiting list'''

        polys = self.aggregation_mode_to_polys.get(mode_name)

        if polys is None:
            _, edge_col = self.mode_colors.get_edge_face_colors(mode_name)
            edge_col = darker(edge_col)

            polys = collections.PolyCollection([], lw=4, animated=True,
                                               edgecolor=edge_col, facecolor='none')
            self.axes.add_collection(polys)
            self.aggregation_mode_to_polys[mode_name] = polys

        paths = polys.get_paths()

        codes = [Path.MOVETO] + [Path.LINETO] * (len(poly_verts) - 2) + [Path.CLOSEPOLY]
        paths.append(Path(poly_verts, codes))
项目:hylaa    作者:stanleybak    | 项目源码 | 文件源码
def add_waiting_list_poly(self, poly_verts, mode_name):
        '''add a polygon on the waiting list'''

        polys = self.waiting_list_mode_to_polys.get(mode_name)

        if polys is None:
            face_col, edge_col = self.mode_colors.get_edge_face_colors(mode_name)

            polys = collections.PolyCollection([], lw=2, animated=True, alpha=0.3,
                                               edgecolor=edge_col, facecolor=face_col)
            self.axes.add_collection(polys)
            self.waiting_list_mode_to_polys[mode_name] = polys

        paths = polys.get_paths()

        codes = [Path.MOVETO] + [Path.LINETO] * (len(poly_verts) - 2) + [Path.CLOSEPOLY]
        paths.append(Path(poly_verts, codes))
项目:hylaa    作者:stanleybak    | 项目源码 | 文件源码
def del_reachable_polys_from_parent(self, parent):
        '''
        stop drawing all polygons which were reached from a star and previously-
        added with add_reachable_poly_from_star
        '''

        assert isinstance(parent, ContinuousPostParent)

        polys = self.parent_to_polys.pop(parent, None)

        # polys may be none if it was an urgent transition
        if polys is not None:
            polys.remove() # reverses axes.add_collection
            polys.get_paths()[:] = []

        markers = self.parent_to_markers.pop(parent, None)

        if markers is not None:
            markers.remove()
            markers.set_xdata([])
            markers.set_ydata([])
项目:hylaa    作者:stanleybak    | 项目源码 | 文件源码
def _blit_draw(_self, artists, bg_cache):
    'money-patch version of animation._blit_draw'
    # Handles blitted drawing, which renders only the artists given instead
    # of the entire figure.
    updated_ax = []
    for a in artists:
        # If we haven't cached the background for this axes object, do
        # so now. This might not always be reliable, but it's an attempt
        # to automate the process.
        if a.axes not in bg_cache:
            # bg_cache[a.axes] = a.figure.canvas.copy_from_bbox(a.axes.bbox)
            # change here
            bg_cache[a.axes] = a.figure.canvas.copy_from_bbox(a.axes.figure.bbox)
        a.axes.draw_artist(a)
        updated_ax.append(a.axes)

    # After rendering all the needed artists, blit each axes individually.
    for ax in set(updated_ax):
        # and here
        # ax.figure.canvas.blit(ax.bbox)
        ax.figure.canvas.blit(ax.figure.bbox)
项目:neighborhood_mood_aws    作者:jarrellmark    | 项目源码 | 文件源码
def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

    plt.locator_params(axis='y', nbins=3)
    axes = plt.axes()
    axes.yaxis.grid()
    plt.plot(x_values, y_values, 'ro', color='red')
    plt.ylim(ymin=-1.2, ymax=1.2)
    plt.tight_layout(pad=5)
    if x_labels:
        plt.xticks(x_values, x_labels, rotation='vertical')
    if y_labels:
        plt.yticks([-1, 0, 1], y_labels, rotation='horizontal')
    # Pad margins so that markers are not clipped by the axes
    plt.margins(0.2)
    plt.show()

#////////////////////////////////////////////////////////////
#{ Parsing and conversion functions
#////////////////////////////////////////////////////////////
项目:mcplates    作者:ian-r-rose    | 项目源码 | 文件源码
def plot_synthetic_poles( ax=None, title=''):
    if ax is None:
        if proj_type == 'M':
            myax = plt.axes(projection=ccrs.Mollweide(200.-lon_shift))
        elif proj_type == 'O':
            myax = plt.axes(projection = ccrs.Orthographic(200.-lon_shift,30.))
    else:
        myax=ax

    myax.gridlines()

    colorcycle = itertools.cycle(colors)
    lons, lats, ages = path.compute_synthetic_poles(n=100)
    for i in range(len(poles)):
        c = colorcycle.next()
        poles[i].plot(ax, color=c)
        myax.scatter(lons[:, i], lats[:, i], color=c,
                     transform=ccrs.PlateCarree())

    if title != '':
        myax.set_title(title)

    if ax is None:
        plt.savefig("keweenawan_poles_" + str(n_euler_rotations)+".pdf")
项目:mcplates    作者:ian-r-rose    | 项目源码 | 文件源码
def plot_result():

    ax = plt.axes(projection = ccrs.Orthographic(0.,-30.))
    #ax = plt.axes(projection = ccrs.Mollweide(0.))
    ax.gridlines()
    ax.set_global()

    direction_samples = path.euler_directions()
    for directions in direction_samples:
        mcplates.plot.plot_distribution( ax, directions[:,0], directions[:,1])

    pathlons, pathlats = path.compute_synthetic_paths(n=100)
    for pathlon,pathlat in zip(pathlons,pathlats):
        ax.plot(pathlon,pathlat, transform=ccrs.PlateCarree(), color='b', alpha=0.05 )

    for p in lon_lats:
        pole = mcplates.PaleomagneticPole( p[0], p[1], angular_error=10. )
        pole.plot(ax)


    plt.show()
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def plot_discrete(self, show=False, transform=None, axes=None):
        import matplotlib.pyplot as plt
        plt.axes().set_aspect('equal', 'datalim')
        def plot_transformed(vertices, color='g'):
            if transform is None: 
                if axes is None:
                    plt.plot(*vertices.T, color=color)
                else:
                    axes.plot(*vertices.T, color=color)
            else:
                transformed = transform_points(vertices, transform)
                plt.plot(*transformed.T, color=color)
        for i, polygon in enumerate(self.polygons_closed):
            color = ['g','k'][i in self.root]
            plot_transformed(np.column_stack(polygon.boundary.xy), color=color)
        if show: plt.show()
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def plot_entities(self, show=False):
        import matplotlib.pyplot as plt
        plt.axes().set_aspect('equal', 'datalim')
        eformat = {'Line0'  : {'color'  :'g', 'linewidth':1},
                   'Line1'  : {'color'  :'y', 'linewidth':1},
                   'Arc0'   : {'color'  :'r', 'linewidth':1}, 
                   'Arc1'   : {'color'  :'b', 'linewidth':1},
                   'Bezier0': {'color'  :'k', 'linewidth':1},
                   'BSpline0': {'color' :'m', 'linewidth':1},
                   'BSpline1': {'color' :'m', 'linewidth':1}}
        for entity in self.entities:
            discrete = entity.discrete(self.vertices)
            e_key    = entity.__class__.__name__ + str(int(entity.closed))
            plt.plot(discrete[:,0], 
                     discrete[:,1], 
                     **eformat[e_key])
        if show: plt.show()
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def plot_raster(raster, pitch, offset=[0,0]):
    '''
    Plot a raster representation. 

    raster: (n,m) array of booleans, representing filled/empty area
    pitch:  the edge length of a box from raster, in cartesian space
    offset: offset in cartesian space to the lower left corner of the raster grid
    '''
    import matplotlib.pyplot as plt
    plt.axes().set_aspect('equal', 'datalim')
    filled = (np.column_stack(np.nonzero(raster)) * pitch) + offset
    for location in filled:
        plt.gca().add_patch(plt.Rectangle(location, 
                                          pitch, 
                                          pitch, 
                                          facecolor="grey"))
项目:sentiment-analysis    作者:saber1988    | 项目源码 | 文件源码
def plot_with_para_labels(low_dim_embs, para_labels, filename='tsne-para.png'):
    assert low_dim_embs.shape[0] == len(para_labels), "label number must equal embedding number"
    plt.clf()
    plt.figure(figsize=(200, 36))
    axes = plt.axes([0.5, 0.1, 0.4, 0.8])
    axes.scatter(low_dim_embs[:, 0], low_dim_embs[:, 1], marker='o', cmap=plt.cm.seismic, s=80)
    for label, x, y in zip(para_labels, low_dim_embs[:, 0], low_dim_embs[:, 1]):
        plt.annotate(
            label,
            xy=(x, y),
            xytext=(-8, -3),
            textcoords='offset points',
            ha='right',
            va='bottom',
            bbox=None,
            arrowprops=None)
    plt.savefig(filename)
项目:hate-to-hugs    作者:sdoran35    | 项目源码 | 文件源码
def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

    plt.locator_params(axis='y', nbins=3)
    axes = plt.axes()
    axes.yaxis.grid()
    plt.plot(x_values, y_values, 'ro', color='red')
    plt.ylim(ymin=-1.2, ymax=1.2)
    plt.tight_layout(pad=5)
    if x_labels:
        plt.xticks(x_values, x_labels, rotation='vertical')
    if y_labels:
        plt.yticks([-1, 0, 1], y_labels, rotation='horizontal')
    # Pad margins so that markers are not clipped by the axes
    plt.margins(0.2)
    plt.show()

#////////////////////////////////////////////////////////////
#{ Parsing and conversion functions
#////////////////////////////////////////////////////////////
项目:PetroPy    作者:toddheitmann    | 项目源码 | 文件源码
def _edit_lock_toggle(self, event):
        """
        Event handler to check for correct axis associated with
        selected curve. Will allow _draw_curve to function if click is
        in proper axis based on the self._edit_curve property set with
        _curve_pick. Connected on lines 767 and 769 to
        :code:`button_press_event` and :code:`button_release_event`.
        """

        if self._edit_curve and hasattr(event, 'inaxes'):
            if event.inaxes:
                ax_num = np.where(self.axes == event.inaxes)[0]
                if len(ax_num) > 0:
                    curve_num = \
                        self.axes.tolist().index(self._edit_curve.axes)
                    if ax_num == curve_num:
                        self._edit_lock = not self._edit_lock
项目:beepboop    作者:nicolehe    | 项目源码 | 文件源码
def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

    plt.locator_params(axis='y', nbins=3)
    axes = plt.axes()
    axes.yaxis.grid()
    plt.plot(x_values, y_values, 'ro', color='red')
    plt.ylim(ymin=-1.2, ymax=1.2)
    plt.tight_layout(pad=5)
    if x_labels:
        plt.xticks(x_values, x_labels, rotation='vertical')
    if y_labels:
        plt.yticks([-1, 0, 1], y_labels, rotation='horizontal')
    # Pad margins so that markers are not clipped by the axes
    plt.margins(0.2)
    plt.show()

#////////////////////////////////////////////////////////////
#{ Parsing and conversion functions
#////////////////////////////////////////////////////////////
项目:static_study    作者:zzqboy    | 项目源码 | 文件源码
def draw_e():
    ### ????
    dataArr, labelArr = loadDataSet('testSet.txt')
    m = len(dataArr)
    dataMatrix,  labelMat = mat(dataArr), mat(labelArr).transpose()
    b, alphas, choose_all_x, all_alpha, all_b = smoP(dataArr, labelArr, 0.6, 0.001, 40)

    ### ??????
    fig = plt.figure()
    iter_time = len(choose_all_x)
    ax = plt.axes()
    ax.set_ylabel(u'error value')
    ax.set_xlabel(u'iter time')
    ax.set_title(u'svm (zzqboy.com)')
    y = []
    for i in range(iter_time):
        e = compute_all_e(dataMatrix, labelMat, all_alpha[i], all_b[i], m)
        y.append(e)
    ax.plot(range(iter_time), y)
    plt.show()
项目:almond-nnparser    作者:Stanford-Mobisocial-IoT-Lab    | 项目源码 | 文件源码
def show_heatmap(x, y, attention):
    #print attention[:len(y),:len(x)]
    #print attention[:len(y),:len(x)].shape
    #data = np.transpose(attention[:len(y),:len(x)])
    data = attention[:len(y),:len(x)]
    x, y = y, x

    #ax = plt.axes(aspect=0.4)
    ax = plt.axes()
    heatmap = plt.pcolor(data, cmap=plt.cm.Blues)

    xticks = np.arange(len(y)) + 0.5
    xlabels = y
    yticks = np.arange(len(x)) + 0.5
    ylabels = x
    plt.xticks(xticks, xlabels, rotation='vertical')
    ax.set_yticks(yticks)
    ax.set_yticklabels(ylabels)

    # make it look less like a scatter plot and more like a colored table
    ax.tick_params(axis='both', length=0)
    ax.invert_yaxis()
    ax.xaxis.tick_top()

    plt.colorbar(heatmap)

    plt.show()
    #plt.savefig('./attention-out.pdf')