Python pylab 模块,xlim() 实例源码

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

项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def plot_density_map(x, y, xbins, ybins, Nlevels=4, cbar=True, weights=None):

    Z = np.histogram2d(x, y, bins=(xbins, ybins), weights=weights)[0].astype(float).T

    # central values
    lt = get_centers_from_bins(xbins)
    lm = get_centers_from_bins(ybins)
    cX, cY = np.meshgrid(lt, lm)
    X, Y = np.meshgrid(xbins, ybins)

    im = plt.pcolor(X, Y, Z, cmap=plt.cm.Blues)
    plt.contour(cX, cY, Z, levels=nice_levels(Z, Nlevels), cmap=plt.cm.Greys_r)

    if cbar:
        cb = plt.colorbar(im)
    else:
        cb = None
    plt.xlim(xbins[0], xbins[-1])
    plt.ylim(ybins[0], ybins[-1])

    try:
        plt.tight_layout()
    except Exception as e:
        print(e)
    return plt.gca(), cb
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def twoDimensionalScatter(title, title_x, title_y,
                          x, y,
                          lim_x = None, lim_y = None,
                          color = 'b', size = 20, alpha=None):
    """
    Create a two-dimensional scatter plot.

    INPUTS
    """
    pylab.figure()

    pylab.scatter(x, y, c=color, s=size, alpha=alpha, edgecolors='none')

    pylab.xlabel(title_x)
    pylab.ylabel(title_y)
    pylab.title(title)
    if type(color) is not str:
        pylab.colorbar()

    if lim_x:
        pylab.xlim(lim_x[0], lim_x[1])
    if lim_y:
        pylab.ylim(lim_y[0], lim_y[1])

############################################################
项目:nn4nlp-code    作者:neubig    | 项目源码 | 文件源码
def display_data(word_vectors, words, target_words=None):
  target_matrix = word_vectors.copy()
  if target_words:
    target_words = [line.strip().lower() for line in open(target_words)][:2000]
    rows = [words.index(word) for word in target_words if word in words]
    target_matrix = target_matrix[rows,:]
  else:
    rows = np.random.choice(len(word_vectors), size=1000, replace=False)
    target_matrix = target_matrix[rows,:]
  reduced_matrix = tsne(target_matrix, 2);

  Plot.figure(figsize=(200, 200), dpi=100)
  max_x = np.amax(reduced_matrix, axis=0)[0]
  max_y = np.amax(reduced_matrix, axis=0)[1]
  Plot.xlim((-max_x,max_x))
  Plot.ylim((-max_y,max_y))

  Plot.scatter(reduced_matrix[:, 0], reduced_matrix[:, 1], 20);

  for row_id in range(0, len(rows)):
      target_word = words[rows[row_id]]
      x = reduced_matrix[row_id, 0]
      y = reduced_matrix[row_id, 1]
      Plot.annotate(target_word, (x,y))
  Plot.savefig("word_vectors.png");
项目:ndparse    作者:neurodata    | 项目源码 | 文件源码
def display_pr_curve(precision, recall):
    # following examples from sklearn

    # TODO:  f1 operating point

    import pylab as plt
    # Plot Precision-Recall curve
    plt.clf()
    plt.plot(recall, precision, label='Precision-Recall curve')
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.0])
    plt.title('Precision-Recall example: Max f1={0:0.2f}'.format(max_f1))
    plt.legend(loc="lower left")
    plt.show()
