python类savefig()的实例源码

visualizer.py 文件源码 项目:adgm 作者: musyoku 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def tile_binary_images(x, dir=None, filename="x"):
    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()
    pylab.gray()
    for m in range(100):
        pylab.subplot(10, 10, m + 1)
        pylab.imshow(np.clip(x[m], 0, 1), interpolation="none")
        pylab.axis("off")
    pylab.savefig("{}/{}.png".format(dir, filename))
visualizer.py 文件源码 项目:adgm 作者: musyoku 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def plot_z(z, dir=None, filename="z", xticks_range=None, yticks_range=None):
    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()
    for n in xrange(z.shape[0]):
        result = pylab.scatter(z[n, 0], z[n, 1], s=40, marker="o", edgecolors='none')
    pylab.xlabel("z1")
    pylab.ylabel("z2")
    if xticks_range is not None:
        pylab.xticks(pylab.arange(-xticks_range, xticks_range + 1))
    if yticks_range is not None:
        pylab.yticks(pylab.arange(-yticks_range, yticks_range + 1))
    pylab.savefig("{}/{}.png".format(dir, filename))
plots.py 文件源码 项目:PyFusionGUI 作者: SyntaxVoid 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def plot_signals(input_data, filename=None,downsamplefactor=1,n_columns=1):
    import pylab as pl
    n_rows = input_data.signal.n_channels()
    n_rows = int(n_rows/n_columns)
    print str(n_rows) + ' ' + str(n_columns)
    for row in range(n_rows):
        for col in range(n_columns):
            print (row)*n_columns+col+1
            pl.subplot(n_rows, n_columns, row*n_columns+col+1)
            if downsamplefactor==1:
                pl.plot(input_data.timebase, input_data.signal.get_channel(row*n_columns+col))
                pl.axis([-0.01,0.1,-5, 5])
            else:
                plotdata=input_data.signal.get_channel(row*n_columns+col)
                timedata=input_data.timebase
                pl.plot(timedata[0:len(timedata):downsamplefactor], plotdata[0:len(timedata):downsamplefactor])
                pl.axis([-0.01,0.1,-5,5])
    if filename != None:
        pl.savefig(filename)
    else:
        pl.show()
util.py 文件源码 项目:variational-autoencoder 作者: musyoku 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def visualize_x(reconstructed_x_batch, image_width=28, image_height=28, image_channel=1, dir=None):
    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()
    if image_channel == 1:
        pylab.gray()
    for m in range(100):
        pylab.subplot(10, 10, m + 1)
        if image_channel == 1:
            pylab.imshow(reconstructed_x_batch[m].reshape((image_width, image_height)), interpolation="none")
        elif image_channel == 3:
            pylab.imshow(reconstructed_x_batch[m].reshape((image_channel, image_width, image_height)), interpolation="none")
        pylab.axis("off")
    pylab.savefig("%s/reconstructed_x.png" % dir)
util.py 文件源码 项目:variational-autoencoder 作者: musyoku 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def visualize_labeled_z(z_batch, label_batch, dir=None):
    fig = pylab.gcf()
    fig.set_size_inches(20.0, 16.0)
    pylab.clf()
    colors = ["#2103c8", "#0e960e", "#e40402","#05aaa8","#ac02ab","#aba808","#151515","#94a169", "#bec9cd", "#6a6551"]
    for n in xrange(z_batch.shape[0]):
        result = pylab.scatter(z_batch[n, 0], z_batch[n, 1], c=colors[label_batch[n]], s=40, marker="o", edgecolors='none')

    classes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    recs = []
    for i in range(0, len(colors)):
        recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=colors[i]))

    ax = pylab.subplot(111)
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
    ax.legend(recs, classes, loc="center left", bbox_to_anchor=(1.1, 0.5))
    pylab.xticks(pylab.arange(-4, 5))
    pylab.yticks(pylab.arange(-4, 5))
    pylab.xlabel("z1")
    pylab.ylabel("z2")
    pylab.savefig("%s/labeled_z.png" % dir)
