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

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

项目:lyricswordcloud    作者:qwertyyb    | 项目源码 | 文件源码
def showData(self):
    print('???,????···')
    mask = imread(self.picfile)
    imgcolor = ImageColorGenerator(mask)
    wcc = WordCloud(font_path='./msyhl.ttc', 
    mask=mask, background_color='white', 
    max_font_size=200, 
    max_words=300,
    color_func=imgcolor
    )
    wc = wcc.generate_from_frequencies(self.data)
    plt.figure()
    plt.imshow(wc)
    plt.axis('off')
    print('?????')
    plt.show()
项目:IgDiscover    作者:NBISweden    | 项目源码 | 文件源码
def plot_counts(counts, gene_type):
    """Plot expression counts. Return a Figure object"""
    import matplotlib
    matplotlib.use('agg')
    import matplotlib.pyplot as plt
    import seaborn as sns
    import numpy as np

    fig = plt.figure(figsize=((50 + len(counts) * 5) / 25.4, 210/25.4))
    matplotlib.rcParams.update({'font.size': 14})
    ax = fig.gca()
    ax.set_title('{} gene usage'.format(gene_type))
    ax.set_xlabel('{} gene'.format(gene_type))
    ax.set_ylabel('Count')
    ax.set_xticks(np.arange(len(counts)) + 0.5)
    ax.set_xticklabels(counts.index, rotation='vertical')
    ax.grid(axis='x')
    ax.set_xlim((-0.25, len(counts)))
    ax.bar(np.arange(len(counts)), counts['count'])
    fig.set_tight_layout(True)
    return fig
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_trigger_snippets_bis(trigger_snippets, elec_index, save=None):
    fig = pylab.figure()
    ax = fig.add_subplot(1, 1, 1)
    for n in xrange(0, trigger_snippets.shape[2]):
        y = trigger_snippets[:, elec_index, 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')
    ax.grid(True)
    ax.set_xlim([numpy.amin(x), numpy.amax(x)])
    ax.set_xlabel("time")
    ax.set_ylabel("amplitude")
    if save is None:
        pylab.show()
    else:
        pylab.savefig(save)
        pylab.close(fig)
    return
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_dataset(X, color='blue', title=None, save=None):
    n_components = 2
    pca = PCA(n_components)
    pca.fit(X)
    x = pca.transform(X)
    fig = pylab.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.scatter(x[:, 0], x[:, 1], c=color, s=5, lw=0.1)
    ax.grid(True)
    if title is None:
        ax.set_title("Dataset ({} samples)".format(X.shape[0]))
    else:
        ax.set_title(title + " ({} samples)".format(X.shape[0]))
    ax.set_xlabel("1st component")
    ax.set_ylabel("2nd component")
    if save is None:
        pylab.show()
    else:
        pylab.savefig(save)
        pylab.close(fig)
    return
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_loss_curve(losss, title=None, save=None):
    '''Plot loss curve'''
    x_min = 1
    x_max = len(losss) - 1
    fig = pylab.figure()
    ax = fig.gca()
    ax.semilogy(range(x_min, x_max + 1), losss[1:], color='blue', linestyle='solid')
    ax.grid(True, which='both')
    if title is None:
        ax.set_title("Loss curve")
    else:
        ax.set_title(title)
    ax.set_xlabel("iteration")
    ax.set_ylabel("loss")
    ax.set_xlim([x_min - 1, x_max + 1])
    if save is None:
        pylab.show()
    else:
        pylab.savefig(save)
        pylab.close(fig)
    return
项目:hippylib    作者:hippylib    | 项目源码 | 文件源码
def plot_eigenvectors(Vh, U, mytitle, which = [0,1,2,5,10,15]):
    assert len(which) % 3 == 0
    nrows = len(which) / 3
    subplot_loc = nrows*100 + 30
    plt.figure(figsize=(18,4*nrows))

    title_stamp = mytitle + " {0}" 
    u = dl.Function(Vh)
    counter=1
    for i in which:
        assert i < U.shape[1]
        Ui = U[:,i]
        if Ui[0] >= 0:
            s = 1./np.linalg.norm(Ui, np.inf)
        else:
            s = -1./np.linalg.norm(Ui, np.inf)
        u.vector().set_local(s*Ui)
        plot(u, subplot_loc=(subplot_loc+counter), mytitle=title_stamp.format(i), vmin=-1, vmax=1)
        counter = counter+1
项目:seq2seq    作者:google    | 项目源码 | 文件源码
def _create_figure(predictions_dict):
  """Creates and returns a new figure that visualizes
  attention scores for for a single model predictions.
  """

  # Find out how long the predicted sequence is
  target_words = list(predictions_dict["predicted_tokens"])

  prediction_len = _get_prediction_length(predictions_dict)

  # Get source words
  source_len = predictions_dict["features.source_len"]
  source_words = predictions_dict["features.source_tokens"][:source_len]

  # Plot
  fig = plt.figure(figsize=(8, 8))
  plt.imshow(
      X=predictions_dict["attention_scores"][:prediction_len, :source_len],
      interpolation="nearest",
      cmap=plt.cm.Blues)
  plt.xticks(np.arange(source_len), source_words, rotation=45)
  plt.yticks(np.arange(prediction_len), target_words, rotation=-45)
  fig.tight_layout()

  return fig
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
def analyze(context=None, results=None):
    import matplotlib.pyplot as plt
    import logbook
    logbook.StderrHandler().push_application()
    log = logbook.Logger('Algorithm')

    fig = plt.figure()
    ax1 = fig.add_subplot(211)

    results.algorithm_period_return.plot(ax=ax1,color='blue',legend=u'????')
    ax1.set_ylabel(u'??')
    results.benchmark_period_return.plot(ax=ax1,color='red',legend=u'????')

    plt.show()

# capital_base is the base value of capital
#
项目:voxcelchain    作者:hiroaki-kaneda    | 项目源码 | 文件源码
def conv1(model):
    n1, n2, x, y, z = model.conv1.W.shape
    fig = plt.figure()
    for nn in range(0, n1):
        ax = fig.add_subplot(4, 5, nn+1, projection='3d')
        ax.set_xlim(0.0, x)
        ax.set_ylim(0.0, y)
        ax.set_zlim(0.0, z)
        ax.set_xticklabels([])
        ax.set_yticklabels([])
        ax.set_zticklabels([])
        for xx in range(0, x):
            for yy in range(0, y):
                for zz in range(0, z):
                    max = np.max(model.conv1.W.data[nn, :])
                    min = np.min(model.conv1.W.data[nn, :])
                    step = (max - min) / 1.0
                    C = (model.conv1.W.data[nn, 0, xx, yy, zz] - min) / step
                    color = cm.cool(C)
                    C = abs(1.0 - C)
                    ax.plot(np.array([xx]), np.array([yy]), np.array([zz]), "o", color=color, ms=7.0*C, mew=0.1)

    plt.savefig("result/graph_conv1.png")
项目:ward-metrics    作者:phev8    | 项目源码 | 文件源码
def plot_events_with_event_scores(gt_event_scores, detected_event_scores, ground_truth_events, detected_events, show=True):
    fig = plt.figure(figsize=(10, 3))
    for i in range(len(detected_events)):
        d = detected_events[i]
        plt.axvspan(d[0], d[1], 0, 0.5)
        plt.text((d[1] + d[0]) / 2, 0.2, detected_event_scores[i], horizontalalignment='center', verticalalignment='center')

    for i in range(len(ground_truth_events)):
        gt = ground_truth_events[i]
        plt.axvspan(gt[0], gt[1], 0.5, 1)
        plt.text((gt[1] + gt[0]) / 2, 0.8, gt_event_scores[i], horizontalalignment='center', verticalalignment='center')

    plt.tight_layout()

    if show:
        plt.show()
    else:
        plt.draw()
项目:Google-QuickDraw    作者:ankonzoid    | 项目源码 | 文件源码
def plot_labeled_images_random(image_list, label_list, categories, n, title_str, ypixels, xpixels, seed, filename):
    random.seed(seed)
    index_sample = random.sample(range(len(image_list)), n)
    plt.figure(figsize=(2*n, 2))
    #plt.suptitle(title_str)
    for i, ind in enumerate(index_sample):
        ax = plt.subplot(1, n, i + 1)
        plt.imshow(image_list[ind].reshape(ypixels, xpixels))
        plt.gray()
        ax.set_title(categories[label_list[ind]], fontsize=20)
        ax.get_xaxis().set_visible(False); ax.get_yaxis().set_visible(False)
    if 1:
        pylab.savefig(filename, bbox_inches='tight')
    else:
        plt.show()

# plot_unlabeled_images_random: plots unlabeled images at random
项目:Google-QuickDraw    作者:ankonzoid    | 项目源码 | 文件源码
def plot_unlabeled_images_random(image_list, n, title_str, ypixels, xpixels, seed, filename):
    random.seed(seed)
    index_sample = random.sample(range(len(image_list)), n)
    plt.figure(figsize=(2*n, 2))
    plt.suptitle(title_str)
    for i, ind in enumerate(index_sample):
        ax = plt.subplot(1, n, i + 1)
        plt.imshow(image_list[ind].reshape(ypixels, xpixels))
        plt.gray()
        ax.get_xaxis().set_visible(False); ax.get_yaxis().set_visible(False)
    if 1:
        pylab.savefig(filename, bbox_inches='tight')
    else:
        plt.show()

# plot_compare: given test images and their reconstruction, we plot them for visual comparison
项目:Google-QuickDraw    作者:ankonzoid    | 项目源码 | 文件源码
def plot_compare(x_test, decoded_imgs, filename):
    n = 10
    plt.figure(figsize=(2*n, 4))
    for i in range(n):
        # display original
        ax = plt.subplot(2, n, i + 1)
        plt.imshow(x_test[i].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

        # display reconstruction
        ax = plt.subplot(2, n, i + 1 + n)
        plt.imshow(decoded_imgs[i].reshape(28, 28))
        plt.gray()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

    if 1:
        pylab.savefig(filename, bbox_inches='tight')
    else:
        plt.show()

# plot_img: plots greyscale image
项目:sampleRNN_ICLR2017    作者:soroushmehr    | 项目源码 | 文件源码
def plot_traing_info(x, ylist, path):
    """
    Loads log file and plot x and y values as provided by input.
    Saves as <path>/train_log.png
    """
    file_name = os.path.join(path, __train_log_file_name)
    try:
        with open(file_name, "rb") as f:
            log = pickle.load(f)
    except IOError:  # first time
        warnings.warn("There is no {} file here!!!".format(file_name))
        return
    plt.figure()
    x_vals = log[x]
    for y in ylist:
        y_vals = log[y]
        if len(y_vals) != len(x_vals):
            warning.warn("One of y's: {} does not have the same length as x:{}".format(y, x))
        plt.plot(x_vals, y_vals, label=y)
        # assert len(y_vals) == len(x_vals), "not the same len"
    plt.xlabel(x)
    plt.legend()
    #plt.show()
    plt.savefig(file_name[:-3]+'png', bbox_inches='tight')
    plt.close('all')
项目:vae-npvc    作者:JeremyCCHsu    | 项目源码 | 文件源码
def plot_spectra(results):
    plt.figure(figsize=(10, 4))
    plt.imshow(
        np.concatenate(
            [np.flipud(results['x'].T),
             np.flipud(results['xh'].T),
             np.flipud(results['x_conv'].T)],
            0),
        aspect='auto',
        cmap='jet',
    )
    plt.colorbar()
    plt.title('Upper: Real input; Mid: Reconstrution; Lower: Conversion to target.')
    plt.savefig(
        os.path.join(
            args.logdir,
            '{}.png'.format(
                os.path.split(str(results['f'], 'utf-8'))[-1]
            )
        )
    )
项目:pybot    作者:spillai    | 项目源码 | 文件源码
def plot_confusion_matrix(cm, target_names, title='Confusion matrix', cmap=plt.cm.Greys, block=True):
    # Colormaps: jet, Greys
    cm_normalized = cm.astype(np.float32) / cm.sum(axis=1)[:, np.newaxis]
    plt.imshow(cm_normalized, interpolation='nearest', cmap=cmap)

    # Show confidences
    for i, cas in enumerate(cm): 
        for j, c in enumerate(cas): 
            if c > 0: 
                plt.text(j-0.1, i+0.2, c, fontsize=16, fontweight='bold', color='#b70000')

    f = plt.figure(1)
    f.clf()
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(target_names))
    plt.xticks(tick_marks, target_names, rotation=45)
    plt.yticks(tick_marks, target_names)
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.show(block=block)
项目:didi_competition    作者:Heipiao    | 项目源码 | 文件源码
def plot_single_day_traffic(df):
    y_tj_l1 = df["tj_level1_count"]
    y_tj_l2 = df["tj_level2_count"]
    y_tj_l3 = df["tj_level3_count"]
    y_tj_l4 = df["tj_level4_count"]

    x_time = df["time"]
    x_district = df["district"]

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(x_time, x_district, y_tj_l1, )
    #ax.plot_surface(x_time, x_district, y_tj_l1)
    print(plt.get_backend())
    plt.show()
    plt.savefig("plot_traffic.png")
项目:shenlan    作者:vector-1127    | 项目源码 | 文件源码
def plotGeneratedImages(epoch,example=100,dim=(10,10),figsize=(10,10)):
    noise = np.random.normal(0,1,size=(example,randomDim))
    generatedImage = generator.predict(noise)
    generatedImage = generatedImage.reshape(example,28,28)

    plt.figure(figsize=figsize)

    for i in range(example):
        plt.subplot(dim[0],dim[1],i+1)
        plt.imshow(generatedImage[i],interpolation='nearest',cmap='gray')
        '''drop the x and y axis'''
        plt.axis('off')
    plt.tight_layout()

    if not os.path.exists('generated_image'):
        os.mkdir('generated_image')
    plt.savefig('generated_image/wgan_generated_img_epoch_%d.png' % epoch)
项目:lung-cancer-detector    作者:YichenGong    | 项目源码 | 文件源码
def plot_3D(img, threshold=-400):
    verts, faces = measure.marching_cubes(img, threshold)

    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111, projection='3d')

    mesh = Poly3DCollection(verts[faces], alpha=0.1)
    face_color = [0.5, 0.5, 1]
    mesh.set_facecolor(face_color)
    ax.add_collection3d(mesh)

    ax.set_xlim(0, img.shape[0])
    ax.set_ylim(0, img.shape[1])
    ax.set_zlim(0, img.shape[2])

    plt.show()