项目:astromalign    作者:dstndstn    | 项目源码 | 文件源码
def plotmatchdisthist(M, mas=True, nbins=100, doclf=True, color='b', **kwa):
    import pylab as plt
    if doclf:
        plt.clf()
    R = np.sqrt(M.dra_arcsec**2 + M.ddec_arcsec**2)
    if mas:
        R *= 1000.
        rng = [0, M.rad*1000.]
    else:
        rng = [0, M.rad]
    print 'Match distances: median', np.median(R), 'arcsec'
    n,b,p = plt.hist(R, nbins, range=rng, histtype='step', color=color, **kwa)
    if mas:
        plt.xlabel('Match distance (mas)')
    else:
        plt.xlabel('Match distance (arcsec)')
    plt.xlim(*rng)
    return n,b,p
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot_rectified(self):
        import pylab
        pylab.title('rectified')
        pylab.imshow(self.rectified)

        for line in self.vlines:
            p0, p1 = line
            p0 = self.inv_transform(p0)
            p1 = self.inv_transform(p1)
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='green')

        for line in self.hlines:
            p0, p1 = line
            p0 = self.inv_transform(p0)
            p1 = self.inv_transform(p1)
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='red')

        pylab.axis('image');
        pylab.grid(c='yellow', lw=1)
        pylab.plt.yticks(np.arange(0, self.l, 100.0));
        pylab.xlim(0, self.w)
        pylab.ylim(self.l, 0)
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot_original(self):
        import pylab
        pylab.title('original')
        pylab.imshow(self.data)

        for line in self.lines:
            p0, p1 = line
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='blue', alpha=0.3)

        for line in self.vlines:
            p0, p1 = line
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='green')

        for line in self.hlines:
            p0, p1 = line
            pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='red')

        pylab.axis('image');
        pylab.grid(c='yellow', lw=1)
        pylab.plt.yticks(np.arange(0, self.l, 100.0));
        pylab.xlim(0, self.w)
        pylab.ylim(self.l, 0)
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def _plot_background(self, bgimage):
        import pylab as pl
        # Show the portion of the image behind this facade
        left, right = self.facade_left, self.facade_right
        top, bottom = 0, self.mega_facade.rectified.shape[0]
        if bgimage is not None:
            pl.imshow(bgimage[top:bottom, left:right], extent=(left, right, bottom, top))
        else:
            # Fit the facade in the plot
            y0, y1 = pl.ylim()
            x0, x1 = pl.xlim()
            x0 = min(x0, left)
            x1 = max(x1, right)
            y0 = min(y0, top)
            y1 = max(y1, bottom)
            pl.xlim(x0, x1)
            pl.ylim(y1, y0)
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def plot(self, filename):
        r"""Save an image file of the transfer function.

        This function loads up matplotlib, plots the transfer function and saves.

        Parameters
        ----------
        filename : string
            The file to save out the plot as.

        Examples
        --------

        >>> tf = TransferFunction( (-10.0, -5.0) )
        >>> tf.add_gaussian(-9.0, 0.01, 1.0)
        >>> tf.plot("sample.png")
        """
        import matplotlib
        matplotlib.use("Agg")
        import pylab
        pylab.clf()
        pylab.plot(self.x, self.y, 'xk-')
        pylab.xlim(*self.x_bounds)
        pylab.ylim(0.0, 1.0)
        pylab.savefig(filename)
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def show(self):
        r"""Display an image of the transfer function

        This function loads up matplotlib and displays the current transfer function.

        Parameters
        ----------

        Examples
        --------

        >>> tf = TransferFunction( (-10.0, -5.0) )
        >>> tf.add_gaussian(-9.0, 0.01, 1.0)
        >>> tf.show()
        """
        import pylab
        pylab.clf()
        pylab.plot(self.x, self.y, 'xk-')
        pylab.xlim(*self.x_bounds)
        pylab.ylim(0.0, 1.0)
        pylab.draw()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        pl.plot(self.t1, self.n_A1, 'b--', label='A1: Time Step = 0.05')
        pl.plot(self.t1, self.n_B1, 'b', label='B1: Time Step = 0.05')
        pl.plot(self.t2, self.n_A2, 'g--', label='A2: Time Step = 0.1')
        pl.plot(self.t2, self.n_B2, 'g', label='B2: Time Step = 0.1')
        pl.plot(self.t1, self.n_A1_true, 'r--', label='True A1: Time Step = 0.05')
        pl.plot(self.t1, self.n_B1_true, 'r', label='True B1: Time Step = 0.05')
        pl.plot(self.t2, self.n_A2_true, 'c--', label='True A2: Time Step = 0.1')
        pl.plot(self.t2, self.n_B2_true, 'c', label='True B2: Time Step = 0.1')
        pl.title('Double Decay Probelm-Approximation Compared with True in Defferent Time Steps')
        pl.xlim(0.0, 0.1)
        pl.ylim(0.0, 100.0)
        pl.xlabel('time ($s$)')
        pl.ylabel('Number of Nuclei')
        pl.legend(loc='best', shadow=True, fontsize='small')
        pl.grid(True)
        pl.savefig("computational_physics homework 4(improved-7).png")
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show(self):
#        pl.semilogy(self.theta, self.omega)
#                , label = '$L =%.1f m, $'%self.l + '$dt = %.2f s, $'%self.dt + '$\\theta_0 = %.2f radians, $'%self.theta[0] + '$q = %i, $'%self.q + '$F_D = %.2f, $'%self.F_D + '$\\Omega_D = %.1f$'%self.Omega_D)
        pl.plot(self.theta_phase ,self.omega_phase, '.', label = '$t \\approx 2\\pi n / \\Omega_D$')
        pl.xlabel('$\\theta$ (radians)')
        pl.ylabel('$\\omega$ (radians/s)')
        pl.legend()
#        pl.text(-1.4, 0.3, '$\\omega$ versus $\\theta$ $F_D = 1.2$', fontsize = 'x-large')
        pl.title('Chaotic Regime')
#        pl.show()
#        pl.semilogy(self.time_array, self.delta)
#        pl.legend(loc = 'upper center', fontsize = 'small')
#        pl.xlabel('$time (s)$')
#        pl.ylabel('$\\Delta\\theta (radians)$')
#        pl.xlim(0, self.T)
#        pl.ylim(float(input('ylim-: ')),float(input('ylim+: ')))
#        pl.ylim(1E-11, 0.01)
#        pl.text(4, -0.15, 'nonlinear pendulum - Euler-Cromer method')
#        pl.text(10, 1E-3, '$\\Delta\\theta versus time F_D = 0.5$')
#        pl.title('Simple Harmonic Motion')
        pl.title('Chaotic Regime')
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_log(self):
#        pl.subplot(121)
        pl.semilogy(self.time_array, self.delta, 'c')
        pl.xlabel('$time (s)$')
        pl.ylabel('$\\Delta\\theta$ (radians)')
        pl.xlim(0, self.T)
#        pl.ylim(1E-11, 0.01)
        pl.text(42, 1E-7, '$\\Delta\\theta$ versus time $F_D = 1.2$', fontsize = 'x-large')
        pl.title('Chaotic Regime')
        pl.show()

#    def show_log_sub122(self):
#        pl.subplot(122)
#        pl.semilogy(self.time_array, self.delta, 'g')
#        pl.xlabel('$time (s)$')
#        pl.ylabel('$\\Delta\\theta$ (radians)')
#        pl.xlim(0, self.T)
#        pl.ylim(1E-6, 100)
#        pl.text(20, 1E-5, '$\\Delta\\theta$ versus time $F_D = 1.2$', fontsize = 'x-large')
#        pl.title('Chaotic Regime')
#        pl.show()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_log(self):
#        pl.subplot(121)
        pl.semilogy(self.time_array, self.delta, 'c')
        pl.xlabel('$time (s)$')
        pl.ylabel('$\\Delta\\theta$ (radians)')
        pl.xlim(0, self.T)