graph.py 文件源码 项目:twitter-bot-detection 作者: franckbrignoli 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def hist_weekday(self, tweet_weekday_user, tweet_weekday_bot, path):
        fig = plt.figure()
        ax = plt.subplot(111)

        opacity = 0.4
        labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        bar_width = 0.3
        x = range(len(tweet_weekday_user["prop"]))

        plt.xticks([0.3, 1.3, 2.3, 3.3, 4.3, 5.3, 6.3], labels)
        ax.bar(x, tweet_weekday_user["prop"],bar_width,color='b',alpha=opacity,label='Humans', yerr=tweet_weekday_user["std"])
        ax.bar([0.3, 1.3, 2.3, 3.3, 4.3, 5.3, 6.3], tweet_weekday_bot["prop"],bar_width,color='g',alpha=opacity,label='Bots', yerr=tweet_weekday_bot["std"])

        ax.set_xlabel('Week days')
        ax.set_ylabel('Tweets proportion per day (0 to 1)')
        sns.plt.title('Proportion of tweets for each week day')
        ax.legend()
        pl.savefig(path)
analysis.py 文件源码 项目:AdK_analysis 作者: orbeckst 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def _auto_plots(self,mode,filebasename,figdir,plotargs):
        """Generate standard plots and write png and and pdf. Chooses filename and plot title."""
        import pylab

        try:
            os.makedirs(figdir)
        except OSError,err:
            if err.errno != errno.EEXIST:
                raise

        def figs(*args):
            return os.path.join(figdir,*args)

        modefilebasename = filebasename + self._suffix[mode]
        _plotargs = plotargs.copy()  # need a copy because of changing 'title'
        if plotargs.get('title') is None:  # None --> set automatic title
            _plotargs['title'] = self._title[mode]+' '+self.legend

        pylab.clf()
        self.plot(**_plotargs)
        pylab.savefig(figs(modefilebasename + '.png'))   # png
        pylab.savefig(figs(modefilebasename + '.pdf'))   # pdf

        print "--- Plotted %(modefilebasename)r (png,pdf)." % vars()
angles.py 文件源码 项目:AdK_analysis 作者: orbeckst 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def plot_windows_together(db,figname=os.path.join(config.basedir,'figs','pmf','windows.pdf'),stride=10,**plotargs):
    """Plot windows in one plot; stride selects a subset of windows.

    Example:

    >>> PMF.angles.plot_windows_together(db,figname='figs/pmf/all_windows.png',stride=1,alpha=0.3,contour_alpha=0.2,cmap=cm.jet_r)
    """
    import pylab

    pylab.clf()

    fn = db.filenames()[::stride]
    for n,f in enumerate(fn):
        fb = os.path.basename(f)
        print "-- %5.1f%% %3d/%3d %s" % (100*(n+1)/len(fn), n, len(fn), fb)
        # figname=os.path.join('figs','pmf',fb+'.pdf'),
        s = Selection(db,'filename="%s"' % f)
        s.plot(clf=False,**plotargs)
    pylab.title('Umbrella windows')
    pylab.savefig(str(figname))
    print "- Created figure '%(figname)s'." % vars()
image_ocr.py 文件源码 项目:keras-101 作者: burness 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_dim_ordering() == 'th':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close()
utilities.py 文件源码 项目:livespin 作者: biocompibens 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def removeIllumination2(self, size, title = ''):
        out = ndimage.filters.gaussian_filter(self.image, size)
        pylab.figure()
        pylab.subplot(2,2,1)
        pylab.axis('off')
        pylab.imshow(self.image)
        pylab.subplot(2,2,2)
        pylab.axis('off')
        pylab.imshow(out)
        pylab.subplot(2,2,3)
        pylab.axis('off')
        pylab.imshow(self.image - out)
        pylab.subplot(2,2,4)
        pylab.axis('off')
        pylab.imshow(self.smooth - out)
        if title != '':
            pylab.savefig(title)
            pylab.close()
        else:
            pylab.show()
        self.smooth -= out
        return self.image - out