项目: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
项目:bayestsa    作者:thalesians    | 项目源码 | 文件源码
def analyseparamsneighbourhood(svdata, params, includejumps, randomstate):
    parameterndarray = transformparameterndarray(np.array(params), includejumps)
    offsets = np.linspace(-.5, .5, 10)
    for dimension in range(params.dimensioncount):
        xs, ys = [], []
        parametername = params.getdimensionname(dimension)
        print('Perturbing %s...' % parametername)
        for offset in offsets:
            newparameterndarray = np.copy(parameterndarray)
            newparameterndarray[dimension] += offset
            xs.append(inversetransformparameterndarray(newparameterndarray, includejumps)[dimension])
            y = runsvljparticlefilter(svdata, sv.Params(*inversetransformparameterndarray(newparameterndarray, includejumps)), randomstate).stochfilter.loglikelihood
            ys.append(y)
        fig = plt.figure()
        plot = fig.add_subplot(111)
        plot.plot(xs, ys)
        plot.axvline(x=inversetransformparameterndarray(parameterndarray, includejumps)[dimension], color='red')
        plot.set_xlabel(parametername)
        plot.set_ylabel('loglikelihood')
        plt.show()
项目:polo    作者:adrianveres    | 项目源码 | 文件源码
def make_benchmark_figure():

    fig = plt.figure(figsize=(6,6))
    ax = fig.add_subplot(1, 1, 1, xscale='linear', yscale='log')


    d1 = np.load('./data/random_data_benchmark.npy')
    d2 = np.load('./data/real_data_benchmark.npy')
    d3 = np.load('./data/real_data_orange3_benchmark.npy')

    ax.scatter(d1[:24, 0], d1[:24, 2], c='r', edgecolor='none', label='Random Data (Polo)')
    ax.scatter(d2[:24, 0], d2[:24, 2], c='green', edgecolor='none', label='Gene expression data (Polo)')
    ax.scatter(d3[:24, 0], d3[:24, 2], c='blue', edgecolor='none', label='Gene expression data (Orange3)')

    ax.legend(loc=2)
    ax.grid('on')
    ax.set_xlabel('log2(Number of leaves)')
    ax.set_ylabel('Run time, seconds')
    fig.tight_layout()
    fig.savefig('data/bench.png', dpi=75)