#        pl.ylim(1E-11, 0.01)
        pl.text(42, 1E-7, '$\\Delta\\theta$ versus time $F_D = 1.2$', fontsize = 'x-large')
        pl.title('Chaotic Regime')
        pl.show()

#    def show_log_sub122(self):
#        pl.subplot(122)
#        pl.semilogy(self.time_array, self.delta, 'g')
#        pl.xlabel('$time (s)$')
#        pl.ylabel('$\\Delta\\theta$ (radians)')
#        pl.xlim(0, self.T)
#        pl.ylim(1E-6, 100)
#        pl.text(20, 1E-5, '$\\Delta\\theta$ versus time $F_D = 1.2$', fontsize = 'x-large')
#        pl.title('Chaotic Regime')
#        pl.show()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_complex(self):
        font = {'family': 'serif',
                'color':  'k',
                'weight': 'normal',
                'size': 16,
        }
        pl.title('The Trajectory of Tageted Baseball\n with air flow in adiabatic model', fontdict = font)
        pl.plot(self.x, self.y, label = '$v_0 = %.5f m/s$'%self.v0 + ', ' + '$\\theta = %.4f \degree$'%self.theta)
        pl.xlabel('x $m$')
        pl.ylabel('y $m$')
        pl.xlim(0, 300)
        pl.ylim(-100, 20)
        pl.grid()
        pl.legend(loc = 'upper right', shadow = True, fontsize = 'small')
        pl.text(15, -90, 'scan to approach the minimum velocity and corresponding launching angle', fontdict = font)
        pl.show()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_simple(self):
        font = {'family': 'serif',
                'color':  'k',
                'weight': 'normal',
                'size': 16,
        }
        pl.title('The Trajectory of Tageted Baseball\n with air flow in adiabatic model', fontdict = font)
        pl.plot(self.x, self.y, label ='$\\alpha = %.0f \degree$'%self.alpha)
        pl.xlabel('x $m$')
        pl.ylabel('y $m$')
        pl.xlim(0, 400)
        pl.ylim(-100, 200)
        pl.grid()
        pl.legend(loc = 'upper right', shadow = True, fontsize = 'medium')
        pl.text(5, -80, 'trojectories varing with angles of wind', fontdict = font)
        pl.show()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        font = {'family': 'serif',
                'color':  'k',
                'weight': 'normal',
                'size': 14,
        }
        pl.plot(self.x, self.y, 'c', label='firing angle = 45°')
        pl.title('The Trajectory of a Cannon Shell', fontdict = font)
        pl.xlabel('x (k$m$)')
        pl.ylabel('y ($km$)')
        pl.xlim(0, 60)
        pl.ylim(0, 20)
        pl.grid(True)
        pl.legend(loc='upper right', shadow=True, fontsize='large')
        pl.text(41, 16, 'Only with air drag', fontdict = font)
        pl.show()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        font = {'family': 'serif',
                'color':  'k',
                'weight': 'normal',
                'size': 12,
        }
        pl.plot(self.x, self.y, 'c', label='firing angle = 45°')
        pl.title('The Trajectory of a Cannon Shell', fontdict = font)
        pl.xlabel('x (k$m$)')
        pl.ylabel('y ($km$)')
        pl.xlim(0, 60)
        pl.ylim(0, 20)
        pl.grid(True)
        pl.legend(loc='upper right', shadow=True, fontsize='large')
        pl.text(34, 16, '       With both air drag and \n reduced air density-isothermal', fontdict = font)
        pl.show()
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        font = {'family': 'serif',
                'color':  'k',
                'weight': 'normal',
                'size': 12,
        }
        pl.plot(self.x, self.y, 'c', label='firing angle = 45°')
        pl.title('The Trajectory of a Cannon Shell', fontdict = font)
        pl.xlabel('x (k$m$)')
        pl.ylabel('y ($km$)')
        pl.xlim(0, 60)
        pl.ylim(0, 20)
        pl.grid(True)
        pl.legend(loc='upper right', shadow=True, fontsize='large')
        pl.text(34.5, 16, '       With both air drag and \n reduced air density-adiabatic', fontdict = font)
        pl.show()
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def starPlot(targ_ra, targ_dec, data, iso, g_radius, nbhd):
    """Star bin plot"""

    mag_g = data[mag_g_dred_flag]
    mag_r = data[mag_r_dred_flag]

    filter = star_filter(data)

    iso_filter = (iso.separation(mag_g, mag_r) < 0.1)

    # projection of image
    proj = ugali.utils.projector.Projector(targ_ra, targ_dec)
    x, y = proj.sphereToImage(data[filter & iso_filter]['RA'], data[filter & iso_filter]['DEC'])

    plt.scatter(x, y, edgecolor='none', s=3, c='black')
    plt.xlim(0.2, -0.2)
    plt.ylim(-0.2, 0.2)
    plt.gca().set_aspect('equal')
    plt.xlabel(r'$\Delta \alpha$ (deg)')
    plt.ylabel(r'$\Delta \delta$ (deg)')

    plt.title('Stars')
项目:unrolled-gan    作者:musyoku    | 项目源码 | 文件源码
def plot_kde(data, dir=None, filename="kde", color="Greens"):
    if dir is None:
        raise Exception()
    try:
        os.mkdir(dir)
    except:
        pass
    fig = pylab.gcf()
    fig.set_size_inches(16.0, 16.0)
    pylab.clf()
    bg_color  = sns.color_palette(color, n_colors=256)[0]
    ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2)
    ax.set_axis_bgcolor(bg_color)
    kde = ax.get_figure()
    pylab.xlim(-4, 4)
    pylab.ylim(-4, 4)
    kde.savefig("{}/{}.png".format(dir, filename))
