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

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

项目:melanoma-transfer    作者:learningtitans    | 项目源码 | 文件源码
def calc_auc(y_pred_proba, labels, exp_run_folder, classifier, fold):

    auc = roc_auc_score(labels, y_pred_proba)
    fpr, tpr, thresholds = roc_curve(labels, y_pred_proba)
    curve_roc = np.array([fpr, tpr])
    dataile_id = open(exp_run_folder+'/data/roc_{}_{}.txt'.format(classifier, fold), 'w+')
    np.savetxt(dataile_id, curve_roc)
    dataile_id.close()
    plt.plot(fpr, tpr, label='ROC curve: AUC={0:0.2f}'.format(auc))
    plt.xlabel('1-Specificity')
    plt.ylabel('Sensitivity')
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.0])
    plt.grid(True)
    plt.title('ROC Fold {}'.format(fold))
    plt.legend(loc="lower left")
    plt.savefig(exp_run_folder+'/data/roc_{}_{}.pdf'.format(classifier, fold), format='pdf')
    return auc
项目:hippylib    作者:hippylib    | 项目源码 | 文件源码
def plot_pts(points, values, colorbar=True, subplot_loc=None, mytitle=None, show_axis='on', vmin=None, vmax=None, xlim=(0,1), ylim=(0,1)):
    if subplot_loc is not None:
        plt.subplot(subplot_loc)

    pp = plt.scatter(points[:,0], points[:,1], c=values.get_local(), marker=",", s=20, vmin=vmin, vmax=vmax)

    plt.axis(show_axis)

    if colorbar:
        plt.colorbar(pp, fraction=.1, pad=0.2)
    else:
        plt.gca().set_aspect('equal')

    if mytitle is not None:
        plt.title(mytitle, fontsize=20)

    if xlim is not None:
        plt.xlim(xlim)

    if ylim is not None:
        plt.ylim(ylim)

    return pp
项目:fingerprint-securedrop    作者:freedomofpress    | 项目源码 | 文件源码
def plot_ROC(test_labels, test_predictions):
    fpr, tpr, thresholds = metrics.roc_curve(
        test_labels, test_predictions, pos_label=1)
    auc = "%.2f" % metrics.auc(fpr, tpr)
    title = 'ROC Curve, AUC = '+str(auc)
    with plt.style.context(('ggplot')):
        fig, ax = plt.subplots()
        ax.plot(fpr, tpr, "#000099", label='ROC curve')
        ax.plot([0, 1], [0, 1], 'k--', label='Baseline')
        plt.xlim([0.0, 1.0])
        plt.ylim([0.0, 1.05])
        plt.xlabel('False Positive Rate')
        plt.ylabel('True Positive Rate')
        plt.legend(loc='lower right')
        plt.title(title)
    return fig
项目:HousePricePredictionKaggle    作者:Nuwantha    | 项目源码 | 文件源码
def get_feature_importance(list_of_features):
    n_estimators=10000
    random_state=0
    n_jobs=4
    x_train=data_frame[list_of_features]
    y_train=data_frame.iloc[:,-1]
    feat_labels= data_frame.columns[1:]
    forest = BaggingRegressor(n_estimators=n_estimators,random_state=random_state,n_jobs=n_jobs) 
    forest.fit(x_train,y_train) 
    importances=forest.feature_importances_ 
    indices = np.argsort(importances)[::-1]


    for f in range(x_train.shape[1]):
        print("%2d) %-*s %f" % (f+1,30,feat_labels[indices[f]],
                                        importances[indices[f]]))


    plt.title("Feature Importance")
    plt.bar(range(x_train.shape[1]),importances[indices],color='lightblue',align='center')
    plt.xticks(range(x_train.shape[1]),feat_labels[indices],rotation=90)
    plt.xlim([-1,x_train.shape[1]])
    plt.tight_layout()
    plt.show()
项目:almond-nnparser    作者:Stanford-Mobisocial-IoT-Lab    | 项目源码 | 文件源码
def different_training_sets():
    # base+author -> +paraphrasing -> +ifttt -> +generated
    train = [84.7, 93.2, 90.4, 91.99]
    test = [3.6, 37.4, 50.94, 55.4]
    train_recall = [66.6, 88.43, 92.63, 91.21]
    test_recall = [0.066, 49.05, 50.94, 75.47]

    #plt.newfigure()

    X = 1 + np.arange(4)
    plt.plot(X, train_recall, '--', color='#85c1e5')
    plt.plot(X, train, '-x', color='#6182a6')
    plt.plot(X, test_recall, '-o', color='#6182a6')
    plt.plot(X, test, '-', color='#052548')

    plt.ylim(0, 100)
    plt.xlim(0.5, 4.5)

    plt.xticks(X, ["Base + Author", "+ Paraphrasing", "+ IFTTT", "+ Generated"])
    plt.tight_layout()

    plt.legend(["Train recall", "Train accuracy", "Test recall", "Test accuracy"], loc='lower right')
    plt.savefig('./figures/training-sets.pdf')
项目:cellranger    作者:10XGenomics    | 项目源码 | 文件源码
def plot_norm_pct_hist( plt, values, binsize, start, **plt_args ):
    x = start
    xvals = []
    yvals = []
    norm = 0.0
    for v in values:
        xvals.append(x)
        yvals.append(v)
        xvals.append(x+binsize)
        norm += v
        yvals.append(v)
        x += binsize
    for i in xrange (len(yvals)):
        yvals[i] = yvals[i]/norm*100.0
    plt.plot( xvals, yvals, **plt_args)
    plt.xlim( start, x )