项目:keras-utilities    作者:cbaziotis    | 项目源码 | 文件源码
def on_train_begin(self, logs={}):
        sns.set_style("whitegrid")
        sns.set_style("whitegrid", {"grid.linewidth": 0.5,
                                    "lines.linewidth": 0.5,
                                    "axes.linewidth": 0.5})
        flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e",
                  "#2ecc71"]
        sns.set_palette(sns.color_palette(flatui))
        # flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
        # sns.set_palette(sns.color_palette("Set2", 10))

        plt.ion()  # set plot to animated
        self.fig = plt.figure(
            figsize=(self.width * (1 + len(self.get_metrics(logs))),
                     self.height))  # width, height in inches

        # move it to the upper left corner
        move_figure(self.fig, 25, 25)
项目:keras-utilities    作者:cbaziotis    | 项目源码 | 文件源码
def on_train_begin(self, logs={}):
        for layer in self.get_trainable_layers():
            for param in self.parameters:
                if any(w for w in layer.weights if param in w.name.split("_")):
                    name = layer.name + "_" + param
                    self.layers_stats[name]["values"] = numpy.asarray(
                        []).ravel()
                    for s in self.stats:
                        self.layers_stats[name][s] = []

        # plt.style.use('ggplot')
        plt.ion()  # set plot to animated
        width = 3 * (1 + len(self.stats))
        height = 2 * len(self.layers_stats)
        self.fig = plt.figure(
            figsize=(width, height))  # width, height in inches
        # sns.set_style("whitegrid")
        # self.draw_plot()