项目:unrolled-gan    作者:musyoku    | 项目源码 | 文件源码
def plot_kde(data, dir=None, filename="kde", color="Greens"):
    if dir is None:
        raise Exception()
    try:
        os.mkdir(dir)
    except:
        pass
    fig = pylab.gcf()
    fig.set_size_inches(16.0, 16.0)
    pylab.clf()
    bg_color  = sns.color_palette(color, n_colors=256)[0]
    ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2)
    ax.set_axis_bgcolor(bg_color)
    kde = ax.get_figure()
    pylab.xlim(-4, 4)
    pylab.ylim(-4, 4)
    kde.savefig("{}/{}".format(dir, filename))
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseNormObject(self):
        shape = (2*self.extent, 2*self.extent)
        pylab.ion()
        pylab.clf()
        #pylab.set_cmap("bone")
        pylab.hot()
        pylab.title("image: %s" % self.fitsFile)
        pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
        pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
        pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
        pylab.colorbar()
        pylab.ylim(-1, 2*self.extent)
        pylab.xlim(-1, 2*self.extent)
        pylab.xlabel("Pixels")
        pylab.ylabel("Pixels")
        pylab.show()
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseNormObject(self):
        shape = (2*self.extent, 2*self.extent)
        pylab.ion()
        pylab.clf()
        #pylab.set_cmap("bone")
        pylab.hot()
        pylab.title("image: %s" % self.fitsFile)
        pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
        pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
        pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
        pylab.colorbar()
        pylab.ylim(-1, 2*self.extent)
        pylab.xlim(-1, 2*self.extent)
        pylab.xlabel("Pixels")
        pylab.ylabel("Pixels")
        pylab.show()
项目:LSGAN    作者:musyoku    | 项目源码 | 文件源码
def plot_kde(data, dir=None, filename="kde", color="Greens"):
    if dir is None:
        raise Exception()
    try:
        os.mkdir(dir)
    except:
        pass
    fig = pylab.gcf()
    fig.set_size_inches(16.0, 16.0)
    pylab.clf()
    bg_color  = sns.color_palette(color, n_colors=256)[0]
    ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2)
    ax.set_axis_bgcolor(bg_color)
    kde = ax.get_figure()
    pylab.xlim(-4, 4)
    pylab.ylim(-4, 4)
    kde.savefig("{}/{}.png".format(dir, filename))
项目:LSGAN    作者:musyoku    | 项目源码 | 文件源码
def plot_kde(data, dir=None, filename="kde", color="Greens"):
    if dir is None:
        raise Exception()
    try:
        os.mkdir(dir)
    except:
        pass
    fig = pylab.gcf()
    fig.set_size_inches(16.0, 16.0)
    pylab.clf()
    bg_color  = sns.color_palette(color, n_colors=256)[0]
    ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2)
    ax.set_axis_bgcolor(bg_color)
    kde = ax.get_figure()
    pylab.xlim(-4, 4)
    pylab.ylim(-4, 4)
    kde.savefig("{}/{}".format(dir, filename))
项目:bokeh_roc_slider    作者:brianray    | 项目源码 | 文件源码
def plot_multiple_rocs_separate(rocList,title='', labels = None, equal_aspect = True):
    """ Plot multiples ROC curves as separate at the same painting area. """
    pylab.clf()
    pylab.title(title)
    for ix, r in enumerate(rocList):
        ax = pylab.subplot(4,4,ix+1)
        pylab.ylim((0,1))
        pylab.xlim((0,1))
        ax.set_yticklabels([])
        ax.set_xticklabels([])
        if equal_aspect:
            cax = pylab.gca()
            cax.set_aspect('equal')

        if not labels:
            labels = ['' for x in rocList]

        pylab.text(0.2,0.1,labels[ix],fontsize=8)
        pylab.plot([x[0] for x in r.derived_points],[y[1] for y in r.derived_points], 'r-',linewidth=2)

    pylab.show()
项目:bokeh_roc_slider    作者:brianray    | 项目源码 | 文件源码
def plot(self,title='',include_baseline=False,equal_aspect=True):
        """ Method that generates a plot of the ROC curve
            Parameters:
                title: Title of the chart
                include_baseline: Add the baseline plot line if it's True
                equal_aspect: Aspects to be equal for all plot
        """

        pylab.clf()
        pylab.plot([x[0] for x in self.derived_points], [y[1] for y in self.derived_points], self.linestyle)
        if include_baseline:
            pylab.plot([0.0,1.0], [0.0,1.0],'k-.')
        pylab.ylim((0,1))
        pylab.xlim((0,1))
        pylab.xticks(pylab.arange(0,1.1,.1))
        pylab.yticks(pylab.arange(0,1.1,.1))
        pylab.grid(True)
        if equal_aspect:
            cax = pylab.gca()
            cax.set_aspect('equal')
        pylab.xlabel('1 - Specificity')
        pylab.ylabel('Sensitivity')
        pylab.title(title)

        pylab.show()
项目:spiking-ratslam    作者:bjkomer    | 项目源码 | 文件源码
def data_loop(self):
        import pylab
        fig = pylab.figure()
        pylab.ion()

        while True:
            fig.clear()
            #pylab.plot(self.t[np.where(self.on==0)])
            hz = 1000000 / self.delta 
            pylab.hist(hz, 50, range=(800, 1200))
            pylab.xlim(500, 1500)
            pylab.ylim(0, 100)
            self.delta = self.delta[:0]

            fig.canvas.draw()
            fig.canvas.flush_events()