项目:chash    作者:luhsra    | 项目源码 | 文件源码
def plot_build_time_composition_graph(parseTimes, hashTimes, compileTimes, diffToBuildTime): # times in s
    fig, ax = plt.subplots()

    ax.stackplot(np.arange(1, len(parseTimes)+1), # x axis
#                 [parseTimes, hashTimes, compileTimes, diffToBuildTime],
                  [[i/60 for i in parseTimes], [i/60 for i in hashTimes], [i/60 for i in compileTimes], [i/60 for i in diffToBuildTime]],
                 colors=[parseColor,hashColor,compileColor,remainColor], edgecolor='none')
    plt.xlim(1,len(parseTimes))
    plt.xlabel('commits')
    plt.ylabel('time [min]')
    lgd = ax.legend([mpatches.Patch(color=remainColor),
                     mpatches.Patch(color=compileColor),
                     mpatches.Patch(color=hashColor),
                     mpatches.Patch(color=parseColor)],
                    ['remaining build time','compile time', 'hash time', 'parse time'],
                    loc='center left', bbox_to_anchor=(1, 0.5))
    fig.savefig(abs_path(BUILD_TIME_COMPOSITION_FILENAME), bbox_extra_artists=(lgd,), bbox_inches='tight')
    print_avg(parseTimes, 'parse')
    print_avg(hashTimes, 'hash')
    print_avg(compileTimes, 'compile')
    print_avg(diffToBuildTime, 'remainder')
项目:chash    作者:luhsra    | 项目源码 | 文件源码
def plot_build_time_composition_graph(parse_times, hash_times, compile_times, diff_to_build_time): # times in ns
    fig, ax = plt.subplots()
#[i/1e6 for i in parse_times],
    ax.stackplot(np.arange(1, len(parse_times)+1), # x axis
                 [[i/1e6 for i in parse_times], [i/1e6 for i in hash_times],[i/1e6 for i in compile_times], # ns to ms
                #diff_to_build_time
                ], colors=[parse_color,hash_color,compile_color,
                 #   remain_color
                ], edgecolor='none')
    plt.xlim(1,len(parse_times))
    plt.xlabel('commits')
    plt.ylabel('time [ms]')
    ax.set_yscale('log')
    lgd = ax.legend([#mpatches.Patch(color=remain_color),
                     mpatches.Patch(color=compile_color),
                     mpatches.Patch(color=hash_color),
                     mpatches.Patch(color=parse_color)],
                    [#'remaining build time',
                    'compile time', 'hash time', 'parse time'],
                    loc='center left', bbox_to_anchor=(1, 0.5))
    fig.savefig(abs_path(BUILD_TIME_FILENAME), bbox_extra_artists=(lgd,), bbox_inches='tight')



################################################################################
项目:CausalGAN    作者:mkocaoglu    | 项目源码 | 文件源码
def scatter2d(x,y,title='2dscatterplot',xlabel=None,ylabel=None):
    fig=plt.figure()
    plt.scatter(x,y)
    plt.title(title)
    if xlabel:
        plt.xlabel(xlabel)
    if ylabel:
        plt.ylabel(ylabel)

    if not 0<=np.min(x)<=np.max(x)<=1:
        raise ValueError('summary_scatter2d title:',title,' input x exceeded [0,1] range.\
                         min:',np.min(x),' max:',np.max(x))
    if not 0<=np.min(y)<=np.max(y)<=1:
        raise ValueError('summary_scatter2d title:',title,' input y exceeded [0,1] range.\
                         min:',np.min(y),' max:',np.max(y))

    plt.xlim([0,1])
    plt.ylim([0,1])
    return fig
项目:nelder_mead    作者:owruby    | 项目源码 | 文件源码
def plot2d_simplex(simplex, ind):
    fig_dir = "./"
    plt.cla()
    n = 1000
    x1 = np.linspace(-256, 1024, n)
    x2 = np.linspace(-256, 1024, n)
    X, Y = np.meshgrid(x1, x2)
    Z = np.sqrt(X ** 2 + Y ** 2)
    plt.contour(X, Y, Z, levels=list(np.arange(0, 1200, 10)))
    plt.gca().set_aspect("equal")
    plt.xlim((-256, 768))
    plt.ylim((-256, 768))

    plt.plot([simplex[0].x[0], simplex[1].x[0]],
             [simplex[0].x[1], simplex[1].x[1]], color="#000000")
    plt.plot([simplex[1].x[0], simplex[2].x[0]],
             [simplex[1].x[1], simplex[2].x[1]], color="#000000")
    plt.plot([simplex[2].x[0], simplex[0].x[0]],
             [simplex[2].x[1], simplex[0].x[1]], color="#000000")
    plt.savefig(os.path.join(fig_dir, "{:03d}.png".format(ind)))
项目:code-uai16    作者:thanhan    | 项目源码 | 文件源码
def plot_gold(g1, g2, lc, p = 0):
    """
    plot sen/spe of g1 against g2
    only consider workers in lc
    """

    mv = crowd_model.mv_model(lc)
    s1 = []; s2 = []

    for w in g1.keys():
        if w in g2 and g1[w][p] != None and g2[w][p] != None and w in mv.dic_ss:
            s1.append(g1[w][p])
            s2.append(g2[w][p])

    plt.xticks((0, 0.5, 1), ("0", "0.5", "1"))
    plt.tick_params(labelsize = 25)
    plt.yticks((0, 0.5, 1), ("0", "0.5", "1"))

    plt.xlim(0,1)
    plt.ylim(0,1)
    plt.scatter(s1, s2, marker = '.', s=50, c = 'black')

    plt.xlabel('task 1 sen.', fontsize = 25)
    plt.ylabel('task 2 sen.', fontsize = 25)
项目:code-uai16    作者:thanhan    | 项目源码 | 文件源码
def plot_multi_err():
    """
    """
    f = open('gzoo1000000_1_2_0.2_pickle.pkl')
    res = pickle.load(f)
    sing = res[(0.5, 'single')]
    multi = res[(0.5, 'multi')]
    (g1, g2, g3, g4) = load_gold()

    a = []; b = []
    for w in multi:
        a.append(abs(g2[w][0]- sing[w][0])); b.append(abs(g2[w][0] - multi[w][0]))


    plt.xlim(0,1); plt.ylim(0,1)
    plt.scatter(a, b, marker = '.')
    plt.plot([0, 1], [0, 1], ls="-", c=".5")

    plt.xlabel('single')
    plt.ylabel('multi')