项目:s2g    作者:caesar0301    | 项目源码 | 文件源码
def test_point_projects_to_edge(self):
        # p = (114.83299055, 26.8892277)
        p = (121.428387, 31.027371)
        a = time.time()
        edges, segments = self.sg.point_projects_to_edges(p, 0.01)
        print(time.time() - a)

        if self.show_plots:
            plt.figure()
            s2g.plot_lines(MultiLineString(segments), color='orange')  # original roads
            for i in range(0, len(edges)):
                s, e = edges[i]
                sxy = self.sg.node_xy[s]
                exy = self.sg.node_xy[e]
                plt.plot([sxy[0], exy[0]], [sxy[1], exy[1]], color='green')  # graph edges
            plt.plot(p[0], p[1], color='red', markersize=12, marker='o')  # bridges
            plt.show()
项目:machine-learning    作者:zzw0929    | 项目源码 | 文件源码
def plotBestFit(weights):
    import matplotlib.pyplot as plt
    dataMat, labelMat =  loadDataSet()
    dataArr =  array(dataMat)
    n = shape(dataArr)[0]
    xcord1 = []; ycord1 = []
    xcord2 = []; ycord2 = []
    for i in range(n):
        if int(labelMat[i]) == 1:
            xcord1.append(dataArr[i, 1]);ycord1.append(dataArr[i, 2])
        else:
            xcord2.append(dataArr[i, 1]);ycord2.append(dataArr[i, 2])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(xcord1, ycord1, s=30, c='red', marker='s')
    ax.scatter(xcord2, ycord2, s=30, c='green')
    x = arange(-3.0, 3.0, 0.1)
    y = (-weights[0]-weights[1]*x)/weights[2] # ??????
    ax.plot(x, y)
    plt.xlabel('X1');plt.ylabel('X2')
    plt.show()

