Python matplotlib.pyplot.annotate() Examples

The following are 30 code examples of matplotlib.pyplot.annotate(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: dataset.py    From neural-combinatorial-optimization-rl-tensorflow with MIT License 8 votes vote down vote up
def visualize_2D_trip(self, trip):
        plt.figure(figsize=(30,30))
        rcParams.update({'font.size': 22})

        # Plot cities
        plt.scatter(trip[:,0], trip[:,1], s=200)

        # Plot tour
        tour=np.array(list(range(len(trip))) + [0])
        X = trip[tour, 0]
        Y = trip[tour, 1]
        plt.plot(X, Y,"--", markersize=100)

        # Annotate cities with order
        labels = range(len(trip))
        for i, (x, y) in zip(labels,(zip(X,Y))):
            plt.annotate(i,xy=(x, y))  

        plt.xlim(0,100)
        plt.ylim(0,100)
        plt.show()


    # Heatmap of permutations (x=cities; y=steps) 
Example #2
Source File: SimplicialComplex.py    From OpenTDA with Apache License 2.0 8 votes vote down vote up
def drawComplex(origData, ripsComplex, axes=[-6,8,-6,6]):
  plt.clf()
  plt.axis(axes)
  plt.scatter(origData[:,0],origData[:,1]) #plotting just for clarity
  for i, txt in enumerate(origData):
      plt.annotate(i, (origData[i][0]+0.05, origData[i][1])) #add labels

  #add lines for edges
  for edge in [e for e in ripsComplex if len(e)==2]:
      #print(edge)
      pt1,pt2 = [origData[pt] for pt in [n for n in edge]]
      #plt.gca().add_line(plt.Line2D(pt1,pt2))
      line = plt.Polygon([pt1,pt2], closed=None, fill=None, edgecolor='r')
      plt.gca().add_line(line)

  #add triangles
  for triangle in [t for t in ripsComplex if len(t)==3]:
      pt1,pt2,pt3 = [origData[pt] for pt in [n for n in triangle]]
      line = plt.Polygon([pt1,pt2,pt3], closed=False, color="blue",alpha=0.3, fill=True, edgecolor=None)
      plt.gca().add_line(line)
  plt.show() 
Example #3
Source File: FilteredSimplicialComplex.py    From OpenTDA with Apache License 2.0 8 votes vote down vote up
def drawComplex(origData, ripsComplex, axes=[-6,8,-6,6]):
  plt.clf()
  plt.axis(axes)
  plt.scatter(origData[:,0],origData[:,1]) #plotting just for clarity
  for i, txt in enumerate(origData):
      plt.annotate(i, (origData[i][0]+0.05, origData[i][1])) #add labels

  #add lines for edges
  for edge in [e for e in ripsComplex if len(e)==2]:
      #print(edge)
      pt1,pt2 = [origData[pt] for pt in [n for n in edge]]
      #plt.gca().add_line(plt.Line2D(pt1,pt2))
      line = plt.Polygon([pt1,pt2], closed=None, fill=None, edgecolor='r')
      plt.gca().add_line(line)

  #add triangles
  for triangle in [t for t in ripsComplex if len(t)==3]:
      pt1,pt2,pt3 = [origData[pt] for pt in [n for n in triangle]]
      line = plt.Polygon([pt1,pt2,pt3], closed=False, color="blue",alpha=0.3, fill=True, edgecolor=None)
      plt.gca().add_line(line)
  plt.show() 
Example #4
Source File: dataset.py    From neural-combinatorial-optimization-rl-tensorflow with MIT License 7 votes vote down vote up
def visualize_2D_trip(self,trip,tw_open,tw_close):
        plt.figure(figsize=(30,30))
        rcParams.update({'font.size': 22})
        # Plot cities
        colors = ['red'] # Depot is first city
        for i in range(len(tw_open)-1):
            colors.append('blue')
        plt.scatter(trip[:,0], trip[:,1], color=colors, s=200)
        # Plot tour
        tour=np.array(list(range(len(trip))) + [0])
        X = trip[tour, 0]
        Y = trip[tour, 1]
        plt.plot(X, Y,"--", markersize=100)
        # Annotate cities with TW
        tw_open = np.rint(tw_open)
        tw_close = np.rint(tw_close)
        time_window = np.concatenate((tw_open,tw_close),axis=1)
        for tw, (x, y) in zip(time_window,(zip(X,Y))):
            plt.annotate(tw,xy=(x, y))  
        plt.xlim(0,60)
        plt.ylim(0,60)
        plt.show()


    # Heatmap of permutations (x=cities; y=steps) 
Example #5
Source File: visualize.py    From Neural-Network-Projects-with-Python with MIT License 6 votes vote down vote up
def plot_lat_long(df, landmarks, points='Pickup'):
    plt.figure(figsize = (12,12)) # set figure size
    if points == 'pickup':
        plt.plot(list(df.pickup_longitude), list(df.pickup_latitude), '.', markersize=1)
    else:
        plt.plot(list(df.dropoff_longitude), list(df.dropoff_latitude), '.', markersize=1)

    for landmark in landmarks:
        plt.plot(landmarks[landmark][0], landmarks[landmark][1], '*', markersize=15, alpha=1, color='r') # plot landmark location on map
        plt.annotate(landmark, (landmarks[landmark][0]+0.005, landmarks[landmark][1]+0.005), color='r', backgroundcolor='w') # add 0.005 offset on landmark name for aesthetics purposes
  
    plt.title("{} Locations in NYC Illustrated".format(points))
    plt.grid(None)
    plt.xlabel("Latitude")
    plt.ylabel("Longitude")
    plt.show() 
Example #6
Source File: graphEvaluation.py    From TikZ with GNU General Public License v3.0 6 votes vote down vote up
def showFigure(y):
    plot.xlabel('# objects')
    plot.ylabel(y)
    plot.xticks(xs,
                ['1'] + ['']*10 + ['12'] + ['']*11 + ['24'] + ['']*10 + ['36'])
    ys = range(-1,int(MAXIMUMY + 1))
    print MAXIMUMY
    plot.ylim(ymin = -1)
    #plot.axvline(x = 12,ymin = 0,ymax = 24,color = 'k')
    # plot.annotate("Within-sample generalization",
    #               rotation = 90,
    #               xytext = (11.5,10),
    #               xy = (7,10),
    #               arrowprops = dict(facecolor = 'black',shrink = 0.05))
    # plot.annotate("out-of-sample generalization",
    #               rotation = 90,
    #               xytext = (12.5,10),
    #               xy = (12 + 5,10),
    #               arrowprops = dict(facecolor = 'black',shrink = 0.05))
    plot.legend(['SMC+NN (100 particles)','NN (10 particles)','SMC (1000 particles)','LSTM (1000 particles)'], loc = 0, fontsize = 9)
    plot.show() 
Example #7
Source File: runNNet.py    From cs224d with MIT License 6 votes vote down vote up
def plot_cost(train_cost, dev_cost,opts):
    plt.figure(figsize=(6,4))
    plt.title(r"Learning Curve Cost of %s on train/dev set" % opts.model)
    plt.xlabel("SGD Iterations");plt.ylabel(r"Cost");
    plt.ylim(ymin=min(min(train_cost)*0.8, min(dev_cost)*0.8),ymax=max(1.2*max(train_cost), 1.2*max(dev_cost)))
    plt.plot(np.arange(opts.epochs),train_cost, color='b', marker='o', linestyle='-')
    plt.annotate("train curve",xy=(1,train_cost[1]),
                 xytext=(1,train_cost[1]+3),
                 arrowprops=dict(facecolor='green'),
                 horizontalalignment='left',verticalalignment='top')
    
    plt.plot(np.arange(opts.epochs),dev_cost, color='r', marker='o', linestyle='-')
    plt.annotate("dev curve",xy=(45,dev_cost[45]),
                 xytext=(45,dev_cost[45]+3),
                 arrowprops=dict(facecolor='red'),
                 horizontalalignment='left',verticalalignment='top')
    plt.savefig("./figures/%s/%s_learningCurveCost_on_train_dev_set_%d_epochs.png" % (opts.model,opts.model,opts.epochs))
    plt.show()
    plt.close() 
Example #8
Source File: runNNet.py    From cs224d with MIT License 6 votes vote down vote up
def plot_accuracies(train_accuracies, dev_accuracies,opts):
    plt.figure(figsize=(6,4))
    plt.title(r"Learning Curve Accuracies of %s on train/dev set" % opts.model)
    plt.xlabel("SGD Iterations");plt.ylabel(r"Accuracy");
    plt.ylim(ymin=min(min(train_accuracies)*0.8, min(dev_accuracies)*0.8),ymax=max(1.2*max(train_accuracies), 1.2*max(dev_accuracies)))
    plt.plot(np.arange(opts.epochs),train_accuracies, color='b', marker='o', linestyle='-')
    plt.annotate("train curve",xy=(1,train_accuracies[1]),
                 xytext=(1,train_accuracies[1]+0.3),
                 arrowprops=dict(facecolor='green'),
                 horizontalalignment='left',verticalalignment='top')
    
    plt.plot(np.arange(opts.epochs),dev_accuracies, color='r', marker='o', linestyle='-')
    plt.annotate("dev curve",xy=(45,dev_accuracies[45]),
                 xytext=(45,dev_accuracies[45]+0.3),
                 arrowprops=dict(facecolor='red'),
                 horizontalalignment='left',verticalalignment='top')
    plt.savefig("./figures/%s/%s_learningCurve_on_train_dev_set_%d_epochs.png" % (opts.model,opts.model,opts.epochs))
    plt.show()
    plt.close() 
Example #9
Source File: runNNet_dev_wvecDim.py    From cs224d with MIT License 6 votes vote down vote up
def plot_cost_acc(a, b, figname, epochs):
    annotate_size = 0.15
    if figname.startswith('Cost') == True:
        annotate_size *= 30
    
    plt.figure(figsize=(6,4))
    plt.title(figname)
    plt.xlabel("SGD Iterations");plt.ylabel(r"Accuracy or Cost")
    plt.ylim(ymin=min(min(a),min(b))*0.8,ymax=max(max(a),max(b))*1.2)
    plt.plot(np.arange(epochs),a,'bo-')
    plt.annotate("train_curve", xy=(1,a[1]),
                 xytext=(1,a[1]+annotate_size),
                 arrowprops=dict(facecolor='green'),
                 horizontalalignment='left',verticalalignment='top')

    plt.plot(np.arange(epochs),b,'ro-')
    plt.annotate("dev_curve",xy=(50,b[50]),
                 xytext=(50,b[50]+annotate_size),
                 arrowprops=dict(facecolor='red'),
                 horizontalalignment='left',verticalalignment='top')
    plt.savefig("%s_per_epochs.png"%figname)
    plt.close() 
Example #10
Source File: meep_utils.py    From python-meep-utils with GNU General Public License v2.0 6 votes vote down vote up
def annotate_frequency_axis(mark_freq, label_position_y=1, arrow_length=3, log_y=False, freq_range=None):#{{{
    """
    """
    import matplotlib.pyplot as plt
    if type(mark_freq) in (float,int): mark_freq=list(mark_freq,)
    if type(mark_freq) in (list,tuple): mark_freq=dict(zip(mark_freq,['' for mf in mark_freq]))
    for mfreq, mfreqtxt in mark_freq.items(): 
        label_y2 = label_position_y
        while (mfreqtxt[0:1]==' ' and mfreqtxt[-2:-1]==' '): 
            label_y2 = label_y2*2 if log_y else label_y2+1
            mfreqtxt=mfreqtxt[1:-1]; 
        bboxprops   = dict(boxstyle='round, pad=.15', fc='white', alpha=1, lw=0)
        arrowprops  = dict(arrowstyle=('->', '-|>', 'simple', 'fancy')[0], connectionstyle = 'arc3,rad=0', lw=1, ec='k', fc='w')
        if not freq_range  or  (mfreq > freq_range[0] and mfreq < freq_range[1]):
            plt.annotate(mfreqtxt,                    clip_on=True,
                    xy      = (mfreq, label_y2),    xycoords  ='data',
                    # (delete following line if text without arrow is used)
                    xytext  = (mfreq, label_y2*arrow_length if log_y else label_y+arrow_length),  textcoords='data',        
                    ha='center', va='bottom', size=15, color='k',
                    bbox        = bboxprops,        # comment out to disable bounding box
                    arrowprops  = arrowprops,       # comment out to disable arrow
                    )
#}}} 
Example #11
Source File: embedding.py    From voice-vector with MIT License 6 votes vote down vote up
def plot_embedding(embedding, annotation=None, filename='outputs/embedding.png'):
    reduced = TSNE(n_components=2).fit_transform(embedding)
    plt.figure(figsize=(20, 20))
    max_x = np.amax(reduced, axis=0)[0]
    max_y = np.amax(reduced, axis=0)[1]
    plt.xlim((-max_x, max_x))
    plt.ylim((-max_y, max_y))

    plt.scatter(reduced[:, 0], reduced[:, 1], s=20, c=["r"] + ["b"] * (len(reduced) - 1))

    # Annotation
    if annotation:
        for i in range(embedding.shape[0]):
            target = annotation[i]
            x = reduced[i, 0]
            y = reduced[i, 1]
            plt.annotate(target, (x, y))

    plt.savefig(filename)
    # plt.show() 
Example #12
Source File: tsne_visualization.py    From face-recognition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    args = parse_args()
    X, labels = np.loadtxt(args.embeddings_path), np.loadtxt(args.labels_path, dtype=np.str)
    tsne = TSNE(n_components=2, n_iter=10000, perplexity=5, init='pca', learning_rate=200, verbose=1)
    transformed = tsne.fit_transform(X)

    y = set(labels)
    labels = np.array(labels)
    plt.figure(figsize=(20, 14))
    colors = cm.rainbow(np.linspace(0, 1, len(y)))
    for label, color in zip(y, colors):
        points = transformed[labels == label, :]
        plt.scatter(points[:, 0], points[:, 1], c=[color], label=label, s=200, alpha=0.5)
        for p1, p2 in random.sample(list(zip(points[:, 0], points[:, 1])), k=min(1, len(points))):
            plt.annotate(label, (p1, p2), fontsize=30)

    plt.savefig('tsne_visualization.png', transparent=True, bbox_inches='tight', pad_inches=0)
    plt.show() 
Example #13
Source File: sse_visualize.py    From Sequence-Semantic-Embedding with Apache License 2.0 6 votes vote down vote up
def visualize(sseEncodingFile, gneratedImageFile):
    print("Loading embingfile: %s" % sseEncodingFile)
    raw_seq, sse = load_embeddings(sseEncodingFile)
    tsne = TSNE(n_components=2, random_state=0)
    np.set_printoptions(suppress=True)
    print("fitting tsne...")
    Y = tsne.fit_transform(sse)
    print("plotting...")
    ChineseFont = FontProperties('SimHei')
    plt.title("SSE Representations", fontdict={'fontsize': 16})
    plt.figure(figsize=(100, 100))  # in inches
    for label, x, y in zip(raw_seq, Y[:, 0], Y[:, 1]):
        plt.scatter(x,y)
        plt.annotate(label, xy=(x, y), xytext=(5, 2),
                     textcoords='offset points',
                     fontproperties=ChineseFont,
                     ha='right',
                     va='bottom')
    plt.savefig(gneratedImageFile, format='png')
    plt.show() 
Example #14
Source File: PCA_projection_1.02.py    From visually-informed-embedding-of-word-VIEW- with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def projection(embeddings, token_list):
    for k in range(6):
        embeddings=np.concatenate((embeddings, embeddings), axis=0)
    proj = PCA(embeddings)
    PCA_proj=proj.Y
    print PCA_proj.shape
    
    #plotting words within the 2D space of the two principal components:
    list=token_list[0]
    
        
    for n in range(maxlen):
        plt.plot(PCA_proj[n][0]+1,PCA_proj[n][1], 'w.')
        plt.annotate(list[n], xy=(PCA_proj[n][0],PCA_proj[n][1]), xytext=(PCA_proj[n][0],PCA_proj[n][1]))
    plt.show()       
    plt.ishold()
    
  
    return 
Example #15
Source File: PCA_projection_1.01.py    From visually-informed-embedding-of-word-VIEW- with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def projection(embeddings, token_list):
    for k in range(6):
        embeddings=np.concatenate((embeddings, embeddings), axis=0)
    proj = PCA(embeddings)
    PCA_proj=proj.Y
    print PCA_proj.shape
    
    #plotting words within the 2D space of the two principal components:
    list=token_list[0]
    
        
    for n in range(maxlen):
        plt.plot(PCA_proj[n][0]+1,PCA_proj[n][1], 'w.')
        plt.annotate(list[n], xy=(PCA_proj[n][0],PCA_proj[n][1]), xytext=(PCA_proj[n][0],PCA_proj[n][1]))
    plt.show()       
    plt.ishold()
    
  
    return 
Example #16
Source File: visualize.py    From KATE with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def word_cloud(word_embedding_matrix, vocab, s, save_file='scatter.png'):
    words = [(i, vocab[i]) for i in s]
    model = TSNE(n_components=2, random_state=0)
    #Note that the following line might use a good chunk of RAM
    tsne_embedding = model.fit_transform(word_embedding_matrix)
    words_vectors = tsne_embedding[np.array([item[1] for item in words])]

    plt.subplots_adjust(bottom = 0.1)
    plt.scatter(
        words_vectors[:, 0], words_vectors[:, 1], marker='o', cmap=plt.get_cmap('Spectral'))

    for label, x, y in zip(s, words_vectors[:, 0], words_vectors[:, 1]):
        plt.annotate(
            label,
            xy=(x, y), xytext=(-20, 20),
            textcoords='offset points', ha='right', va='bottom',
            fontsize=20,
            # bbox=dict(boxstyle='round,pad=1.', fc='yellow', alpha=0.5),
            arrowprops=dict(arrowstyle = '<-', connectionstyle='arc3,rad=0')
            )
    plt.show()
    # plt.savefig(save_file) 
Example #17
Source File: plotting.py    From OpenTDA with Apache License 2.0 6 votes vote down vote up
def drawComplex(data, ph, axes=[-6, 8, -6, 6]):
    plt.clf()
    plt.axis(axes)  # axes = [x1, x2, y1, y2]
    plt.scatter(data[:, 0], data[:, 1])  # plotting just for clarity
    for i, txt in enumerate(data):
        plt.annotate(i, (data[i][0] + 0.05, data[i][1]))  # add labels

    # add lines for edges
    for edge in [e for e in ph.ripsComplex if len(e) == 2]:
        # print(edge)
        pt1, pt2 = [data[pt] for pt in [n for n in edge]]
        # plt.gca().add_line(plt.Line2D(pt1,pt2))
        line = plt.Polygon([pt1, pt2], closed=None, fill=None, edgecolor='r')
        plt.gca().add_line(line)

    # add triangles
    for triangle in [t for t in ph.ripsComplex if len(t) == 3]:
        pt1, pt2, pt3 = [data[pt] for pt in [n for n in triangle]]
        line = plt.Polygon([pt1, pt2, pt3], closed=False,
                           color="blue", alpha=0.3, fill=True, edgecolor=None)
        plt.gca().add_line(line)
    plt.show() 
Example #18
Source File: run_visual.py    From time-series-machine-learning with Apache License 2.0 6 votes vote down vote up
def main():
  train_date = None
  tickers, periods, targets = parse_command_line(default_tickers=['BTC_ETH', 'BTC_LTC'],
                                                 default_periods=['day'],
                                                 default_targets=['high'])

  for ticker in tickers:
    for period in periods:
      for target in targets:
        job = JobInfo('_data', '_zoo', name='%s_%s' % (ticker, period), target=target)
        result_df = predict_multiple(job, raw_df=read_df(job.get_source_name()), rows_to_predict=120)
        result_df.index.names = ['']
        result_df.plot(title=job.name)

        if train_date is not None:
          x = train_date
          y = result_df['True'].min()
          plt.axvline(x, color='k', linestyle='--')
          plt.annotate('Training stop', xy=(x, y), xytext=(result_df.index.min(), y), color='k',
                       arrowprops={'arrowstyle': '->', 'connectionstyle': 'arc3', 'color': 'k'})

  plt.show() 
Example #19
Source File: viz2d.py    From obman_train with GNU General Public License v3.0 6 votes vote down vote up
def visualize_joints_2d(
    ax, joints, joint_idxs=True, links=None, alpha=1, scatter=True, linewidth=2
):
    if links is None:
        links = [
            (0, 1, 2, 3, 4),
            (0, 5, 6, 7, 8),
            (0, 9, 10, 11, 12),
            (0, 13, 14, 15, 16),
            (0, 17, 18, 19, 20),
        ]
    # Scatter hand joints on image
    x = joints[:, 0]
    y = joints[:, 1]
    if scatter:
        ax.scatter(x, y, 1, "r")

    # Add idx labels to joints
    for row_idx, row in enumerate(joints):
        if joint_idxs:
            plt.annotate(str(row_idx), (row[0], row[1]))
    _draw2djoints(ax, joints, links, alpha=alpha, linewidth=linewidth)
    ax.axis("equal") 
Example #20
Source File: aco_tsp.py    From aco-tsp with MIT License 6 votes vote down vote up
def plot(self, line_width=1, point_radius=math.sqrt(2.0), annotation_size=8, dpi=120, save=True, name=None):
        x = [self.nodes[i][0] for i in self.global_best_tour]
        x.append(x[0])
        y = [self.nodes[i][1] for i in self.global_best_tour]
        y.append(y[0])
        plt.plot(x, y, linewidth=line_width)
        plt.scatter(x, y, s=math.pi * (point_radius ** 2.0))
        plt.title(self.mode)
        for i in self.global_best_tour:
            plt.annotate(self.labels[i], self.nodes[i], size=annotation_size)
        if save:
            if name is None:
                name = '{0}.png'.format(self.mode)
            plt.savefig(name, dpi=dpi)
        plt.show()
        plt.gcf().clear() 
Example #21
Source File: plotter.py    From imgcomp-cvpr with GNU General Public License v3.0 6 votes vote down vote up
def plot_ours_mean(measures_readers, metric, color, show_ids):
    if not show_ids:
        show_ids = []
    ops = []
    for first, measures_reader in flag_first_iter(measures_readers):
        this_op_bpps = []
        this_op_values = []
        for img_name, bpp, value in measures_reader.iter_metric(metric):
            this_op_bpps.append(bpp)
            this_op_values.append(value)
        ours_mean_bpp, ours_mean_value = np.mean(this_op_bpps), np.mean(this_op_values)
        ops.append((ours_mean_bpp, ours_mean_value))
        plt.scatter(ours_mean_bpp, ours_mean_value, marker='x', zorder=10, color=color,
                    label='Ours' if first else None)
    for (bpp, value), job_id in zip(sorted(ops), show_ids):
        plt.annotate(job_id, (bpp + 0.04, value),
                     horizontalalignment='bottom', verticalalignment='center') 
Example #22
Source File: convergence.py    From PyChemia with MIT License 5 votes vote down vote up
def plot(self, filedir=None, file_format='pdf'):
        if filedir is None:
            filedir = self.workdir
        figname = filedir + os.sep + 'convergence.' + file_format
        return self._convergence_plot(variable='encut', xlabel='ENCUT', title='ENCUT Convergence', figname=figname,
                                      annotate='encut') 
Example #23
Source File: convergence.py    From PyChemia with MIT License 5 votes vote down vote up
def plot(self, filedir=None, file_format='pdf'):
        if filedir is None:
            filedir = self.workdir
        figname = filedir + os.sep + 'convergence.' + file_format

        return self._convergence_plot(variable='kp_density', xlabel='K-points density', title='KPOINTS Convergence',
                                      figname=figname, annotate='kp_grid') 
Example #24
Source File: convergence.py    From PyChemia with MIT License 5 votes vote down vote up
def _convergence_plot(self, variable, xlabel, title, figname, annotate):

        import matplotlib.pyplot as plt
        if not self.is_converge:
            print('Convergence not executed')
            return

        x = [idata[variable] for idata in self.convergence_info]
        y = [idata['free_energy'] for idata in self.convergence_info]
        plt.figure(figsize=(10, 8))
        plt.clf()
        plt.plot(x, y, 'rd-')
        dy = self.energy_tolerance
        sup_dy = min(y[-3:]) + dy
        low_dy = max(y[-3:]) - dy
        xlims = plt.xlim()
        plt.plot(xlims, [sup_dy, sup_dy], '0.5')
        plt.plot(xlims, [low_dy, low_dy], '0.5')
        plt.fill_between(xlims, [low_dy, low_dy], [sup_dy, sup_dy], color='0.9', alpha=0.5)
        assert (self.convergence_info is not None)
        for idata in self.convergence_info:
            plt.annotate(s=str(idata[annotate]), xy=(idata[variable], idata['free_energy']), size=10)

        plt.xlim(*xlims)
        plt.title(title)
        plt.xlabel(xlabel)
        plt.ylabel('Free Energy [eV]')
        plt.savefig(figname)
        return plt.gca() 
Example #25
Source File: plot.py    From 2018-CCF-BDCI-China-Unicom-Research-Institute-top2 with MIT License 5 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= (10, 18))
    for i, label in enumerate(labels):
        x, y = low_dim_embs[i, :]
        plt.scatter(x, y)
        plt.annotate(label, xy = (x, y), textcoords = 'offset points', ha = 'right', va = 'bottom')
    plt.savefig(filename) 