项目:AdK_analysis    作者:orbeckst    | 项目源码 | 文件源码
def plot_coverage(db,use_blacklist=True):
    """Plot the total covrage of the unbiased histogram.

    >>> db = setup(pmfonly=True)
    >>> db.add_metadata()
    >>> plot_coverage(db)

    Simple hard-coded plotting routine. Adds two dots for the end
    points and focuses on the interesting region.

    db              pmfonly db
    use_blacklist   True: filter all files that appear in the blacklist [default]
    """
    from pylab import clf,plot,xlim,ylim,title
    if use_blacklist:
        print "Excluding anything listed in the blacklist (i.e. restricting to __meta__)"
        selection = db.selection("SELECT * FROM __data__")
    else:
        selection = db
    selection.plot(mode="reldev")
    #title(r'Umbrella sampling coverage: ${N}/{\langle{N}\rangle} - 1$')
    make_canonical_plot()
项目:AdK_analysis    作者:orbeckst    | 项目源码 | 文件源码
def make_canonical_plot(NMP_lim=(39,76),LID_lim=(99,154),
                        c1AKE=config.angles['1AKE'],
                        c4AKE=config.angles['4AKE'],
                        xray=True):
    """Scale current figure to default limits and plot the positions of 1AKE and 4AKE.

    The points for the end states are taken from txt/x-ray_angles.txt.

    If xray=True then add locations of the X-ray structures; this is
    the same as running plot_xary_structures().
    """
    import pylab
    if xray:
        plot_xray_structures()
    pylab.plot([c1AKE[0],c4AKE[0]], [c1AKE[1],c4AKE[1]], 'sw', ms=12, alpha=0.8)
    pylab.xlim(NMP_lim)
    pylab.ylim(LID_lim)
项目:livespin    作者:biocompibens    | 项目源码 | 文件源码
def plot(self, outpath=''):
        pylab.figure(figsize = (17,10))
        diff = self.f2-self.f3
        pylab.subplot(2,1,1)
        pylab.plot(range(self.lengthSeq), self.f2, 'r-', label = "f2")
        pylab.plot(range(self.lengthSeq), self.f3, 'g-', label = "f3")
        pylab.xlim([0., self.lengthSeq])
        pylab.tick_params(axis='both', which='major', labelsize=25)
        pylab.subplot(2,1,2)

        diff2 = diff/self.f3
        diff2 /= np.max(diff2)
        pylab.plot(range(self.lengthSeq), diff2, 'b-', label = "Rescaled (by max) difference / f3")
        pylab.xlabel("Temps (en images)", fontsize = 25)
        pylab.tick_params(axis='both', which='major', labelsize=25)
        pylab.xlim([0., self.lengthSeq])
        #pylab.legend(loc= 2, prop = {'size':15})
        pylab.savefig(outpath)
        pylab.close()
项目:livespin    作者:biocompibens    | 项目源码 | 文件源码
def plotAgainstGFP_hist2d(self):
        fig1 = pylab.figure(figsize = (20, 15))
        print len(self.GFP)
        for i in xrange(min(len(data.cat), 4)):
            print len(self.GFP[self.categories == i])
            vect = []
            pylab.subplot(2,2,i+1)
            pop = self.GFP[self.categories == i]
            print "cat", i, "n pop", len(self.GFP[(self.categories == i) & (self.GFP > -np.log(12.5))])
            H, xedges, yedges = np.histogram2d(self.angles[self.categories == i], self.GFP[self.categories == i], bins = 10)
            hist = pylab.hist2d(self.GFP[self.categories == i], self.angles[self.categories == i], bins = 10, cmap = pylab.cm.Reds, normed = True)
            pylab.clim(0.,0.035)
            pylab.colorbar()
            pylab.title(data.cat[i])
            pylab.xlabel('GFP score')
            pylab.ylabel('Angle (degree)')
            pylab.xlim([-4.2, -1])
        pylab.show()
项目:livespin    作者:biocompibens    | 项目源码 | 文件源码
def bootstrap_extradata(self, nBoot, extradataA, nbins = 20):
        pops =[]
        meanpop = [[] for i in data.cat]
        pylab.figure(figsize = (14,14))
        for i in xrange(min(4, len(extradataA))):
            #pylab.subplot(2,2,i+1)
            if  i ==0:
                pylab.title("Bootstrap on means", fontsize = 20.)
            pop = extradataA[i]# & (self.GFP > 2000)]#
            for index in xrange(nBoot):
                newpop = np.random.choice(pop, size=len(pop), replace=True)

                #meanpop[i].append(np.mean(newpop))
            pops.append(newpop)
            pylab.legend()
        #pylab.title(cat[i])
            pylab.xlabel("Angle(degree)", fontsize = 15)
            pylab.xlim([0., 90.])
        for i in xrange(len(extradataA)):
            for j in xrange(i+1, len(extradataA)):
                statT, pvalue = scipy.stats.ttest_ind(pops[i], pops[j], equal_var=False)
                print "cat{0} & cat{1} get {2} ({3})".format(i,j, pvalue,statT)
        pylab.savefig("/users/biocomp/frose/frose/Graphics/FINALRESULTS-diff-f3/mean_nBootstrap{0}_bins{1}_GFPsup{2}_FLO_{3}.png".format(nBoot, nbins, 'all', randint(0,999)))
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_waveforms_clusters(data, halo, threshold, templates, amps_lim, n_curves=200, save=False):

    nb_templates = templates.shape[1]
    n_panels     = numpy.ceil(numpy.sqrt(nb_templates))
    mask         = numpy.where(halo > -1)[0]
    clust_idx    = numpy.unique(halo[mask])
    fig          = pylab.figure()    
    square       = True
    center       = len(data[0] - 1)//2
    for count, i in enumerate(xrange(nb_templates)):
        if square:
            pylab.subplot(n_panels, n_panels, count + 1)
            if (numpy.mod(count, n_panels) != 0):
                pylab.setp(pylab.gca(), yticks=[])
            if (count < n_panels*(n_panels - 1)):
                pylab.setp(pylab.gca(), xticks=[])

        subcurves = numpy.where(halo == clust_idx[count])[0]
        for k in numpy.random.permutation(subcurves)[:n_curves]:
            pylab.plot(data[k], '0.5')

        pylab.plot(templates[:, count], 'r')        
        pylab.plot(amps_lim[count][0]*templates[:, count], 'b', alpha=0.5)
        pylab.plot(amps_lim[count][1]*templates[:, count], 'b', alpha=0.5)

        xmin, xmax = pylab.xlim()
        pylab.plot([xmin, xmax], [-threshold, -threshold], 'k--')
        pylab.plot([xmin, xmax], [threshold, threshold], 'k--')
        #pylab.ylim(-1.5*threshold, 1.5*threshold)
        ymin, ymax = pylab.ylim()
        pylab.plot([center, center], [ymin, ymax], 'k--')
        pylab.title('Cluster %d' %i)

    if nb_templates > 0:
        pylab.tight_layout()
    if save:
        pylab.savefig(os.path.join(save[0], 'waveforms_%s' %save[1]))
        pylab.close()
    else:
        pylab.show()
    del fig