# ??500???
项目:machine-learning    作者:zzw0929    | 项目源码 | 文件源码
def createPlot(inTree):
    fig = plt.figure(1, facecolor='white')
    fig.clf()
    axprops = dict(xticks=[], yticks=[])
    createPlot.ax1 = plt.subplot(111, frameon=False, **axprops)    #no ticks
    #createPlot.ax1 = plt.subplot(111, frameon=False) #ticks for demo puropses 
    plotTree.totalW = float(getNumLeafs(inTree))
    plotTree.totalD = float(getTreeDepth(inTree))
    plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0;
    plotTree(inTree, (0.5,1.0), '')
    plt.show()

# def createPlot():
#   fig = plt.figure(1, facecolor='white')
#   fig.clf()
#   createPlot.ax1 = plt.subplot(111, frameon=True)
#   plotNode(U'a decision node',(0.5,0.1), (0.1,0.5), decisionNode)
#   plotNode(U'a leaf node',(0.8,0.1), (0.3,0.8), leafNode)
#   plt.show()
项目:PersonalizedMultitaskLearning    作者:mitmedialab    | 项目源码 | 文件源码
def plotValResults(self, save_path=None, label=None):
        if label is not None:
            accs = self.training_val_results['acc'][label]
            aucs = self.training_val_results['auc'][label]
        else:
            accs = self.training_val_results['acc']
            aucs = self.training_val_results['auc']
        plt.figure()
        plt.plot([i * ACCURACY_LOGGED_EVERY_N_STEPS for i in range(len(accs))], accs)
        plt.plot([i * ACCURACY_LOGGED_EVERY_N_STEPS for i in range(len(aucs))], aucs)
        plt.xlabel('Training step')
        plt.ylabel('Validation accuracy')
        plt.legend(['Accuracy','AUC'])
        if save_path is None:
            plt.show()
        else:
            plt.savefig(save_path)
        plt.close()
项目:PersonalizedMultitaskLearning    作者:mitmedialab    | 项目源码 | 文件源码
def plotValResults(self, save_path=None, label=None):
        if label:
            accs = self.training_val_results_per_task['acc'][label]
            aucs = self.training_val_results_per_task['auc'][label]
        else:
            accs = self.training_val_results['acc']
            aucs = self.training_val_results['auc']
        plt.figure()
        plt.plot([i * self.accuracy_logged_every_n for i in range(len(accs))], accs)
        plt.plot([i * self.accuracy_logged_every_n for i in range(len(aucs))], aucs)
        plt.xlabel('Training step')
        plt.ylabel('Validation accuracy')
        plt.legend(['Accuracy','AUC'])
        if save_path is None:
            plt.show()
        else:
            plt.savefig(save_path)
项目:photinia    作者:XoriieInpottn    | 项目源码 | 文件源码
def plot_with_labels(low_dim_embs, labels, filename='tsne.png'):
    assert low_dim_embs.shape[0] >= len(labels), "More labels than embeddings"
    plt.figure(figsize=(18, 18))  # in inches
    x = low_dim_embs[:, 0]
    y = low_dim_embs[:, 1]
    plt.scatter(x, y)
    for i, label in enumerate(labels):
        x, y = low_dim_embs[i, :]
        plt.annotate(label,
                     xy=(x, y),
                     xytext=(5, 2),
                     textcoords='offset points',
                     ha='right',
                     va='bottom')
    plt.show()
    # plt.savefig(filename)
项目:bob.bio.base    作者:bioidiap    | 项目源码 | 文件源码
def _plot_cmc(cmcs, colors, labels, title, fontsize=10, position=None):
  if position is None: position = 'lower right'
  # open new page for current plot
  figure = pyplot.figure()

  max_R = 0
  # plot the CMC curves
  for i in range(len(cmcs)):
    probs = bob.measure.cmc(cmcs[i])
    R = len(probs)
    pyplot.semilogx(range(1, R+1), probs, figure=figure, color=colors[i], label=labels[i])
    max_R = max(R, max_R)

  # change axes accordingly
  ticks = [int(t) for t in pyplot.xticks()[0]]
  pyplot.xlabel('Rank')
  pyplot.ylabel('Probability')
  pyplot.xticks(ticks, [str(t) for t in ticks])
  pyplot.axis([0, max_R, -0.01, 1.01])
  pyplot.legend(loc=position, prop = {'size':fontsize})
  pyplot.title(title)

  return figure
项目:bob.bio.base    作者:bioidiap    | 项目源码 | 文件源码
def _plot_epc(scores_dev, scores_eval, colors, labels, title, fontsize=10, position=None):
  if position is None: position = 'upper center'
  # open new page for current plot
  figure = pyplot.figure()

  # plot the DET curves
  for i in range(len(scores_dev)):
    x,y = bob.measure.epc(scores_dev[i][0], scores_dev[i][1], scores_eval[i][0], scores_eval[i][1], 100)
    pyplot.plot(x, y, color=colors[i], label=labels[i])

  # change axes accordingly
  pyplot.xlabel('alpha')
  pyplot.ylabel('HTER')
  pyplot.title(title)
  pyplot.axis([-0.01, 1.01, -0.01, 0.51])
  pyplot.grid(True)
  pyplot.legend(loc=position, prop = {'size':fontsize})
  pyplot.title(title)

  return figure