Example #26
Source File: maps.py    From pastas with MIT License 5 votes vote down vote up
def series(self, kind="stresses", label=False, **kwargs):
        """Plot the location of the oseries or the stresses on a map.

        Parameters
        ----------
        kind: str
            kind of series to plot. Possible values are the oseries,
            stresses or a specific type of stress (e.g. prec, evap or well).
        label: bool, optional
            Display a label next to the point with the name of the series.
        kwargs: dict, optional
            Any keyword arguments are passed on to plt.scatter.

        Returns
        -------
        sc: matplotlib.axes
            Return the axes.

        """
        if kind == "oseries":
            series = self.mls.oseries
        elif kind == "stresses":
            series = self.mls.stresses
        else:
            series = self.mls.stresses.loc[self.mls.stresses.kind == kind]

        x = series.loc[:, "x"].astype(float)
        y = series.loc[:, "y"].astype(float)

        sc = plt.scatter(x, y, **kwargs)

        if label:
            for name, xy in zip(x.index, zip(x, y)):
                plt.annotate(s=name, xy=xy, fontsize=10,
                             bbox=dict(facecolor='w', edgecolor='k'),
                             textcoords="offset points", xytext=(10, 10))

        return sc 
Example #27
Source File: som.py    From som with MIT License 5 votes vote down vote up
def plot_density_map(self, data, colormap='Oranges', filename=None, example_dict=None, internal=False):
        """ Visualize the data density in different areas of the SOM.

        :param data: {numpy.ndarray} data to visualize the SOM density (number of times a neuron was winner)
        :param colormap: {str} colormap to use, select from matplolib sequential colormaps
        :param filename: {str} optional, if given, the plot is saved to this location
        :param example_dict: {dict} dictionary containing names of examples as keys and corresponding descriptor values
            as values. These examples will be mapped onto the density map and marked
        :param internal: {bool} if True, the current plot will stay open to be used for other plot functions
        :return: plot shown or saved if a filename is given
        """
        wm = self.winner_map(data)
        fig, ax = plt.subplots(figsize=self.shape)
        plt.pcolormesh(wm, cmap=colormap, edgecolors=None)
        plt.colorbar()
        plt.xticks(np.arange(.5, self.x + .5), range(self.x))
        plt.yticks(np.arange(.5, self.y + .5), range(self.y))
        ax.set_aspect('equal')

        if example_dict:
            for k, v in example_dict.items():
                w = self.winner(v)
                x = w[1] + 0.5 + np.random.normal(0, 0.15)
                y = w[0] + 0.5 + np.random.normal(0, 0.15)
                plt.plot(x, y, marker='*', color='#FDBC1C', markersize=24)
                plt.annotate(k, xy=(x + 0.5, y - 0.18), textcoords='data', fontsize=18, fontweight='bold')

        if not internal:
            if filename:
                plt.savefig(filename)
                plt.close()
                print("Density map plot done!")
            else:
                plt.show()
        else:
            return fig, ax 