项目:seqhawkes    作者:mlukasik    | 项目源码 | 文件源码
def align_subplots(
    N,
    M,
    xlim=None,
    ylim=None,
    ):
    """make all of the subplots have the same limits, turn off unnecessary ticks"""

    # find sensible xlim,ylim

    if xlim is None:
        xlim = [np.inf, -np.inf]
        for i in range(N * M):
            pb.subplot(N, M, i + 1)
            xlim[0] = min(xlim[0], pb.xlim()[0])
            xlim[1] = max(xlim[1], pb.xlim()[1])
    if ylim is None:
        ylim = [np.inf, -np.inf]
        for i in range(N * M):
            pb.subplot(N, M, i + 1)
            ylim[0] = min(ylim[0], pb.ylim()[0])
            ylim[1] = max(ylim[1], pb.ylim()[1])

    for i in range(N * M):
        pb.subplot(N, M, i + 1)
        pb.xlim(xlim)
        pb.ylim(ylim)
        if i % M:
            pb.yticks([])
        else:
            removeRightTicks()
        if i < M * (N - 1):
            pb.xticks([])
        else:
            removeUpperTicks()
项目:seqhawkes    作者:mlukasik    | 项目源码 | 文件源码
def align_subplot_array(axes, xlim=None, ylim=None):
    """
    Make all of the axes in the array hae the same limits, turn off unnecessary ticks
    use pb.subplots() to get an array of axes
    """

    # find sensible xlim,ylim

    if xlim is None:
        xlim = [np.inf, -np.inf]
        for ax in axes.flatten():
            xlim[0] = min(xlim[0], ax.get_xlim()[0])
            xlim[1] = max(xlim[1], ax.get_xlim()[1])
    if ylim is None:
        ylim = [np.inf, -np.inf]
        for ax in axes.flatten():
            ylim[0] = min(ylim[0], ax.get_ylim()[0])
            ylim[1] = max(ylim[1], ax.get_ylim()[1])

    (N, M) = axes.shape
    for (i, ax) in enumerate(axes.flatten()):
        ax.set_xlim(xlim)
        ax.set_ylim(ylim)
        if i % M:
            ax.set_yticks([])
        else:
            removeRightTicks(ax)
        if i < M * (N - 1):
            ax.set_xticks([])
        else:
            removeUpperTicks(ax)
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot_facade_cuts(self):

        facade_sig = self.facade_edge_scores.sum(0)
        facade_cuts = find_facade_cuts(facade_sig, dilation_amount=self.facade_merge_amount)
        mu = np.mean(facade_sig)
        sigma = np.std(facade_sig)

        w = self.rectified.shape[1]
        pad=10

        gs1 = pl.GridSpec(5, 5)
        gs1.update(wspace=0.5, hspace=0.0)  # set the spacing between axes.

        pl.subplot(gs1[:3, :])
        pl.imshow(self.rectified)
        pl.vlines(facade_cuts, *pl.ylim(), lw=2, color='black')
        pl.axis('off')
        pl.xlim(-pad, w+pad)

        pl.subplot(gs1[3:, :], sharex=pl.gca())
        pl.fill_between(np.arange(w), 0, facade_sig, lw=0, color='red')
        pl.fill_between(np.arange(w), 0, np.clip(facade_sig, 0, mu+sigma), color='blue')
        pl.plot(np.arange(w), facade_sig, color='blue')

        pl.vlines(facade_cuts, facade_sig[facade_cuts], pl.xlim()[1], lw=2, color='black')
        pl.scatter(facade_cuts, facade_sig[facade_cuts])

        pl.axis('off')

        pl.hlines(mu, 0, w, linestyle='dashed', color='black')
        pl.text(0, mu, '$\mu$ ', ha='right')

        pl.hlines(mu + sigma, 0, w, linestyle='dashed', color='gray',)
        pl.text(0, mu + sigma, '$\mu+\sigma$ ', ha='right')
        pl.xlim(-pad, w+pad)