项目:multimodal_varinf    作者:tmoer    | 项目源码 | 文件源码
def __init__(self,to_plot = True):
        self.state = np.array([0,0])        
        self.observation_shape = np.shape(self.get_state())[0]

        if to_plot:
            plt.ion()
            fig = plt.figure()
            ax1 = fig.add_subplot(111,aspect='equal')
            #ax1.axis('off')
            plt.xlim([-0.5,5.5])
            plt.ylim([-0.5,5.5])

            self.g1 = ax1.add_artist(plt.Circle((self.state[0],self.state[1]),0.1,color='red'))
            self.fig = fig
            self.ax1 = ax1
            self.fig.canvas.draw()
            self.fig.canvas.flush_events()
项目:kmeans-service    作者:MAYHEM-Lab    | 项目源码 | 文件源码
def plot_spatial_cluster_fig(data, covar_type_tied_labels_k):
    """ Creates a 3x2 plot spatial plot using labels as the color """
    sns.set(context='talk', style='white')
    data.columns = [c.lower() for c in data.columns]
    fig = plt.figure()
    placement = {'full': {True: 1, False: 4}, 'diag': {True: 2, False: 5}, 'spher': {True: 3, False: 6}}

    lim_left = data['longitude'].min()
    lim_right = data['longitude'].max()
    lim_bottom = data['latitude'].min()
    lim_top = data['latitude'].max()
    for covar_type, covar_tied, labels, k in covar_type_tied_labels_k:
        plt.subplot(2, 3, placement[covar_type][covar_tied])
        plt.scatter(data['longitude'], data['latitude'], c=labels, cmap=plt.cm.rainbow, s=10)
        plt.xlim(left=lim_left, right=lim_right)
        plt.ylim(bottom=lim_bottom, top=lim_top)
        plt.xticks([])
        plt.yticks([])
        plt.xlabel('Longitude')
        plt.ylabel('Latitude')
        plt.title('{}-{}, K={}'.format(covar_type.capitalize(), ['Untied', 'Tied'][covar_tied], k))
    plt.tight_layout()
    return fig
项目:Mini-Projects    作者:gaborvecsei    | 项目源码 | 文件源码
def main():
    #First we train the classifier to get the correct weights
    w = Perceptron(data_two)

    for x in data_two:
        #Get the responses with the correct weights
        y = x[0]*w[0]+x[1]*w[1]
        if y >= 0:
            y = 1
        else:
            y = -1

        if y == 1:
            plt.plot(x[0],x[1],'xb')
        else:
            plt.plot(x[0],x[1],'or')

    #Setting the range of the plot
    plt.ylim(-2, 2)
    plt.xlim(-2, 2)
    plt.show()
项目:DeblurGAN    作者:KupynOrest    | 项目源码 | 文件源码
def __plot_canvas(self, show, save):
        if self.x is None:
            raise Exception("Please run fit() method first")
        else:
            plt.close()
            plt.plot(self.x.real, self.x.imag, '-', color='blue')

            plt.xlim((0, self.canvas))
            plt.ylim((0, self.canvas))
            if show and save:
                plt.savefig(self.path_to_save)
                plt.show()
            elif save:
                if self.path_to_save is None:
                    raise Exception('Please create Trajectory instance with path_to_save')
                plt.savefig(self.path_to_save)
            elif show:
                plt.show()
项目:OASIS    作者:j-friedrich    | 项目源码 | 文件源码
def plot_trace(n=0, lg=False):
    plt.plot(trueC[n], c=col[2], clip_on=False, zorder=5, label='Truth')
    plt.plot(solution, c=col[0], clip_on=False, zorder=7, label='Estimate')
    plt.plot(y, c=col[7], alpha=.7, lw=1, clip_on=False, zorder=-10, label='Data')
    if lg:
        plt.legend(frameon=False, ncol=3, loc=(.1, .62), columnspacing=.8)
    spks = np.append(0, solution[1:] - g * solution[:-1])
    plt.text(800, 2.2, 'Correlation: %.3f' % (np.corrcoef(trueSpikes[n], spks)[0, 1]), size=24)
    plt.gca().set_xticklabels([])
    simpleaxis(plt.gca())
    plt.ylim(0, 2.85)
    plt.xlim(0, 1500)
    plt.yticks([0, 2], [0, 2])
    plt.xticks([300, 600, 900, 1200], ['', ''])


# init params
项目: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()
项目:SelfDrivingCar    作者:aguijarro    | 项目源码 | 文件源码
def main():

    rh, gh, bh, bincen, feature_vec = color_hist(image,
                                                 nbins=32,
                                                 bins_range=(0, 256))

    # Plot a figure with all three bar charts
    if rh is not None:
        fig = plt.figure(figsize=(12, 3))
        plt.subplot(131)
        plt.bar(bincen, rh[0])
        plt.xlim(0, 256)
        plt.title('R Histogram')
        plt.subplot(132)
        plt.bar(bincen, gh[0])
        plt.xlim(0, 256)
        plt.title('G Histogram')
        plt.subplot(133)
        plt.bar(bincen, bh[0])
        plt.xlim(0, 256)
        plt.title('B Histogram')
        fig.tight_layout()
        plt.show()
    else:
        print('Your function is returning None for at least one variable...')
项目:TickTickBacktest    作者:gavincyi    | 项目源码 | 文件源码
def plot_graph(cls, date_time, price, graph=None):
        """
        Plot the graph
        :param graph: MatPlotLibGraph
        :param date_time: Date time
        :param price: Price
        """
        date_time = (date_time - datetime.datetime(1970, 1, 1)).total_seconds()
        if graph is None:
            graph = plt.scatter([date_time], [price])
            plt.xlim([date_time, date_time + 60 * 60 * 24])
            # plt.ylim([float(price) * 0.95, float(price) * 1.05])
            plt.draw()
            plt.pause(0.1)
        else:
            array = graph.get_offsets()
            array = np.append(array, [date_time, price])
            graph.set_offsets(array)
            # plt.xlim([array[::2].min() - 0.5, array[::2].max() + 0.5])
            plt.ylim([float(array[1::2].min()) - 0.5, float(array[1::2].max()) + 0.5])
            plt.draw()
            plt.pause(0.1)

        return graph