项目:klineyes    作者:tenstone    | 项目源码 | 文件源码
def mfi(df):
    df['date'] = pd.to_datetime(df.date)

    fig = plt.figure(figsize=(16, 9))
    gs = GridSpec(3, 1) # 2 rows, 3 columns
    fig.suptitle(df['date'][-1:].values[0])
    fig.set_label('MFI')
    price = fig.add_subplot(gs[:2, 0])
    price.plot(df['date'], df['close'], color='blue')

    indicator = fig.add_subplot(gs[2, 0], sharex=price)
    indicator.plot(df['date'], df['mfi'], c='pink')
    indicator.plot(df['date'], [20.]*len(df['date']), c='green')
    indicator.plot(df['date'], [80.]*len(df['date']), c='orange')

    price.grid(True)
    indicator.grid(True)
    plt.tight_layout()
    plt.show()
项目:klineyes    作者:tenstone    | 项目源码 | 文件源码
def atr(df):
    '''
    Average True Range
    :param df:
    :return:
    '''
    df['date'] = pd.to_datetime(df.date)

    fig = plt.figure(figsize=(16, 9))
    gs = GridSpec(3, 1) # 2 rows, 3 columns
    fig.suptitle(df['date'][-1:].values[0])
    fig.set_label('ATR')
    price = fig.add_subplot(gs[:2, 0])
    price.plot(df['date'], df['close'], color='blue')

    indicator = fig.add_subplot(gs[2, 0], sharex=price)
    indicator.plot(df['date'], df['atr'], c='pink')
    # indicator.plot(df['date'], [20.]*len(df['date']), c='green')
    # indicator.plot(df['date'], [80.]*len(df['date']), c='orange')

    price.grid(True)
    indicator.grid(True)
    plt.tight_layout()
    plt.show()
项目:klineyes    作者:tenstone    | 项目源码 | 文件源码
def rocr(df):
    '''
    Average True Range
    :param df:
    :return:
    '''
    df['date'] = pd.to_datetime(df.date)

    fig = plt.figure(figsize=(16, 9))
    gs = GridSpec(3, 1) # 2 rows, 3 columns
    fig.suptitle(df['date'][-1:].values[0])
    fig.set_label('ATR')
    price = fig.add_subplot(gs[:2, 0])
    price.plot(df['date'], df['close'], color='blue')

    indicator = fig.add_subplot(gs[2, 0], sharex=price)
    indicator.plot(df['date'], df['rocr'], c='pink')
    # indicator.plot(df['date'], [20.]*len(df['date']), c='green')
    # indicator.plot(df['date'], [80.]*len(df['date']), c='orange')

    price.grid(True)
    indicator.grid(True)
    plt.tight_layout()
    plt.show()
项目: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()
项目:Flavor-Network    作者:lingcheng99    | 项目源码 | 文件源码
def plot_similardishes(idx,xlim):
    match = yum_ingr2.iloc[yum_cos[idx].argsort()[-21:-1]][::-1]
    newidx = match.index.get_values()
    match['cosine'] = yum_cos[idx][newidx]
    match['rank'] = range(1,1+len(newidx))

    label1, label2 =[],[]
    for i in match.index:
        label1.append(match.ix[i,'cuisine'])
        label2.append(match.ix[i,'recipeName'])

    fig = plt.figure(figsize=(10,10))
    ax = sns.stripplot(y='rank', x='cosine', data=match, jitter=0.05,
                       hue='cuisine',size=15,orient="h")
    ax.set_title(yum_ingr2.ix[idx,'recipeName']+'('+yum_ingr2.ix[idx,'cuisine']+')',fontsize=18)
    ax.set_xlabel('Flavor cosine similarity',fontsize=18)
    ax.set_ylabel('Rank',fontsize=18)
    ax.yaxis.grid(color='white')
    ax.xaxis.grid(color='white')

    for label, y,x, in zip(label2, match['rank'],match['cosine']):
         ax.text(x+0.001,y-1,label, ha = 'left')
    ax.legend(loc = 'lower right',prop={'size':14})
    ax.set_ylim([20,-1])
    ax.set_xlim(xlim)
项目:Flavor-Network    作者:lingcheng99    | 项目源码 | 文件源码
def tsne_cluster_cuisine(df,sublist):
    lenlist=[0]
    df_sub = df[df['cuisine']==sublist[0]]
    lenlist.append(df_sub.shape[0])
    for cuisine in sublist[1:]:
        temp = df[df['cuisine']==cuisine]
        df_sub = pd.concat([df_sub, temp],axis=0,ignore_index=True)
        lenlist.append(df_sub.shape[0])
    df_X = df_sub.drop(['cuisine','recipeName'],axis=1)
    print df_X.shape, lenlist

    dist = squareform(pdist(df_X, metric='cosine'))
    tsne = TSNE(metric='precomputed').fit_transform(dist)

    palette = sns.color_palette("hls", len(sublist))
    plt.figure(figsize=(10,10))
    for i,cuisine in enumerate(sublist):
        plt.scatter(tsne[lenlist[i]:lenlist[i+1],0],\
        tsne[lenlist[i]:lenlist[i+1],1],c=palette[i],label=sublist[i])
    plt.legend()