项目:merlin    作者:CSTR-Edinburgh    | 项目源码 | 文件源码
def generate_plot(self,filename,title='',xlabel='',ylabel='',xlim=None,ylim=None):

        logger = logging.getLogger("plotting")
        logger.debug('MultipleSeriesPlot.generate_plot')

        # a plot with one or more time series sharing a common x axis:
        # e.g., the training error and the validation error plotted against epochs

        # sort the data series and make sure they are consistent
        self.sort_and_validate()

        # if there is a plot already in existence, we will clear it and re-use it;
        # this avoids creating extraneous figures which will stay in memory
        # (even if we are no longer referencing them)
        if self.plot:
            self.plot.clf()
        else:
            # create a plot
            self.plot = plt.figure()

        splt = self.plot.add_subplot(1, 1, 1)
        splt.set_title(title)
        splt.set_xlabel(xlabel)
        splt.set_ylabel(ylabel)

        if xlim:
            pylab.xlim(xlim)
        if ylim:
            pylab.ylim(ylim)

        for series_name,data_points in self.data.items():
            xpoints=numpy.asarray([seq[0] for seq in data_points])
            ypoints=numpy.asarray([seq[1] for seq in data_points])
            line, = splt.plot(xpoints, ypoints, '-', linewidth=2)
            logger.debug('set_label for %s' % series_name)
            line.set_label(series_name)

        splt.legend()

        # TO DO - better filename configuration for plots
        self.plot.savefig(filename)
项目:multi-contact-zmp    作者:stephane-caron    | 项目源码 | 文件源码
def __init__(self):
        pylab.ion()
        self.com_real = []
        self.com_ref = []
        self.support_areas = []
        self.xlabel = "$y$ (m)"
        self.ylabel = "$x$ (m)"
        self.xlim = (-0.6, 0.1)
        self.ylim = (0. - 0.05, 1.4 + 0.05)
        self.zmp_real = []
        self.zmp_ref = []
项目:multi-contact-zmp    作者:stephane-caron    | 项目源码 | 文件源码
def plot_com(self):
        pylab.plot(
            [-p[1] for p in self.com_real], [p[0] for p in self.com_real],
            'g-', lw=2)
        pylab.plot(
            [-p[1] for p in self.com_ref], [p[0] for p in self.com_ref],
            'k--', lw=1)
        pylab.legend(('$p_G$', '$p_G^{ref}$'), loc='upper right')
        pylab.grid(False)
        pylab.xlim(self.xlim)
        pylab.ylim(self.ylim)
        pylab.xlabel(self.xlabel)
        pylab.ylabel(self.ylabel)
        pylab.title("COM trajectory")
项目:multi-contact-zmp    作者:stephane-caron    | 项目源码 | 文件源码
def plot_zmp(self):
        pylab.plot(
            [-p[1] for p in self.zmp_real], [p[0] for p in self.zmp_real],
            'r-', lw=2)
        pylab.plot(
            [-p[1] for p in self.zmp_ref], [p[0] for p in self.zmp_ref],
            'k--', lw=1)
        pylab.legend(('$p_Z$', '$p_Z^{ref}$'), loc='upper right')
        pylab.grid(False)
        pylab.xlim(self.xlim)
        pylab.ylim(self.ylim)
        pylab.xlabel(self.xlabel)
        pylab.ylabel(self.ylabel)
        pylab.title("ZMP trajectory")
项目:multi-contact-zmp    作者:stephane-caron    | 项目源码 | 文件源码
def plot_support_areas(self, indices=None):
        if indices is None:
            indices = range(len(self.support_areas))
        for i in indices:
            vertices, rays = self.support_areas[i]
            vertices_3d = _convert_cone2d_to_vertices(vertices, rays)
            vertices = [[-v[1], v[0]] for v in vertices_3d]
            plot_polygon(vertices, color='g', fill=None, lw=2)
        pylab.xlim(self.xlim)
        pylab.ylim(self.ylim)
项目:MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python    作者:tiagomestreteixeira    | 项目源码 | 文件源码
def displayRetirementWithMonthsAndRates(monthlies, rates, terms):
    plt.figure('retireBoth')
    plt.clf()
    plt.xlim(30 * 12, 40 * 12)
    for monthly in monthlies:
        for rate in rates:
            xvals, yvals = retire(monthly, rate, terms)
            plt.plot(xvals, yvals,
                     label='retire:' + str(monthly) + ':' + str(int(rate * 100)))
            plt.legend(loc='upper left')
项目:dynamic-walking    作者:stephane-caron    | 项目源码 | 文件源码
def test_dT_impact(xvals, f, nmpc, sim, start=0.1, end=0.8, step=0.02, ymax=200,
                   sample_size=100, label=None):
    """Used to generate Figure XX of the paper."""
    c = raw_input("Did you remove iter/time caps in IPOPT settings? [y/N] ")
    if c.lower() not in ['y', 'yes']:
        print "Then go ahead and do it."
        return
    stats = [Statistics() for _ in xrange(len(xvals))]
    fails = [0. for _ in xrange(len(xvals))]
    pylab.ion()
    pylab.clf()
    for (i, dT) in enumerate(xvals):
        f(dT)
        for _ in xrange(sample_size):
            nmpc.on_tick(sim)
            if 'Solve' in nmpc.nlp.return_status:
                stats[i].add(nmpc.nlp.solve_time)
            else:  # max CPU time exceeded, infeasible problem detected, ...
                fails[i] += 1.
    yvals = [1000 * ts.avg if ts.avg is not None else 0. for ts in stats]
    yerr = [1000 * ts.std if ts.std is not None else 0. for ts in stats]
    pylab.bar(
        xvals, yvals, width=step, yerr=yerr, color='y', capsize=5,
        align='center', error_kw={'capsize': 5, 'elinewidth': 5})
    pylab.xlim(start - step / 2, end + step / 2)
    pylab.ylim(0, ymax)
    pylab.grid(True)
    if label is not None:
        pylab.xlabel(label, fontsize=24)
    pylab.ylabel('Comp. time (ms)', fontsize=20)
    pylab.tick_params(labelsize=16)
    pylab.twinx()
    yfails = [100. * fails[i] / sample_size for i in xrange(len(xvals))]
    pylab.plot(xvals, yfails, 'ro', markersize=12)
    pylab.plot(xvals, yfails, 'r--', linewidth=3)
    pylab.xlim(start - step / 2, end + step / 2)
    pylab.ylabel("Failure rate [%]", fontsize=20)
    pylab.tight_layout()