项目:NuGridPy    作者:NuGrid    | 项目源码 | 文件源码
def set_plot_R(self):

        '''
            Plots the stellar logarithmic radius vs model number
        '''

        m=self.run_historydata
            figure(7)
            i=0
            for case in m:
                case.plot('star_age','log_R',legend=self.run_label[i],shape=self.symbs[i])
            i += 1
            legend(loc=2)
            xlabel('model number')
            ylabel('log_R')
            if xlim_mod_min >= 0:
                xlim(xlim_mod_min,xlim_mod_max)
项目:NuGridPy    作者:NuGrid    | 项目源码 | 文件源码
def hrd_key(self, key_str):
        """
        plot an HR diagram

        Parameters
        ----------
        key_str : string
            A label string

        """

        pyl.plot(self.data[:,self.cols['log_Teff']-1],\
                 self.data[:,self.cols['log_L']-1],label = key_str)
        pyl.legend()
        pyl.xlabel('log Teff')
        pyl.ylabel('log L')
        x1,x2=pl.xlim()
        if x2 > x1:
            self._xlimrev()
项目:NuGridPy    作者:NuGrid    | 项目源码 | 文件源码
def plot_prof_2(self, mod, species, xlim1, xlim2):

        """
        Plot one species for cycle between xlim1 and xlim2

        Parameters
        ----------
        mod : string or integer
            Model to plot, same as cycle number.
        species : list
            Which species to plot.
        xlim1, xlim2 : float
            Mass coordinate range.

        """

        mass=self.se.get(mod,'mass')
        Xspecies=self.se.get(mod,'yps',species)
        pyl.plot(mass,Xspecies,'-',label=str(mod)+', '+species)
        pyl.xlim(xlim1,xlim2)
        pyl.legend()
项目:piwall-cvtools    作者:infinnovation    | 项目源码 | 文件源码
def gimpMarkup(self, hints = gimpContours, image = "2x2-red-1.jpg", feature = "top-left-monitor"):
        r = Rectangle(*hints[image][feature])
        contour = r.asContour()
        cv2.drawContours(self.img, [contour], -1, (0, 255, 0), 5 )
        title = self.tgen.next(feature)
        if self.show: ImageViewer(self.img).show(window=title, destroy = self.destroy, info = self.info, thumbnailfn = title)
        roi = r.getRoi(self.img)
        self.rois[feature] = roi
        # Histogram the ROI to get the spread of intensities, in each channel and grayscale
        title = '%s-roi.jpg' % feature
        if self.show: ImageViewer(roi).show(window=title, destroy = self.destroy, info = self.info, thumbnailfn = title)
        colors = ('b','g','r')
        for i,col in enumerate(colors):
            hist = cv2.calcHist([roi], [i], None, [256], [0,256])
            plt.plot(hist, color = col)
            plt.xlim([0,256])
            #plt.hist(roi.ravel(), 256, [0,256])
        plt.show()
        cmap = ColorMapper(roi)
        cmap.mapit(1)
        title = self.tgen.next('colourMapping')
        if self.show: ImageViewer(self.img).show(window=title, destroy = self.destroy, info = self.info, thumbnailfn = title)
        cv2.waitKey()
项目:Master-Thesis    作者:AntoinePassemiers    | 项目源码 | 文件源码
def plot_feature_importances(forest, patch_name_nfeatures, layer_name):
    importances = forest.feature_importances_
    n_features = len(importances)
    plt.figure()
    plt.title("Feature importances (layer %s)" % str(layer_name))
    bar_list = plt.bar(range(n_features), importances, color="r", align="center")
    if n_features < 50:
        plt.xticks(range(n_features), range(n_features))
    plt.xlim([-1, n_features])

    PATCH_COLORS = ["orangered", "orange", "green", "purple", "cyan", "blue", "red", "yellow"]

    bar_id = 0
    patches = list()
    for i, (patch_name, n_bars) in enumerate(patch_name_nfeatures):
        patches.append(mpatches.Patch(color=PATCH_COLORS[i], label=patch_name))
        for b in range(n_bars):
            bar_list[bar_id].set_color(PATCH_COLORS[i])
            bar_id += 1
        plt.legend(handles = patches)
项目:HyperGAN    作者:255BITS    | 项目源码 | 文件源码
def sample(self, filename, save_samples):
        gan = self.gan
        generator = gan.generator.sample

        sess = gan.session
        config = gan.config
        x_v, z_v = sess.run([gan.inputs.x, gan.encoder.z])

        sample = sess.run(generator, {gan.inputs.x: x_v, gan.encoder.z: z_v})

        plt.clf()
        fig = plt.figure(figsize=(3,3))
        plt.scatter(*zip(*x_v), c='b')
        plt.scatter(*zip(*sample), c='r')
        plt.xlim([-2, 2])
        plt.ylim([-2, 2])
        plt.ylabel("z")
        fig.canvas.draw()
        data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
        data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
        #plt.savefig(filename)
        self.plot(data, filename, save_samples)
        return [{'image': filename, 'label': '2d'}]
项目:bmcmc    作者:sanjibs    | 项目源码 | 文件源码
def myplot(self):
        # Plot the results
        plt.clf()
        burn=1000
        x=np.arange(self.eargs['dsize'])+1
        stats=[[],[]]
        for i,y in enumerate(self.data['y']):
            stats[0].append(np.mean(y))
            stats[1].append(self.eargs['sigma']/np.sqrt(y.size))
        plt.errorbar(x,stats[0],yerr=stats[1],fmt='.b',lw=3,ms=12,alpha=0.8) 
        plt.errorbar(x,self.mu['alpha'],yerr=self.sigma['alpha'],fmt='.g',lw=3,ms=12,alpha=0.8)

        temp1=np.mean(self.chain['mu'][burn:])
        plt.plot([0,self.eargs['dsize']+1],[temp1,temp1],'k--')
        plt.xlim([0,self.eargs['dsize']+1])
        plt.ylabel(r'$\alpha_j$')
        plt.xlabel(r'Group $j$')