infofiles.py 文件源码 项目:livespin 作者: biocompibens 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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()
GaussClasses.py 文件源码 项目:livespin 作者: biocompibens 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def draw2D(self, title, image=[]):
        pylab.figure()
        if image == []:
            pylab.imshow(self.image, 'gray')
        else:
            pylab.imshow(image, 'gray')
        pylab.axis('off')
        pylab.autoscale(False)
        for i in xrange(self.nComponents):
            xeq = lambda t: self.params[6 * i + 3] * np.cos(t) * np.cos(self.params[6 * i + 5]) + self.params[
                                                                                                      6 * i + 4] * np.sin(
                t) * np.sin(self.params[6 * i + 5]) + self.params[6 * i + 1]
            yeq = lambda t: - self.params[6 * i + 3] * np.cos(t) * np.sin(self.params[6 * i + 5]) + self.params[
                                                                                                        6 * i + 4] * np.sin(
                t) * np.cos(self.params[6 * i + 5]) + self.params[6 * i + 2]
            t = np.linspace(0, 2 * np.pi, 100)
            x = xeq(t)
            y = yeq(t)
            pylab.scatter(self.params[6 * i + 2], self.params[6 * i + 1], color='k')
            pylab.plot(y.astype(int), x.astype(int), self.colors[i] + '-')
        pylab.savefig(title)
        pylab.close()
analyzeAngle.py 文件源码 项目:livespin 作者: biocompibens 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)))
plot.py 文件源码 项目:spyking-circus 作者: spyking-circus 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
plot.py 文件源码 项目:spyking-circus 作者: spyking-circus 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def view_artefact(data, save=False):

    fig          = pylab.figure()    
    pylab.plot(data.T)
    if save:
        pylab.savefig(os.path.join(save[0], 'artefact_%s' %save[1]))
        pylab.close()
    else:
        pylab.show()
    del fig
plot.py 文件源码 项目:spyking-circus 作者: spyking-circus 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def view_trigger_snippets(trigger_snippets, chans, save=None):
    # Create output directory if necessary.
    if os.path.exists(save):
        for f in os.listdir(save):
            p = os.path.join(save, f)
            os.remove(p)
        os.removedirs(save)
    os.makedirs(save)
    # Plot figures.
    fig = pylab.figure()
    for (c, chan) in enumerate(chans):
        ax = fig.add_subplot(1, 1, 1)
        for n in xrange(0, trigger_snippets.shape[2]):
            y = trigger_snippets[:, c, n]
            x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1)
            b = 0.5 + 0.5 * numpy.random.rand()
            ax.plot(x, y, color=(0.0, 0.0, b), linestyle='solid')
        y = numpy.mean(trigger_snippets[:, c, :], axis=1)
        x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1)
        ax.plot(x, y, color=(1.0, 0.0, 0.0), linestyle='solid')
        ax.grid(True)
        ax.set_xlim([numpy.amin(x), numpy.amax(x)])
        ax.set_title("Channel %d" %chan)
        ax.set_xlabel("time")
        ax.set_ylabel("amplitude")
        if save is not None:
            # Save plot.
            filename = "channel-%d.png" %chan
            path = os.path.join(save, filename)
            pylab.savefig(path)
        fig.clf()
    if save is None:
        pylab.show()
    else:
        pylab.close(fig)
    return