项目:world_merlin    作者:pbaljeka    | 项目源码 | 文件源码
def generate_plot(self,filename,title='',xlabel='',ylabel='',xlim=None,ylim=None):

        logger = logging.getLogger("plotting")
        logger.debug('MultipleSeriesPlot.generate_plot')

        # a plot with one or more time series sharing a common x axis:
        # e.g., the training error and the validation error plotted against epochs

        # sort the data series and make sure they are consistent
        self.sort_and_validate()

        # if there is a plot already in existence, we will clear it and re-use it;
        # this avoids creating extraneous figures which will stay in memory
        # (even if we are no longer referencing them)
        if self.plot:
            self.plot.clf()
        else:
            # create a plot
            self.plot = plt.figure()

        splt = self.plot.add_subplot(1, 1, 1)
        splt.set_title(title)
        splt.set_xlabel(xlabel)
        splt.set_ylabel(ylabel)

        if xlim:
            pylab.xlim(xlim)
        if ylim:
            pylab.ylim(ylim)

        for series_name,data_points in self.data.iteritems():
            xpoints=numpy.asarray([seq[0] for seq in data_points])
            ypoints=numpy.asarray([seq[1] for seq in data_points])
            line, = splt.plot(xpoints, ypoints, '-', linewidth=2)
            logger.debug('set_label for %s' % series_name)
            line.set_label(series_name)

        splt.legend()

        # TO DO - better filename configuration for plots
        self.plot.savefig(filename)
项目:mimicry.ai    作者:fizerkhan    | 项目源码 | 文件源码
def generate_plot(self,filename,title='',xlabel='',ylabel='',xlim=None,ylim=None):

        logger = logging.getLogger("plotting")
        logger.debug('MultipleSeriesPlot.generate_plot')

        # a plot with one or more time series sharing a common x axis:
        # e.g., the training error and the validation error plotted against epochs

        # sort the data series and make sure they are consistent
        self.sort_and_validate()

        # if there is a plot already in existence, we will clear it and re-use it;
        # this avoids creating extraneous figures which will stay in memory
        # (even if we are no longer referencing them)
        if self.plot:
            self.plot.clf()
        else:
            # create a plot
            self.plot = plt.figure()

        splt = self.plot.add_subplot(1, 1, 1)
        splt.set_title(title)
        splt.set_xlabel(xlabel)
        splt.set_ylabel(ylabel)

        if xlim:
            pylab.xlim(xlim)
        if ylim:
            pylab.ylim(ylim)

        for series_name,data_points in self.data.iteritems():
            xpoints=numpy.asarray([seq[0] for seq in data_points])
            ypoints=numpy.asarray([seq[1] for seq in data_points])
            line, = splt.plot(xpoints, ypoints, '-', linewidth=2)
            logger.debug('set_label for %s' % series_name)
            line.set_label(series_name)

        splt.legend()

        # TO DO - better filename configuration for plots
        self.plot.savefig(filename)
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        pl.plot(self.t, self.n_A1, 'b--', label='A1: Time Constant = 1')
        pl.plot(self.t, self.n_B1, 'g', label='B1: Time Constant = 2')
        pl.plot(self.t, self.n_A2, 'k--', label='A2: Time Constant = 1')
        pl.plot(self.t, self.n_B2, 'c', label='B2: Time Constant = 2')
        pl.plot(self.t, self.n_A3, 'm--', label='A3: Time Constant = 1')
        pl.plot(self.t, self.n_B3, 'y', label='B3: Time Constant = 2')
        pl.title('Double Decay Probelm - Nuclei with Different Time Constans')
        pl.xlim(0.0, 5.0)
        pl.ylim(0.0, 100.0)
        pl.xlabel('time ($s$)')
        pl.ylabel('Number of Nuclei')
        pl.legend(loc='upper right', shadow=True, fontsize='small')
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        pl.plot(self.t, self.n_A, 'b--', label='Number of Nuclei A: Time Constant = 1')
        pl.plot(self.t, self.n_B, 'g', label='Number of Nuclei B: Time Constant = 2')
        pl.title('Double Decay Probelm - Nuclei with Different Time Constans')
        pl.xlim(0.0, 5.0)
        pl.ylim(0.0, 100.0)
        pl.xlabel('time ($s$)')
        pl.ylabel('Number of Nuclei')
        pl.legend(loc='best', shadow=True)
项目:computational_physics_N2014301020117    作者:yukangnineteen    | 项目源码 | 文件源码
def show_results(self):
        pl.plot(self.t, self.n_A, 'b--', label='Number of Nuclei A')
        pl.plot(self.t, self.n_B, 'g', label='Number of Nuclei B')
        pl.title('Double Decay Probelm-Situation 1')
        pl.xlim(0.0, 5.0)
        pl.ylim(0.0, 100.0)
        pl.xlabel('time ($s$)')
        pl.ylabel('Number of Nuclei')
        pl.legend(loc='best', shadow=True)