项目:ReGraph    作者:eugeniashurko    | 项目源码 | 文件源码
def _set_limits(nodes, labels, margin=0.1):
    xmin = min([
        p[0] for _, p in nodes.items()
    ])
    xmax = max([
        p[0] for _, p in nodes.items()
    ])
    ymin = min([
        p[1] for _, p in nodes.items()
    ])
    ymax = max([
        p[1] for _, p in labels.items()
    ])

    plt.xlim([
        xmin - margin * abs(xmax - xmin),
        xmax + margin * abs(xmax - xmin)
    ])
    plt.ylim([
        ymin - margin * abs(ymax - ymin),
        ymax + margin * abs(ymax - ymin)
    ])
    return
项目:usbtc08    作者:bankrasrg    | 项目源码 | 文件源码
def init_plot(self):
        # Interactive mode
        plt.ion()
        # Chart size and margins
        plt.figure(figsize = (20, 10))
        plt.subplots_adjust(hspace = 0.05, top = 0.95, bottom = 0.1, left = 0.05, right = 0.95)
        # Setup axis labels and ranges
        plt.title('Pico Technology TC-08')
        plt.xlabel('Time [s]')
        plt.ylabel('Temperature [' + self.unit_text + ']')
        plt.xlim(0, self.duration)
        self.plotrangemin = 19
        self.plotrangemax = 21
        plt.ylim(self.plotrangemin, self.plotrangemax)
        # Enable a chart line for each channel
        self.lines = []
        for i in CHANNEL_CONFIG:
            if CHANNEL_CONFIG.get(i) != ' ':
                self.lines.append(line(plt, CHANNEL_NAME.get(i)))
            else:
                self.lines.append(line(plt, 'Channel {:d} OFF'.format(i)))
        # Plot the legend
        plt.legend(loc = 'best', fancybox = True, framealpha = 0.5)
        plt.draw()
项目:dcss_single_cell    作者:srmcc    | 项目源码 | 文件源码
def tru_plot9(X,labels,t,plot_suffix,clust_names,clust_color, plot_loc):
    """
    From clustering_on_transcript_compatibility_counts, see github for MIT license
    """
    unique_labels = np.unique(labels)
    plt.figure(figsize=(15,10))
    for i in unique_labels:
        ind = np.squeeze(labels == i)
        plt.scatter(X[ind,0],X[ind,1],c=clust_color[i],s=36,edgecolors='gray',
                    lw = 0.5, label=clust_names[i])        
    plt.legend(loc='upper right',bbox_to_anchor=(1.1, 1))
    plt.legend(loc='upper right',bbox_to_anchor=(1.19, 1.01))
    plt.title(t)
    plt.xlim([-20,20])
    plt.ylim([-20,20])
    plt.axis('off')
    plt.savefig(plot_loc+ 't-SNE_plot_tru_plot9_'+ plot_suffix +'.pdf', bbox_inches='tight')

    # Plot function with Zeisel's colors corresponding to labels
项目:Auspex    作者:BBN-Q    | 项目源码 | 文件源码
def phase_diagram_mesh(points, values,
                                title="Phase diagram",
                                xlabel="Pulse Duration (s)",
                                ylabel="Pulse Amplitude (V)",
                                shading="flat",
                                voronoi=False, **kwargs):
    # fig = plt.figure()
    if voronoi:
        from scipy.spatial import Voronoi, voronoi_plot_2d
        points[:,0] *= 1e9
        vor = Voronoi(points)
        cmap = mpl.cm.get_cmap('RdGy')
        # colorize
        for pr, v in zip(vor.point_region, values):
            region = vor.regions[pr]
            if not -1 in region:
                polygon = [vor.vertices[i] for i in region]
                plt.fill(*zip(*polygon), color=cmap(v))
    else:
        mesh = scaled_Delaunay(points)
        xs = mesh.points[:,0]
        ys = mesh.points[:,1]
        plt.tripcolor(xs,ys,mesh.simplices.copy(),values, cmap="RdGy",shading=shading,**kwargs)
    plt.xlim(min(xs),max(xs))
    plt.ylim(min(ys),max(ys))
    plt.title(title, size=18)
    plt.xlabel(xlabel, size=16)
    plt.ylabel(ylabel, size=16)
    cb = plt.colorbar()
    cb.set_label("Probability",size=16)
    return mesh
项目:ExperimentPackage_PyTorch    作者:ICEORY    | 项目源码 | 文件源码
def __init__(self, file_path, fig_path=""):
        self.fig_params = {"figure_path": "./",
                           "figure_name": "Test-Acc",
                           "label": "ResNet20",
                           "xlabel": "epoch",
                           "ylabel": "testing error (%)",
                           "title": "",
                           "line_width": 2,
                           "line_style": "-",
                           "xlim": [],
                           "ylim": [],
                           "inverse": True,
                           "figure_format": "pdf"}
        self.file_path = file_path
        self.fig_path = fig_path
        split_str = self.fig_path.split("/")
        label_str = split_str[-2]
        split_label_str = label_str.split("_")
        label_str = ""
        for i in range(len(split_label_str)-2):
            label_str += "-" + split_label_str[i+1]
        self.fig_params["label"] = label_str