plot.py 文件源码 项目:spyking-circus 作者: spyking-circus 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def view_mahalanobis_distribution(data_1, data_2, save=None):
    '''Plot Mahalanobis distribution Before and After'''
    fig = pylab.figure()
    ax = fig.add_subplot(1,2,1)
    if len(data_1) == 3:
        d_gt, d_ngt, d_noi = data_1
    elif len(data_1) == 2:
        d_gt, d_ngt = data_1
    if len(data_1) == 3:
        ax.hist(d_noi, bins=50, color='k', alpha=0.5, label="Noise")
    ax.hist(d_ngt, bins=50, color='b', alpha=0.5, label="Non GT")
    ax.hist(d_gt, bins=75, color='r', alpha=0.5, label="GT")
    ax.grid(True)
    ax.set_title("Before")
    ax.set_ylabel("")
    ax.set_xlabel('# Samples')
    ax.set_xlabel('Distances')

    if len(data_2) == 3:
        d_gt, d_ngt, d_noi = data_2
    elif len(data_2) == 2:
        d_gt, d_ngt = data_2
    ax = fig.add_subplot(1,2,2)
    if len(data_2) == 3:
        ax.hist(d_noi, bins=50, color='k', alpha=0.5, label="Noise")
    ax.hist(d_ngt, bins=50, color='b', alpha=0.5, label="Non GT")
    ax.hist(d_gt, bins=75, color='r', alpha=0.5, label="GT")
    ax.grid(True)
    ax.set_title("After")
    ax.set_ylabel("")
    ax.set_xlabel('Distances')


    ax.legend()
    if save is None:
        pylab.show()
    else:
        pylab.savefig(save)
        pylab.close(fig)
    return
hp.py 文件源码 项目:seqhawkes 作者: mlukasik 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def plot_intensity_all(self, x, figure_path):
        sumI = np.array([self.sumIntensitiesAll(xi, self.node_vec,
                        self.etimes, True)[1] for xi in x])
        (f_mean, f_lower, f_upper) = (sumI, sumI, sumI)
        gpplot(x, f_mean, f_lower, f_upper)
        pb.xlabel('time')
        pb.ylabel('intensity lambda over all memes and users')
        pb.savefig(figure_path)
plot_indices.py 文件源码 项目:pyrsss 作者: butala 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    parser = ArgumentParser('Create plot of the Kp and Dst indices.',
                            formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument('pdf_fname',
                        type=str,
                        help='file to store plot')
    parser.add_argument('d1',
                        type=dt_parser,
                        help='start date/time')
    parser.add_argument('d2',
                        type=dt_parser,
                        help='end date/time')
    parser.add_argument('--style',
                        '-s',
                        type=str,
                        choices=sorted(STYLE_MAP),
                        default='display',
                        help='plot style (display is more colorful and meant for screen display whereas document is high contrast and uses hatches for both color and black-white interpretation and meant for use in publication)')
    args = parser.parse_args(argv[1:])

    plot_indices(args.d1,
                 args.d2,
                 style=args.style)

    PL.savefig(args.pdf_fname,
               bbox_inches='tight')
dvhcalc.py 文件源码 项目:DVH 作者: glucee 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def main():


    # Read the example RT structure and RT dose files
    # The testdata was downloaded from the dicompyler website as testdata.zip

    # Obtain the structures and DVHs from the DICOM data

    rtssfile = 'testdata/rtss.dcm'
    rtdosefile = 'testdata/rtdose.dcm'
    RTss = dicomparser.DicomParser(rtssfile)
    #RTdose = dicomparser.DicomParser("testdata/rtdose.dcm") 
    RTstructures = RTss.GetStructures()

    # Generate the calculated DVHs
    calcdvhs = {}
    for key, structure in RTstructures.iteritems():
        calcdvhs[key] = dvhcalc.get_dvh(rtssfile, rtdosefile, key)
        if (key in calcdvhs) and (len(calcdvhs[key].counts) and calcdvhs[key].counts[0]!=0):
            print ('DVH found for ' + structure['name'])
            pl.plot(calcdvhs[key].counts * 100/calcdvhs[key].counts[0], 
                    color=dvhcalc.np.array(structure['color'], dtype=float) / 255, 
                    label=structure['name'], 
                    linestyle='dashed')
        #else: 
        #    print("%d: no DVH"%key)
    pl.xlabel('Distance (cm)')
    pl.ylabel('Percentage Volume')
    pl.legend(loc=7, borderaxespad=-5)
    pl.setp(pl.gca().get_legend().get_texts(), fontsize='x-small')
    pl.savefig('testdata/dvh.png', dpi = 75)


问题


面经


文章

微信
公众号

扫码关注公众号