Example #28
Source File: application.py    From seasonal with MIT License 5 votes vote down vote up
def _periodogram_plot(title, column, data, trend, peaks):
    """display periodogram results using matplotlib"""

    periods, power = periodogram(data)
    plt.figure(1)
    plt.subplot(311)
    plt.title(title)
    plt.plot(data, label=column)
    if trend is not None:
        plt.plot(trend, linewidth=3, label="broad trend")
        plt.legend()
        plt.subplot(312)
        plt.title("detrended")
        plt.plot(data - trend)
    else:
        plt.legend()
        plt.subplot(312)
        plt.title("(no detrending specified)")
    plt.subplot(313)
    plt.title("periodogram")
    plt.stem(periods, power)
    for peak in peaks:
        period, score, pmin, pmax = peak
        plt.axvline(period, linestyle='dashed', linewidth=2)
        plt.axvspan(pmin, pmax, alpha=0.2, color='b')
        plt.annotate("{}".format(period), (period, score * 0.8))
        plt.annotate("{}...{}".format(pmin, pmax), (pmin, score * 0.5))
    plt.tight_layout()
    plt.show() 
Example #29
Source File: dataset_visualizer.py    From blockchain-predictor with MIT License 5 votes vote down vote up
def createAnimation(frames, dates):
	fig = plt.figure()
	ax = fig.add_subplot(111)

	ims = []

	#for i, frame in enumerate(frames):
	#	im = plt.imshow(frame, animated=True)
	#	tit = plt.annotate(str(dates[i]), (-1,-1), animated=True)
	#	#cb = plt.colorbar()
	#	ims.append([im, tit])
	cv0 = frames[0]
	im = ax.imshow(cv0, origin='lower') # Here make an AxesImage rather than contour
	cb = fig.colorbar(im)
	tx = ax.set_title(str(dates[0]))

	def animate(i):
		arr = frames[i]
		vmax     = np.max(arr)
		vmin     = np.min(arr)
		im.set_data(arr)
		im.set_clim(vmin, vmax)
		tx.set_text(str(dates[i]))

	ani = animation.FuncAnimation(fig, animate, frames=len(frames), interval=1)

	global args

	ani.save(args.renderTimelapse) 