项目:CfdnaPattern    作者:OpenGene    | 项目源码 | 文件源码
def plot_benchmark(scores_arr, algorithms_arr, filename):
    colors = ['#FF6600', '#009933', '#2244AA', '#552299', '#11BBDD']
    linestyles = ['-', '--', ':']
    passes = len(scores_arr[0])

    x = range(1, passes+1)
    title = "Benchmark Result"
    plt.figure(1, figsize=(8,8))
    plt.title(title, size=20, color='#333333')
    plt.xlim(1, passes)
    plt.ylim(0.97, 1.001)
    plt.ylabel('Score', size=16, color='#333333')
    plt.xlabel('Validation pass (sorted by score)', size=16, color='#333333')
    for i in xrange(len(scores_arr)):
        plt.plot(x, scores_arr[i], color = colors[i%5], label=algorithms_arr[i], alpha=0.5, linewidth=2, linestyle = linestyles[i%3])
    plt.legend(loc='lower left')
    plt.savefig(filename)
    plt.close(1)
项目:johnson-county-ddj-public    作者:dssg    | 项目源码 | 文件源码
def plot_ROC(self):
        """ Plot the receiver operating characteristic curve

        :returns: ROC curve
        :rtype: matplotlib figure
        """
        fpr = self.subset_metrics('pct', 'false_pos_rate')['value']
        tpr = self.subset_metrics('pct', 'recall')['value']
        thresholds = np.arange(.01, 1.01, .01)
        with plt.style.context(('ggplot')):
            fig, ax = plt.subplots()
            ax.plot(fpr, tpr, "#000099", label='ROC curve')
            ax.plot([0, 1], [0, 1], 'k--')
            plt.xlim([0.0, 1.0])
            plt.ylim([0.0, 1.05])
            plt.xlabel('False Positive Rate')
            plt.ylabel('True Positive Rate')
            plt.legend(loc='lower right')
            plt.title('Receiver operating characteristic')
        return(fig)
项目:SciData_08-17-2017    作者:kitestring    | 项目源码 | 文件源码
def SimilarityPlot(self, SpectralDict):
        fig = plt.figure(figsize=(18,9))

        # Add each data set to the Spectral Qualithy Plot
        for n, data_set in enumerate(SpectralDict['data_sets']):
            plt.scatter(SpectralDict['x_data'][n], SpectralDict['y_data'][n], color=self.color_codes[n], label=data_set)

        # Horizontal 800 Similarity line
        plt.axhline(y=800, xmin=0, xmax=1, hold=None, color=self.red_hex_code, label='800 Similarity')

        # Make your plot pretty
        plt.legend(loc='upper left')
        plt.ylabel('Similarity vs. Main NIST Hit')
        plt.xlabel('Concentration (pg)')
        plt.title('%s - Spectral Quality' % SpectralDict['analyte_name'])
        plt.xscale('log')
        plt.xlim(SpectralDict['x_axis_min'], SpectralDict['x_axis_max'])
        plt.savefig(SpectralDict['file_name'], bbox_inches='tight')
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
def generate_plot(plot_dir, iteration, data_in, output_g, output_d, train_data, args):
    data_in = data_in.squeeze()
    generated = output_g['generated']
    plt.plot(data_in[0], data_in[1], 'gx')
    plt.plot(generated[0], generated[1], 'r.')
    plt.xlim([-2, 2])
    plt.ylim([-2, 2])
    plt.gca().set_aspect('equal', adjustable='box')
    plt.axis('off')
    title = 'Iteration {} \n Gen. Cost {:.2E}  Disc. Cost {:.2E}'.format(
        iteration, float(output_g['batch_cost']), float(output_d['batch_cost']))
    plt.title(title)
    plt.savefig(plot_dir + '/' + str(iteration) + 'Generated.png')
    plt.clf()

    # plot and save loss and gradients
    for key in train_data.keys():
        data = np.array(train_data[key]).T
        plt.plot(data[0], data[1])
        plt.title(key + ' for ' + args.loss_type)
        plt.xlabel('Iterations')
        plt.ylabel(key)
        plt.savefig(plot_dir + '/' + key + '.png')
        plt.clf()
项目:same-stats-different-graphs    作者:jmatejka    | 项目源码 | 文件源码
def show_scatter(df, xlim=(-5, 105), ylim=(-5, 105), color="black", marker="o", reg_fit=False):
    """Create a scatter plot of the data

    Args:
        df (pd.DataFrame):      The data set to plot
        xlim ((float, float)):  The x-axis limits
        ylim ((float, float)):  The y-axis limits
        color (str):            The color of the scatter points
        marker (str):           The marker style for the scatter points
        reg_fit (bool):         Whether to plot a linear regression on the graph
    """
    sns.regplot(
        x="x",
        y="y",
        data=df,
        ci=None,
        fit_reg=reg_fit,
        marker=marker,
        scatter_kws={"s": 50, "alpha": 0.7, "color": color},
        line_kws={"linewidth": 4, "color": "red"})
    plt.xlim(xlim)
    plt.ylim(ylim)
    plt.tight_layout()
项目:TemporalEncoding    作者:SpikeFrame    | 项目源码 | 文件源码
def plot_spikepattern(spike_trains, sim_time):
    """Plot set of spike trains (spike pattern)"""
    plt.ioff()

    plt.figure()
    for i in xrange(len(spike_trains)):
        spike_times = spike_trains[i].value
        plt.plot(spike_times, np.full(len(spike_times), i,
                 dtype=np.int), 'k.')
    plt.xlim((0.0, sim_time))
    plt.ylim((0, len(spike_trains)))
    plt.xlabel('Time (ms)')
    plt.ylabel('Neuron index')
    plt.show()

    plt.ion()
项目:TemporalEncoding    作者:SpikeFrame    | 项目源码 | 文件源码
def plot_spiker(record, spike_trains_target, neuron_index=0):
    """Plot spikeraster and target timings for given neuron index"""
    plt.ioff()

    spike_trains = [np.array(i.spiketrains[neuron_index])
                    for i in record.segments]
    n_segments = record.size['segments']

    plt.figure()
    for i in xrange(len(spike_trains)):
        plt.plot(spike_trains[i], np.full(len(spike_trains[i]), i + 1,
                 dtype=np.int), 'k.')
    target_timings = spike_trains_target[neuron_index].value
    plt.plot(target_timings, np.full(len(target_timings), 1.025 * n_segments),
             'kx', markersize=8, markeredgewidth=2)
    plt.xlim((0., np.float(record.segments[0].t_stop)))
    plt.ylim((0, np.int(1.05 * n_segments)))
    plt.xlabel('Time (ms)')
    plt.ylabel('Trials')
    plt.title('Output neuron {}'.format(neuron_index))
    plt.show()

    plt.ion()