#interactive plot with boken; set up for four categories, with color palette; pass in df for either ingredient or flavor
项目:MicroGrids    作者:squoilin    | 项目源码 | 文件源码
def Energy_Flow(Time_Series):


    Energy_Flow = {'Energy_Demand':0, 'Lost Load':0, 'Energy PV':0,'Curtailment':0, 'Energy Diesel':0, 'Discharge energy from the Battery':0, 'Charge energy to the Battery':0}

    for v in Energy_Flow.keys():
        if v == 'Energy PV':
            Energy_Flow[v] = round((Time_Series[v].sum() - Time_Series['Curtailment'].sum()- Time_Series['Charge energy to the Battery'].sum())/1000000, 2)
        else:
            Energy_Flow[v] = round((Time_Series[v].sum())/1000000, 2)


    c = ['From Generator', 'To Battery', 'Demand', 'From PV', 'From Battery', 'Curtailment', 'Lost Load']       
    plt.figure()    
    plt.bar((1,2,3,4,5,6,7), Energy_Flow.values(), color= 'b', alpha=0.3, align='center')

    plt.xticks((1.2,2.2,3.2,4.2,5.2,6.2,7.2), c)
    plt.xlabel('Technology')
    plt.ylabel('Energy Flow (MWh)')
    plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='on')
    plt.xticks(rotation=-30)
    plt.savefig('Results/Energy_Flow.png', bbox_inches='tight')
    plt.show()    

    return Energy_Flow
项目:MicroGrids    作者:squoilin    | 项目源码 | 文件源码
def LDR(Time_Series):

    columns=['Consume diesel', 'Lost Load', 'Energy PV','Curtailment','Energy Diesel', 
             'Discharge energy from the Battery', 'Charge energy to the Battery', 
             'Energy_Demand',  'State_Of_Charge_Battery'  ]
    Sort_Values = Time_Series.sort('Energy_Demand', ascending=False)

    index_values = []

    for i in range(len(Time_Series)):
        index_values.append((i+1)/float(len(Time_Series))*100)

    Sort_Values = pd.DataFrame(Sort_Values.values/1000, columns=columns, index=index_values)

    plt.figure() 
    ax = Sort_Values['Energy_Demand'].plot(style='k-',linewidth=1)

    fmt = '%.0f%%' # Format you want the ticks, e.g. '40%'
    xticks = mtick.FormatStrFormatter(fmt)
    ax.xaxis.set_major_formatter(xticks)
    ax.set_ylabel('Load (kWh)')
    ax.set_xlabel('Percentage (%)')

    plt.savefig('Results/LDR.png', bbox_inches='tight')
    plt.show()
项目:MLPractices    作者:carefree0910    | 项目源码 | 文件源码
def draw_results(self):
        metrics_log, cost_log = {}, {}
        for key, value in sorted(self._logs.items()):
            metrics_log[key], cost_log[key] = value[:-1], value[-1]

        for i, name in enumerate(sorted(self._metric_names)):
            plt.figure()
            plt.title("Metric Type: {}".format(name))
            for key, log in sorted(metrics_log.items()):
                xs = np.arange(len(log[i])) + 1
                plt.plot(xs, log[i], label="Data Type: {}".format(key))
            plt.legend(loc=4)
            plt.show()
            plt.close()

        plt.figure()
        plt.title("Cost")
        for key, loss in sorted(cost_log.items()):
            xs = np.arange(len(loss)) + 1
            plt.plot(xs, loss, label="Data Type: {}".format(key))
        plt.legend()
        plt.show()
项目:MLPractices    作者:carefree0910    | 项目源码 | 文件源码
def get_graphs_from_logs():
        with open("Results/logs.dat", "rb") as file:
            logs = pickle.load(file)
        for (hus, ep, bt), log in logs.items():
            hus = list(map(lambda _c: str(_c), hus))
            title = "hus: {} ep: {} bt: {}".format(
                "- " + " -> ".join(hus) + " -", ep, bt
            )
            fb_log, acc_log = log["fb_log"], log["acc_log"]
            xs = np.arange(len(fb_log)) + 1
            plt.figure()
            plt.title(title)
            plt.plot(xs, fb_log)
            plt.plot(xs, acc_log, c="g")
            plt.savefig("Results/img/" + "{}_{}_{}".format(
                "-".join(hus), ep, bt
            ))
            plt.close()
