Python matplotlib.pyplot.figure() Examples

The following are 50 code examples for showing how to use matplotlib.pyplot.figure(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: lyricswordcloud   Author: qwertyyb   File: analyse.py    (license) View Source Project 11 votes vote down vote up
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() 
Example 2
Project: s2g   Author: caesar0301   File: test.py    (MIT License) View Source Project 8 votes vote down vote up
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() 
Example 3
Project: IgDiscover   Author: NBISweden   File: count.py    (MIT License) View Source Project 7 votes vote down vote up
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 
Example 4
Project: seq2seq   Author: google   File: dump_attention.py    (license) View Source Project 7 votes vote down vote up
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 
Example 5
Project: bob.bio.base   Author: bioidiap   File: evaluate.py    (license) View Source Project 7 votes vote down vote up
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 
Example 6
Project: spyking-circus   Author: spyking-circus   File: plot.py    (license) View Source Project 6 votes vote down vote up
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 
Example 7
Project: spyking-circus   Author: spyking-circus   File: plot.py    (license) View Source Project 6 votes vote down vote up
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 
Example 8
Project: spyking-circus   Author: spyking-circus   File: plot.py    (license) View Source Project 6 votes vote down vote up
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 
Example 9
Project: hippylib   Author: hippylib   File: nb.py    (license) View Source Project 6 votes vote down vote up
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 
Example 10
Project: zipline-chinese   Author: zhanghan1990   File: doubleMA.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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
# 
Example 11
Project: voxcelchain   Author: hiroaki-kaneda   File: voxelchain_visualize.py    (MIT License) View Source Project 6 votes vote down vote up
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") 
Example 12
Project: ward-metrics   Author: phev8   File: visualisations.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 13
Project: Google-QuickDraw   Author: ankonzoid   File: QuickDraw_noisy_classifier.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 14
Project: Google-QuickDraw   Author: ankonzoid   File: QuickDraw_noisy_classifier.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 15
Project: Google-QuickDraw   Author: ankonzoid   File: QuickDraw_noisy_classifier.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 16
Project: sampleRNN_ICLR2017   Author: soroushmehr   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
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') 
Example 17
Project: GraphTime   Author: GlooperLabs   File: simulate.py    (license) View Source Project 6 votes vote down vote up
def draw(self, layout='circular', figsize=None):
        """Draw all graphs that describe the DGM in a common figure

        Parameters
        ----------
        layout : str
            possible are 'circular', 'shell', 'spring'
        figsize : tuple(int)
            tuple of two integers denoting the mpl figsize

        Returns
        -------
        fig : figure
        """
        layouts = {
            'circular': nx.circular_layout,
            'shell': nx.shell_layout,
            'spring': nx.spring_layout
        }
        figsize = (10, 10) if figsize is None else figsize
        fig = plt.figure(figsize=figsize)
        rocls = np.ceil(np.sqrt(len(self.graphs)))
        for i, graph in enumerate(self.graphs):
            ax = fig.add_subplot(rocls, rocls, i+1)
            ax.set_title('Graph ' + str(i+1))
            ax.axis('off')
            ax.set_frame_on(False)
            g = graph.nxGraph
            weights = [abs(g.edge[i][j]['weight']) * 5 for i, j in g.edges()]
            nx.draw_networkx(g, pos=layouts[layout](g), ax=ax, edge_cmap=plt.get_cmap('Reds'),
                             width=2, edge_color=weights)
        return fig 
Example 18
Project: GraphTime   Author: GlooperLabs   File: simulate.py    (license) View Source Project 6 votes vote down vote up
def draw(self, layout='circular', figsize=None):
        """Draw graph in a matplotlib environment

        Parameters
        ----------
        layout : str
            possible are 'circular', 'shell', 'spring'
        figsize : tuple(int)
            tuple of two integers denoting the mpl figsize

        Returns
        -------
        fig : figure
        """
        layouts = {
            'circular': nx.circular_layout,
            'shell': nx.shell_layout,
            'spring': nx.spring_layout
        }
        figsize = (10, 10) if figsize is None else figsize
        fig = plt.figure(figsize=figsize)
        ax = fig.add_subplot(1, 1, 1)
        ax.axis('off')
        ax.set_frame_on(False)
        g = self.nxGraph
        weights = [abs(g.edge[i][j]['weight']) * 5 for i, j in g.edges()]
        nx.draw_networkx(g, pos=layouts[layout](g), ax=ax, edge_cmap=plt.get_cmap('Reds'),
                         width=2, edge_color=weights)
        return fig 
Example 19
Project: vae-npvc   Author: JeremyCCHsu   File: validate.py    (license) View Source Project 6 votes vote down vote up
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]
            )
        )
    ) 