项目:nanopores    作者:mitschabaude    | 项目源码 | 文件源码
def plot_evolution(params, color=None, label=None):
    data = get_results(NAME, params, calc=do_calculations)
    times = data.times
    success = data.success
    N = float(len(success))
    t = sorted(times[success])
    p = np.arange(sum(success))/N
    t.append(endtime)
    p = np.append(p, [p[-1]])
    errp = 1.96*np.sqrt(p*(1.-p)/N) # 95% confidence

    plt.semilogx(t, p, color=color, label=label)
    plt.fill_between(t, p - errp, p + errp, alpha=0.2,
                     facecolor=color, linewidth=0)
    plt.xlabel("Time [ns]")
    plt.ylabel("Exit probability")
    plt.xlim(xmin=0.1, xmax=5e6)
    print "last time: %.5f ms\nend prob: %.3f\nstd. dev.: %.3f" % (
        t[-2]*1e-6, p[-2], errp[-2])
项目: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)
项目:nanopores    作者:mitschabaude    | 项目源码 | 文件源码
def exponential_hist(times, a, b, **params):
    cutoff = 0.03 # cutoff frequency in ms
    if len(times) == 0:
        return
    bins = np.logspace(a, b, 100)
    hist = plt.hist(times, bins=bins, alpha=0.5, **params)
    plt.xscale("log")
    params.pop("label")
    color = params.pop("color")
    total = integrate_hist(hist, cutoff)
    if sum(times > cutoff) == 0:
        return
    tmean = times[times > cutoff].mean()
    T = np.logspace(a-3, b, 1000)
    fT = np.exp(-T/tmean)*T/tmean
    fT *= total/integrate_values(T, fT, cutoff)
    plt.plot(T, fT, label="exp. fit, mean = %.2f ms" % (tmean,),
             color="dark" + color, **params)
    plt.xlim(10**a, 10**b)
项目:merlin    作者:CSTR-Edinburgh    | 项目源码 | 文件源码
def plot_weight_histogram(model, outfile, lower=-0.25, upper=0.25):
    n = len(model.params)
    plt.clf()
    for (i, theano_shared_params) in enumerate(model.params):
        weights = theano_shared_params.get_value()
        values = weights.flatten()
        plt.subplot(n,1,i+1)
        frame = plt.gca()
        frame.axes.get_yaxis().set_ticks([])
        if i != n-1:  ## only keep bottom one
            frame.axes.get_xaxis().set_ticks([])
        plt.hist(values, 100)
        plt.xlim(lower, upper)
        print('   param no. %s'%(i))
        print(get_stats(theano_shared_params))
    plt.savefig(outfile)
    print('Made plot %s'%(outfile))
项目:StrepHit    作者:Wikidata    | 项目源码 | 文件源码
def about_biographies_count(corpus):
    """ Finds how many items have/don't have a biography
    """
    count = with_bio = characters = 0
    for doc in load_scraped_items(corpus):
        count += 1
        if doc.get('bio') and len(doc['bio']) > 5:
            with_bio += 1
            characters += len(doc['bio'])

    print 'Total number of items:', count
    print 'Items with a biography %d (%.2f %%)' % (with_bio, 100. * with_bio / count)
    print 'Cumulative length of biographies: %d characters' % characters

    try:
        import matplotlib.pyplot as plt
    except ImportError:
        logger.warn('Cannot import matplotlib, skipping chart')
        return

    plt.bar([0, 1], [count - with_bio, with_bio], width=0.75)
    plt.xticks([0.375, 1.375], ['Without Biography', 'With Biography'])
    plt.grid(True, axis='y')
    plt.xlim((-0.5, 2.25))
    plt.show()
项目:Machine-Learning-Algorithms    作者:PacktPublishing    | 项目源码 | 文件源码
def show_classification_areas(X, Y, lr):
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
    Z = lr.predict(np.c_[xx.ravel(), yy.ravel()])

    Z = Z.reshape(xx.shape)
    plt.figure(1, figsize=(30, 25))
    plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Pastel1)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=np.abs(Y - 1), edgecolors='k', cmap=plt.cm.coolwarm)
    plt.xlabel('X')
    plt.ylabel('Y')

    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.xticks(())
    plt.yticks(())

    plt.show()
项目:python-machine-learning    作者:sho-87    | 项目源码 | 文件源码
def plot_training(history):
    """Plot the training curve.

    Parameters:
    history -- numpy array/list of cost values over all training iterations

    Returns:
    Plot of the cost for each iteration of training

    """
    plt.plot(range(1, len(history)+1), history)
    plt.grid(True)
    plt.xlim(1, len(history))
    plt.ylim(min(history), max(history))

    plt.title("Training Curve")
    plt.xlabel("Iteration")
    plt.ylabel("Cost")
项目:pyballd    作者:Yurlungur    | 项目源码 | 文件源码
def plot_test_function(orderx,ordery):
    s = PseudoSpectralDiscretization2D(orderx,XMIN,XMAX,
                                ordery,YMIN,YMAX)
    X,Y = s.get_x2d()
    f_ana = f(X,Y)
    plt.pcolor(X,Y,f_ana)
    plt.xlabel('x',fontsize=16)
    plt.ylabel('y',fontsize=16)
    plt.xlim(XMIN,XMAX)
    plt.ylim(YMIN,YMAX)
    cb = plt.colorbar()
    cb.set_label(label=r'$\cos(x)\sin(2 y)$',fontsize=16)
    for postfix in ['.png','.pdf']:
        name = 'test_function'+postfix
        if USE_FIGS_DIR:
            name = 'figs/' + name
        plt.savefig(name,
                    bbox_inches='tight')
    plt.clf()