项目:deep-summarization    作者:harpribot    | 项目源码 | 文件源码
def plot_all_metrics(self):
        """

        :return:
        """
        plt.figure()
        self.plot_one_metric(self.bleu_1, 'BLEU Score - 1-Gram')
        plt.figure()
        self.plot_one_metric(self.bleu_2, 'BLEU Score - 2-Gram')
        plt.figure()
        self.plot_one_metric(self.bleu_3, 'BLEU Score - 3-Gram')
        plt.figure()
        self.plot_one_metric(self.bleu_4, 'BLEU Score - 4-Gram')
        plt.figure()
        self.plot_one_metric(self.rouge, 'ROUGE Score')
项目:RandTerrainPy    作者:jackromo    | 项目源码 | 文件源码
def display_terrain(self):
        """Display 3D surface of terrain."""
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        ax.plot_surface(self.x_grid, self.y_grid, self.z_grid)
        ax.set_zlim(0.0, 1.0)
        plt.show()
项目:lang-reps    作者:chaitanyamalaviya    | 项目源码 | 文件源码
def heatmap(src_sent, tgt_sent, att_weights, idx):

    plt.figure(figsize=(8, 6), dpi=80)
    att_probs = np.stack(att_weights, axis=1)

    plt.imshow(att_weights, cmap='gray', interpolation='nearest')
    #src_sent = [ str(s) for s in src_sent]
    #tgt_sent = [ str(s) for s in tgt_sent]
    #plt.xticks(range(0, len(tgt_sent)), tgt_sent, rotation='vertical')
    #plt.yticks(range(0, len(src_sent)), src_sent)
    plt.xticks(range(0, len(tgt_sent)),"")
    plt.yticks(range(0, len(src_sent)),"")
    plt.axis('off')
    plt.savefig("att_matrix_"+str(idx), bbox_inches='tight')
    plt.close()
项目:almond-nnparser    作者:Stanford-Mobisocial-IoT-Lab    | 项目源码 | 文件源码
def show_pca(X, sentences):
    plt.figure()
    plt.plot(X[:,0], X[:,1], 'x')

    for x, sentence in zip(X, sentences):
        plt.text(x[0]-0.01, x[1]-0.01, sentence, horizontalalignment='center', verticalalignment='top')

    plt.show()
项目:almond-nnparser    作者:Stanford-Mobisocial-IoT-Lab    | 项目源码 | 文件源码
def show_pca(X, sentences):
    plt.figure()
    plt.plot(X[:,0], X[:,1], 'x')

    for x, sentence in zip(X, sentences):
        plt.text(x[0]+0.01, x[1]-0.01, sentence, horizontalalignment='left', verticalalignment='top')

    plt.show()
项目:almond-nnparser    作者:Stanford-Mobisocial-IoT-Lab    | 项目源码 | 文件源码
def show_pca(X, programs):
    plt.figure()
    plt.plot(X[:,0], X[:,1], 'x')

    for x, program in zip(X, programs):
        plt.text(x[0]-0.01, x[1]-0.01, program, horizontalalignment='center', verticalalignment='top')

    plt.show()
项目:pyfds    作者:emtpb    | 项目源码 | 文件源码
def show_setup(self, halt=True):
        """Open a plot window that shows the simulation setup including boundaries, outputs and 
        material regions.

        Args:
            halt: Halt script execution until plot window is closed.
        """

        pp.figure()
        self.axes = pp.gca()
        self.axes.set_xlim(0, max(self.field.x.vector) / self._x_axis_factor)
        self.axes.set_ylim(-self.scale, self.scale)
        self.axes.set_xlabel('{0} / {1}m'.format(self.x_label, self._x_axis_prefix))
        self.axes.set_ylabel(self.y_label)
        pp.grid(True)

        if self.show_materials:
            for mat_region in self.field.material_regions:
                self.plot_region(mat_region.region)

        if self.show_boundaries:
            for name, component in self.field_components.items():
                for boundary in component.boundaries:
                    self.plot_region(boundary.region)

        if self.show_output:
            for name, component in self.field_components.items():
                for output in component.outputs:
                    self.plot_region(output.region)

        if halt:
            pp.show()
项目:pyfds    作者:emtpb    | 项目源码 | 文件源码
def show_setup(self, halt=True):
        """Open a plot window that shows the simulation setup including boundaries, outputs and 
        material regions.

        Args:
            halt: Halt script execution until plot window is closed.
        """

        pp.figure()
        self.axes = pp.gca()
        pp.axis('equal')
        self.axes.set_xlim(0, max(self.field.x.vector) / self._x_axis_factor)
        self.axes.set_ylim(0, max(self.field.y.vector) / self._y_axis_factor)
        self.axes.set_xlabel('{0} / {1}m'.format(self.x_label, self._x_axis_prefix))
        self.axes.set_ylabel('{0} / {1}m'.format(self.y_label, self._y_axis_prefix))

        if self.show_materials:
            for mat_region in self.field.material_regions:
                self.plot_region(mat_region.region)

        if self.show_boundaries:
            for name, component in self.field_components.items():
                for boundary in component.boundaries:
                    self.plot_region(boundary.region)

        if self.show_output:
            for name, component in self.field_components.items():
                for output in component.outputs:
                    self.plot_region(output.region)

        if halt:
            pp.show()