Example 20
Project: pybot   Author: spillai   File: plot_utils.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 21
Project: didi_competition   Author: Heipiao   File: plot_traffic_data.py    (MIT License) View Source Project 6 votes vote down vote up
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") 
Example 22
Project: shenlan   Author: vector-1127   File: wgan.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 23
Project: lung-cancer-detector   Author: YichenGong   File: plot_utils.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 24
Project: CausalGAN   Author: mkocaoglu   File: utils.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 25
Project: bayestsa   Author: thalesians   File: studysv.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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() 
Example 26
Project: polo   Author: adrianveres   File: test.py    (MIT License) View Source Project 6 votes vote down vote up
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) 
Example 27
Project: keras-utilities   Author: cbaziotis   File: callbacks.py    (MIT License) View Source Project 6 votes vote down vote up
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) 
Example 28
Project: keras-utilities   Author: cbaziotis   File: callbacks.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 29
Project: machine-learning   Author: zzw0929   File: logRegres.py    (license) View Source Project 6 votes vote down vote up
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??? 
Example 30
Project: machine-learning   Author: zzw0929   File: treePlotter.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 31
Project: PersonalizedMultitaskLearning   Author: mitmedialab   File: tensorFlowNetwork.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 32
Project: PersonalizedMultitaskLearning   Author: mitmedialab   File: tensorFlowNetworkMultiTask.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 33
Project: photinia   Author: XoriieInpottn   File: tsne.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 34
Project: bob.bio.base   Author: bioidiap   File: evaluate.py    (license) View Source Project 6 votes vote down vote up
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 
Example 35
Project: klineyes   Author: tenstone   File: show_plot.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 36
Project: klineyes   Author: tenstone   File: show_plot.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 37
Project: klineyes   Author: tenstone   File: show_plot.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 38
Project: multimodal_varinf   Author: tmoer   File: chicken.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 39
Project: Flavor-Network   Author: lingcheng99   File: recipe_recommendation.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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) 
Example 40
Project: Flavor-Network   Author: lingcheng99   File: recipe_clustering.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 41
Project: MicroGrids   Author: squoilin   File: Results.py    (European Union Public License 1.1) View Source Project 6 votes vote down vote up
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 
Example 42
Project: MicroGrids   Author: squoilin   File: Results.py    (European Union Public License 1.1) View Source Project 6 votes vote down vote up
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() 
Example 43
Project: compresso   Author: VCG   File: util.py    (MIT License) View Source Project 6 votes vote down vote up
def adj_fig_size(width=10, height=10):
        '''Adjust figsize of plot
        '''

        fig_size = plt.rcParams["figure.figsize"]
        fig_size[0] = width
        fig_size[1] = height
        plt.rcParams["figure.figsize"] = fig_size 
Example 44
Project: MLPractices   Author: carefree0910   File: Networks.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 45
Project: MLPractices   Author: carefree0910   File: Util.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 46
Project: deep-summarization   Author: harpribot   File: plotter.py    (MIT License) View Source Project 5 votes vote down vote up
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') 
Example 47
Project: RandTerrainPy   Author: jackromo   File: terraindisplay.py    (MIT License) View Source Project 5 votes vote down vote up
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() 
Example 48
Project: lang-reps   Author: chaitanyamalaviya   File: util.py    (license) View Source Project 5 votes vote down vote up
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() 
Example 49
Project: almond-nnparser   Author: Stanford-Mobisocial-IoT-Lab   File: run_pca.py    (license) View Source Project 5 votes vote down vote up
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() 
Example 50
Project: almond-nnparser   Author: Stanford-Mobisocial-IoT-Lab   File: run_pca.py    (license) View Source Project 5 votes vote down vote up
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()