项目:almond-nnparser    作者:Stanford-Mobisocial-IoT-Lab    | 项目源码 | 文件源码
def correct_function():
    # order is para-prim, para-comp, cheat-prim, cheat-comp, scenario-prim, scenario-comp
    SEMPRE = [85.04, 66.98, 77.5, 49.01, 60, 33]
    DEEP_SEMPRE = [95.23, 75.64, 50, 47.05, 42.85, 16.66]

    X = np.arange(3)
    width = (0.8-0.1)/4

    s_p = [SEMPRE[0], SEMPRE[2], SEMPRE[4]]
    s_c = [SEMPRE[1], SEMPRE[3], SEMPRE[5]]
    d_p = [DEEP_SEMPRE[0], DEEP_SEMPRE[2], DEEP_SEMPRE[4]]
    d_c = [DEEP_SEMPRE[1], DEEP_SEMPRE[3], DEEP_SEMPRE[5]]

    plt.bar(X, s_p, width=width, color='#85c1e5')
    plt.bar(X+width, d_p, width=width, color='#254e7b')
    plt.bar(X+2*width+0.1, s_c, width=width, color='#85c1e5')
    plt.bar(X+3*width+0.1, d_c, width=width, color='#254e7b')

    width = (0.8-0.1)/4
    plt.xticks(np.array([width, 3*width+0.1,
                         1+width, 1+3*width+0.1,
                         2+width, 2+3*width+0.1]),
        ["Prim.", "Comp.", "Prim.", "Comp.", "Prim.", "Comp."])
    plt.text(0.4, -10, "Paraphrasing", ha='center', fontsize=18)
    plt.text(1.4, -10, "Scenarios", ha='center', fontsize=18)
    plt.text(2.4, -10, "Composition", ha='center', fontsize=18)
    plt.ylim(0, 100)
    plt.xlim(-0.1, 2.9)
    #plt.tight_layout()
    plt.legend(["SEMPRE", "Neural Net"], loc ="upper right")
    plt.savefig('./figures/correct-function.pdf')
项目:almond-nnparser    作者:Stanford-Mobisocial-IoT-Lab    | 项目源码 | 文件源码
def accuracy_against_sempre():
    # order is para-prim, para-comp, cheat-prim, cheat-comp, scenario-prim, scenario-comp
    SEMPRE = [71.4, 50.2, 67.5, 33.3, 34.28, 30.5]
    DEEP_SEMPRE = [89.11, 55.27, 47.5, 29.4, 34.28, 16.66]

    X = np.arange(3)
    width = (0.8-0.1)/4

    s_p = [SEMPRE[0], SEMPRE[2], SEMPRE[4]]
    s_c = [SEMPRE[1], SEMPRE[3], SEMPRE[5]]
    d_p = [DEEP_SEMPRE[0], DEEP_SEMPRE[2], DEEP_SEMPRE[4]]
    d_c = [DEEP_SEMPRE[1], DEEP_SEMPRE[3], DEEP_SEMPRE[5]]

    plt.bar(X, s_p, width=width, color='#85c1e5')
    plt.bar(X+width, d_p, width=width, color='#254e7b')
    plt.bar(X+2*width+0.1, s_c, width=width, color='#85c1e5')
    plt.bar(X+3*width+0.1, d_c, width=width, color='#254e7b')

    width = (0.8-0.1)/4
    plt.xticks(np.array([width, 3*width+0.1,
                         1+width, 1+3*width+0.1,
                         2+width, 2+3*width+0.1]),
        ["Prim.", "Comp.", "Prim.", "Comp.", "Prim.", "Comp."])
    plt.text(0.4, -10, "Paraphrasing", ha='center', fontsize=18)
    plt.text(1.4, -10, "Scenarios", ha='center', fontsize=18)
    plt.text(2.4, -10, "Composition", ha='center', fontsize=18)
    plt.ylim(0, 100)
    plt.xlim(-0.1, 2.9)
    #plt.tight_layout()
    plt.legend(["SEMPRE", "Neural Net"], loc ="upper right")
    plt.savefig('./figures/accuracy-combined.pdf')
项目:almond-nnparser    作者:Stanford-Mobisocial-IoT-Lab    | 项目源码 | 文件源码
def extensibility():
    # order is new device acc, new device recall, new domain acc, new domain recall
    SEMPRE = [100 * 117./214., 100 * (10.+63.)/(15.+104.), 100 * (42.+232.)/(535.+75.), 100 * (32.+136.)/(286.+48.)]
    DEEP_SEMPRE = [38, 47, 55, 74]

    X = np.arange(2)
    width = (0.8-0.1)/4

    s_a = [SEMPRE[0], SEMPRE[2]]
    s_r = [SEMPRE[1], SEMPRE[3]]
    d_a = [DEEP_SEMPRE[0], DEEP_SEMPRE[2]]
    d_r = [DEEP_SEMPRE[1], DEEP_SEMPRE[3]]

    plt.bar(X, s_a, width=width, color='#85c1e5')
    plt.bar(X+width, d_a, width=width, color='#254e7b')
    plt.bar(X+2*width+0.1, s_r, width=width, color='#85c1e5')
    plt.bar(X+3*width+0.1, d_r, width=width, color='#254e7b')

    width = (0.8-0.1)/4
    plt.xticks(np.array([width, 3*width+0.1,
                         1+width, 1+3*width+0.1,
                         2+width, 2+3*width+0.1]),
        ["Accuracy", "Recall", "Accuracy", "Recall"])
    plt.text(0.4, -10, "New Device", ha='center', fontsize=18)
    plt.text(1.4, -10, "New Domain", ha='center', fontsize=18)
    plt.ylim(0, 100)
    plt.xlim(-0.1, 1.9)
    #plt.tight_layout()
    plt.legend(["SEMPRE", "Neural Net"], loc ="upper right")
    plt.savefig('./figures/extensibility.pdf')