Example #30
Source File: som.py    From som with MIT License 5 votes vote down vote up
def plot_class_density(self, data, targets, t=1, name='actives', colormap='Oranges', example_dict=None,
                           filename=None):
        """ Plot a density map only for the given class

        :param data: {numpy.ndarray} data to visualize the SOM density (number of times a neuron was winner)
        :param targets: {list/array} array of target classes (0 to len(targetnames)) corresponding to data
        :param t: {int} target class to plot the density map for
        :param name: {str} target name corresponding to target given in t
        :param colormap: {str} colormap to use, select from matplolib sequential colormaps
        :param example_dict: {dict} dictionary containing names of examples as keys and corresponding descriptor values
            as values. These examples will be mapped onto the density map and marked
        :param filename: {str} optional, if given, the plot is saved to this location
        :return: plot shown or saved if a filename is given
        """
        targets = np.array(targets)
        t_data = data[np.where(targets == t)[0]]
        wm = self.winner_map(t_data)
        fig, ax = plt.subplots(figsize=self.shape)
        plt.pcolormesh(wm, cmap=colormap, edgecolors=None)
        plt.colorbar()
        plt.xticks(np.arange(.5, self.x + .5), range(self.x))
        plt.yticks(np.arange(.5, self.y + .5), range(self.y))
        plt.title(name, fontweight='bold', fontsize=28)
        ax.set_aspect('equal')
        plt.text(0.1, -1., "%i Datapoints" % len(t_data), fontsize=20, fontweight='bold')

        if example_dict:
            for k, v in example_dict.items():
                w = self.winner(v)
                x = w[1] + 0.5 + np.random.normal(0, 0.15)
                y = w[0] + 0.5 + np.random.normal(0, 0.15)
                plt.plot(x, y, marker='*', color='#FDBC1C', markersize=24)
                plt.annotate(k, xy=(x + 0.5, y - 0.18), textcoords='data', fontsize=18, fontweight='bold')

        if filename:
            plt.savefig(filename)
            plt.close()
            print("Class density plot done!")
        else:
            plt.show()