Python matplotlib.pyplot.annotate() Examples

The following are code examples for showing how to use matplotlib.pyplot.annotate(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: rtreelib   Author: sergkr   File: diagram.py    MIT License 6 votes vote down vote up
def _plot_rtree_leaves(ax, tree, highlight_entry=None):
    for entry in tree.get_leaf_entries():
        xy = (entry.rect.min_x, entry.rect.min_y)
        w, h = (entry.rect.width, entry.rect.height)
        highlight = entry is highlight_entry
        edgecolor = (0.78, 0.24, 0.52) if highlight else (0.24, 0.52, 0.78)
        facecolor = (0.78, 0.24, 0.52, 0.64) if highlight else (0.24, 0.52, 0.78, 0.5)
        text_color = (0.25, 0.08, 0.17) if highlight else (0.09, 0.19, 0.29)
        text_facecolor = (0.78, 0.24, 0.52, 0.25) if highlight else (0.24, 0.52, 0.78, 0.25)
        patch = patches.Rectangle(xy, w, h, linewidth=1, edgecolor=edgecolor, facecolor=facecolor)
        ax.add_patch(patch)
        plt.annotate(
            s=entry.data,
            color=text_color,
            fontsize=6,
            fontweight='bold',
            xy=xy,
            xytext=(5, 4),
            textcoords='offset pixels',
            bbox=dict(fc=text_facecolor, ec='none', pad=3),
            va='bottom',
            ha='left') 
Example 2
Project: imgcomp-cvpr   Author: fab-jul   File: plotter.py    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 3
Project: NNLM   Author: kanoh-k   File: corpus.py    GNU General Public License v3.0 6 votes vote down vote up
def plot(self, filename="./corpus/model/blog.png"):
        tsne = TSNE(perplexity=30, n_components=2, init="pca", n_iter=5000)
        plot_only=500
        low_dim_embeddings = tsne.fit_transform(self.final_embeddings[:plot_only, :])
        reversed_dictionary = dict(zip(self.dictionary.values(), self.dictionary.keys()))
        labels = [reversed_dictionary[i] for i in range(plot_only)]

        plt.figure(figsize=(18, 18))
        for i, label in enumerate(labels):
            x, y = low_dim_embeddings[i, :]
            plt.scatter(x, y)
            plt.annotate(label,
                        xy=(x, y),
                        xytext=(5, 2),
                        textcoords="offset points",
                        ha="right",
                        va="bottom")
        plt.savefig(filename)
        print("Scatter plot was saved to", filename) 
Example 4
Project: aco-tsp   Author: rochakgupta   File: aco_tsp.py    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 5
Project: OpenTDA   Author: outlace   File: plotting.py    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 6
Project: OpenTDA   Author: outlace   File: SimplicialComplex.py    Apache License 2.0 6 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 7
Project: OpenTDA   Author: outlace   File: FilteredSimplicialComplex.py    Apache License 2.0 6 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 8
Project: AI2-Reasoning-Challenge-ARC   Author: SebiSebi   File: pos_embeddings.py    GNU General Public License v3.0 6 votes vote down vote up
def _show_pca_plot(model):
    import matplotlib.pyplot as plt
    from sklearn.decomposition import PCA

    num_words = len(model.wv.vocab)
    # Lines are words in ND space => a matrix of num_words x size
    # Fit the model and apply the dimensionality reduction.
    data = PCA(n_components=2).fit_transform(model[model.wv.vocab])
    assert(isinstance(data, np.ndarray))
    assert(data.shape[0] == num_words)
    assert(data.shape[1] == 2)

    plt.scatter(data[:, 0], data[:, 1], s=50, c='r', marker='x', linewidth=1)
    words = list(model.wv.vocab)
    for i in range(0, len(words)):
        plt.annotate(' ' + words[i], xy=(data[i, 0], data[i, 1]))
    plt.show() 
Example 9
Project: AI2-Reasoning-Challenge-ARC   Author: SebiSebi   File: dep_embeddings.py    GNU General Public License v3.0 6 votes vote down vote up
def _show_pca_plot(model):
    import matplotlib.pyplot as plt
    from sklearn.decomposition import PCA

    num_words = len(model.wv.vocab)
    # Lines are words in ND space => a matrix of num_words x size
    # Fit the model and apply the dimensionality reduction.
    data = PCA(n_components=2).fit_transform(model[model.wv.vocab])
    assert(isinstance(data, np.ndarray))
    assert(data.shape[0] == num_words)
    assert(data.shape[1] == 2)

    plt.scatter(data[:, 0], data[:, 1], s=50, c='r', marker='x', linewidth=1)
    words = list(model.wv.vocab)
    for i in range(0, len(words)):
        plt.annotate(' ' + words[i], xy=(data[i, 0], data[i, 1]))
    plt.show() 
Example 10
Project: visually-informed-embedding-of-word-VIEW-   Author: oswaldoludwig   File: PCA_projection_1.01.py    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 11
Project: visually-informed-embedding-of-word-VIEW-   Author: oswaldoludwig   File: PCA_projection_1.02.py    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 12
Project: FMC   Author: Jose-Alvarez   File: plotFMC.py    GNU General Public License v3.0 6 votes vote down vote up
def annot(X, Y, size, color, plotname, label, annots, lab_param, spacing):

    fig = circles(X, Y, size, color, plotname, label, spacing)
    for i, txt in enumerate(annots):
        plt.annotate(
            str(txt).strip(".'[]'"),
            (X[i] + 0.01,
             Y[i] + 0.01),
            horizontalalignment='left',
            verticalalignment='bottom',
            rotation=30,
            size='x-small')
        plt.text(
            1.4,
            -0.75,
            'Text label:\n' + str(
                lab_param).strip(
                    "'[]'").replace(
                "_",
                 " "),
                 fontsize=10,
                 horizontalalignment='right',
                 verticalalignment='top')

    return fig 
Example 13
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_distance_arrow(self, ax):
		"""
		Plots two arrows and the 2m label on top of the given axis.
		"""
		ax = plt.gca()
		trans = mpl.transforms.blended_transform_factory(
							ax.transAxes, ax.transAxes)
		plt.annotate(
			 '', xy=(0.35, 1), xycoords=trans,
			xytext=(0, 1), textcoords=trans,
			arrowprops={'arrowstyle': '<-', 'shrinkA': 1, 'shrinkB': 1, 'lw':1.0,
						'mutation_scale': 15., 'color': 'black'})
		plt.annotate(
			 '', xy=(0.65, 1), xycoords=trans,
			xytext=(1, 1), textcoords=trans,
			arrowprops={'arrowstyle': '<-', 'shrinkA': 1, 'shrinkB': 1, 'lw':1.0,
						'mutation_scale': 15., 'color': 'black'})
		plt.text(0.5, 1, '2m', va='center', ha='center', transform=trans) 
Example 14
Project: TensorFlowactual-Practice   Author: Asurada2015   File: 7_1_Word2Vec.py    MIT License 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
  for i, label in enumerate(labels):
    x, y = low_dim_embs[i,:]
    plt.scatter(x, y)
    plt.annotate(label,
                 xy=(x, y),
                 xytext=(5, 2),
                 textcoords='offset points',
                 ha='right',
                 va='bottom')

  plt.savefig(filename)

  #%% 
Example 15
Project: pisa   Author: IceCubeOpenSource   File: plotter.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, outdir='.', stamp=None, size=(8, 8), fmt='pdf',
                 log=True, label='# events', grid=True, ratio=False,
                 annotate=False, symmetric=False, loc='outside'):
        self.fig = None
        self.axes = None

        self.outdir = outdir
        self.stamp = stamp
        if isinstance(fmt, str):
            fmt = [fmt]
        self.fmt = fmt
        self.size = size
        self.fig = None
        self.log = log
        self.label = label
        self.grid = grid
        self.ratio = ratio
        self.annotate = annotate
        if symmetric:
            assert(not self.log), 'cannot do log and symmetric at the same time'
        self.symmetric = symmetric
        self.reset_colors()
        self.color = 'b'
        self.loc = loc 
Example 16
Project: LOFAR-LIM   Author: Bhare8972   File: read_interferometric_PSE.py    MIT License 6 votes vote down vote up
def plot(self, station_set="all"):
        """station_set should be "all", "CS", "RS" """
        file_dataset = self.h5_dataset_opener.get_object()
        
        station_ant_info = self.header.antenna_info_by_station()
        for stat_i, (sname, ant_list) in enumerate(station_ant_info.items()):
            if station_set=="all" or station_set==sname[:2]:
                traces = []
                max = 0.0
                for ant in ant_list:
                    traces.append( np.abs( file_dataset[ ant.antenna_index ] ) )
                    tmax = np.max( traces[-1] )
                    if tmax > max:
                        max = tmax
                    
                for t in traces:
                    plt.plot( np.abs(t)/max+stat_i*1.1, linewidth=3 )
                plt.annotate(sname, (0.0,stat_i*1.1+0.5))
                
        plt.axvline(x=25)
        plt.show() 
Example 17
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 6 votes vote down vote up
def test_pie_center_radius():
    # The slices will be ordered and plotted counter-clockwise.
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    sizes = [15, 30, 45, 10]
    colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
    explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

    plt.pie(sizes, explode=explode, labels=labels, colors=colors,
            autopct='%1.1f%%', shadow=True, startangle=90,
            wedgeprops={'linewidth': 0}, center=(1, 2), radius=1.5)

    plt.annotate("Center point", xy=(1, 2), xytext=(1, 1.5),
                 arrowprops=dict(arrowstyle="->",
                                 connectionstyle="arc3"))
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal') 
Example 18
Project: face-recognition   Author: arsfutura   File: tsne_visualization.py    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 19
Project: convenience_py   Author: ronrest   File: scatter.py    Apache License 2.0 6 votes vote down vote up
def plot_scatter(x, y, ax=None, color=None, alpha=None, size=None, labels=None, title="Scatterplot", figsize=(10,6)):
    # TODO: Add x, and y labels
    # TODO: grid
    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
        fig.suptitle(title, fontsize=15)
    else:
        fig = ax.get_figure()
    ax.scatter(x=x, y=y, c=color, alpha=alpha, s=size)

    # LABEL - each of the points
    if labels is not None:
        for xx, yy, label in zip(x, y, labels):
            plt.annotate(label, xy=(xx, yy), xytext=(7, 0),
                         textcoords='offset points',
                         ha='left', va='center')
    return fig, ax 
Example 20
Project: voice-vector   Author: andabi   File: embedding.py    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 21
Project: helloworld   Author: pip-uninstaller-python   File: matplotlibTest.py    GNU General Public License v2.0 5 votes vote down vote up
def main():
    # line
    x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
    c, s = np.cos(x), np.sin(x)
    plt.figure(1)
    plt.plot(x, c, color="blue", linewidth=1.0, linestyle="-", label="COS", alpha=0.5)  # 自变量, 因变量
    plt.plot(x, s, "r.", label="SIN")  # 正弦  "-"/"r-"/"r."
    plt.title("COS & SIN")
    ax = plt.gca()
    ax.spines["right"].set_color("none")
    ax.spines["top"].set_color("none")
    ax.spines["left"].set_position(("data", 0))  # 横轴位置
    ax.spines["bottom"].set_position(("data", 0))  # 纵轴位置
    ax.xaxis.set_ticks_position("bottom")
    ax.yaxis.set_ticks_position("left")
    plt.xticks([-np.pi, -np.pi / 2.0, np.pi / 2, np.pi],
               [r'$-\pi/2$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$-\pi$'])
    plt.yticks(np.linspace(-1, 1, 5, endpoint=True))
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontsize(16)
        label.set_bbox(dict(facecolor="white", edgecolor="None", alpha=0.2))
    plt.legend(loc="upper left")  # 左上角的显示图标
    plt.grid()  # 网格线
    # plt.axis([-1, 1, -0.5, 1])  # 显示范围
    plt.fill_between(x, np.abs(x) < 0.5, c, c < 0.5, color="green", alpha=0.25)
    t = 1
    plt.plot([t, t], [0, np.cos(t)], "y", linewidth=3, linestyle="--")
    # 注释
    plt.annotate("cos(1)", xy=(t, np.cos(1)), xycoords="data", xytext=(+10, +30),
                 textcoords="offset points", arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=.2"))
    plt.show()


# Scatter --> 散点图 
Example 22
Project: Pesquisas   Author: danilopcarlotti   File: statistical_analysis.py    Apache License 2.0 5 votes vote down vote up
def plotScatter(self, title, xAxis, yAxis,xLabel,yLabel):
		try:
			plt.plot(xAxis, yAxis, 'ro')
		except:
			y = yAxis
			plt.yticks(y, xAxis)
			plt.plot(yAxis,y,'ro')
			for a,b in zip(yAxis,y):
				plt.annotate(a,xy=(a,b))
		plt.xlabel(xLabel)
		plt.ylabel(yLabel)
		plt.title(title)
		plt.savefig(title+".png", dpi=80) 
Example 23
Project: scicast   Author: iandriver   File: cluster.py    MIT License 5 votes vote down vote up
def augmented_dendrogram(*args, **kwargs):
    plt.clf()
    ddata = dendrogram(*args, **kwargs)

    if not kwargs.get('no_plot', False):
        for i, d in zip(ddata['icoord'], ddata['dcoord'], ):
            x = 0.5 * sum(i[1:3])
            y = d[1]
            if y >= 200000:
                plt.plot(x, y, 'ro')
                plt.annotate("%.3g" % y, (x, y), xytext=(0, -8),
                         textcoords='offset points',
                         va='top', ha='center')
    plt.show()
    plt.savefig(os.path.join(new_file,'augmented_dendrogram.png')) 
Example 24
Project: wtfrnn   Author: juliakreutzer   File: w2v.py    MIT License 5 votes vote down vote up
def plot_with_labels(low_dim_embs, labels, filename="plots/.tsne.png"):
  assert low_dim_embs.shape[0] >= len(labels), "More labels than embeddings"
  plt.figure(figsize=(18, 18))  #in inches
  for i, label in enumerate(labels):
    x, y = low_dim_embs[i,:]
    plt.scatter(x, y)
    plt.annotate(label,
                 xy=(x, y),
                 xytext=(5, 2),
                 textcoords='offset points',
                 ha='right',
                 va='bottom')
  plt.savefig(filename) 
Example 25
Project: DPC   Author: TengdaHan   File: utils.py    MIT License 5 votes vote down vote up
def plot_mat(self, path, dictionary=None, annotate=False):
        plt.figure(dpi=600)
        plt.imshow(self.mat,
            cmap=plt.cm.jet,
            interpolation=None,
            extent=(0.5, np.shape(self.mat)[0]+0.5, np.shape(self.mat)[1]+0.5, 0.5))
        width, height = self.mat.shape
        if annotate:
            for x in range(width):
                for y in range(height):
                    plt.annotate(str(int(self.mat[x][y])), xy=(y+1, x+1),
                                 horizontalalignment='center',
                                 verticalalignment='center',
                                 fontsize=8)

        if dictionary is not None:
            plt.xticks([i+1 for i in range(width)],
                       [dictionary[i] for i in range(width)],
                       rotation='vertical')
            plt.yticks([i+1 for i in range(height)],
                       [dictionary[i] for i in range(height)])
        plt.xlabel('Ground Truth')
        plt.ylabel('Prediction')
        plt.colorbar()
        plt.tight_layout()
        plt.savefig(path, format='svg')
        plt.clf()

        # for i in range(width):
        #     if np.sum(self.mat[i,:]) != 0:
        #         self.precision.append(self.mat[i,i] / np.sum(self.mat[i,:]))
        #     if np.sum(self.mat[:,i]) != 0:
        #         self.recall.append(self.mat[i,i] / np.sum(self.mat[:,i]))
        # print('Average Precision: %0.4f' % np.mean(self.precision))
        # print('Average Recall: %0.4f' % np.mean(self.recall)) 
Example 26
Project: student-resources   Author: djgroen   File: make-animation.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_location():
    # sample data in data directory
    location_df = pd.read_csv('%s/locations.csv' % data_path, index_col="#name")
    city_names = location_df.index.tolist()
    x = location_df.x
    y = location_df.y
    plt.scatter(x, y, s=300, alpha=0.5)
    # label the points with the city names
    for i, txt in enumerate(city_names):
        plt.annotate(txt, (x[i], y[i]), xytext=(5, 5), textcoords='offset points', fontsize='12') 
Example 27
Project: kor2vec   Author: dongjun-Lee   File: visualization.py    MIT License 5 votes vote down vote up
def plot_with_labels(embeds, labels, filename="output.png"):
    plt.figure(figsize=(18, 18))
    pca = decomposition.PCA(n_components=2)
    pca.fit(embeds)
    Y = pca.transform(embeds)
    for i, label in enumerate(labels):
        x, y = Y[i, :]
        plt.scatter(x, y)
        plt.annotate(label,
                     xy=(x, y),
                     xytext=(5, 2),
                     textcoords='offset points',
                     ha='right',
                     va='bottom')
        plt.savefig(filename) 
Example 28
Project: lmdiag   Author: dynobo   File: plot.py    MIT License 5 votes vote down vote up
def resid_fit(lm):
    """Draw Residuals vs. Fitted Values Plot."""
    verify_input(lm)

    # Calculate values for scatter points
    fitted = get_fitted_values(lm)
    residuals = get_residuals(lm)

    # Calculate lowess for smoothing line
    grid, yhat = lowess(residuals, fitted).T

    # Get top three observations for annotation
    top_3 = np.abs(residuals).argsort()[-3:][::1]

    # Draw scatter and lowess line
    plt.plot([fitted.min(), fitted.max()], [0, 0], 'k:')
    plt.plot(grid, yhat, 'r-')
    plt.plot(fitted,
             residuals,
             'o',
             mec=edge_col,
             markeredgewidth=1,
             fillstyle='none')

    # Draw Annotations
    for point in top_3:
        plt.annotate(point,
                     xy=(fitted[point], residuals[point]),
                     color='r')

    # Set Labels
    plt.title('Residual vs. Fitted', fontsize=title_size)
    plt.xlabel('Fitted values')
    plt.ylabel('Residuals')

    return plt 
Example 29
Project: lmdiag   Author: dynobo   File: plot.py    MIT License 5 votes vote down vote up
def scale_loc(lm):
    """Draw Scale-Location Plot."""
    verify_input(lm)

    # Get Fitted Values
    fitted_vals = get_fitted_values(lm)
    sqrt_abs_res = get_sqrt_abs_residuals(lm)

    # Get top three observations for annotation
    top_3 = sqrt_abs_res.argsort()[-3:][::1]

    # Calculate lowess for smoothing line
    grid, yhat = lowess(sqrt_abs_res, fitted_vals).T

    # Draw scatter and lowess line
    plt.plot(grid, yhat, 'r-')
    plt.plot(fitted_vals,
             sqrt_abs_res,
             'o',
             mec=edge_col,
             markeredgewidth=1,
             fillstyle='none')

    # Draw Annotations
    for point in top_3:
        plt.annotate(point,
                     xy=(fitted_vals[point], sqrt_abs_res[point]),
                     color='r')

    # Set Labels
    plt.title('Scale-Location', fontsize=title_size)
    plt.xlabel('Fitted values')
    plt.ylabel(r'$\sqrt{\left|Standardized\ residuals\right|}$')

    return plt 
Example 30
Project: ml-deepranking   Author: urakozz   File: visualsearch_train.py    MIT License 5 votes vote down vote up
def plot_with_labels(low_dim_embs, labels, filename='tsne_c5s5r5.png'):
    assert low_dim_embs.shape[0] >= len(labels), "More labels than embeddings"
    colors = cm.rainbow(np.linspace(0, 1, len(np.unique(np.array(labels)))))
    plt.figure(figsize=(18, 18))  #in inches
    for i, label in enumerate(labels):
        x, y = low_dim_embs[i,:]
        plt.scatter(x, y, color=colors[label])
        plt.annotate(label,
                     xy=(x, y),
                     xytext=(5, 2),
                     textcoords='offset points',
                     ha='right',
                     va='bottom')

    plt.savefig(filename) 
Example 31
Project: marine-phage-paper-scripts   Author: nanoporetech   File: cluster_ani.py    Mozilla Public License 2.0 5 votes vote down vote up
def fancy_dendrogram(*args, **kwargs):
    max_d = kwargs.pop('max_d', None)
    if max_d and 'color_threshold' not in kwargs:
        kwargs['color_threshold'] = max_d
    annotate_above = kwargs.pop('annotate_above', 0)

    ddata = sch.dendrogram(*args, **kwargs)

    if not kwargs.get('no_plot', False):
        # plt.title('Hierarchical Clustering Dendrogram (truncated)')
        # plt.xlabel('sample index or (cluster size)')
        # plt.ylabel('distance')
        plt.xticks([])
        plt.yticks([])
        
        for i, d, c in zip(ddata['icoord'], ddata['dcoord'], ddata['color_list']):
            x = 0.5 * sum(i[1:3])
            y = d[1]
            if y > annotate_above:
                plt.plot(x, y, 'o', c=c)
                # plt.annotate("%.3g" % y, (x, y), xytext=(0, -5),
                #              textcoords='offset points',
                #              va='top', ha='center')
        if max_d:
            plt.axhline(y=max_d, c='k')
    ax = plt.gca()
    ax.spines['left'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    return ddata 
Example 32
Project: Roy-Coinbase-Trader   Author: gincarbone   File: botindicators.py    GNU General Public License v3.0 5 votes vote down vote up
def plot(self, prices, emaSlow, emaFast):
		
		#z = [1.1, 1.2, 1.3]

		#times = pd.date_range('2015-10-06', periods=500, freq='5sec')
		try:
			os.remove("operate.png")
		except OSError:
			pass

		plt.xlabel("Data Time")
		plt.ylabel("Values")
		plt.title("A test graph")

		#plt.ion()
		#plt.clear()

		plt.figure(1)
		plt.subplot(211)
		plt.plot(prices)

		plt.subplot(212)
		plt.plot(emaSlow, 'b--')

		#plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),arrowprops=dict(facecolor='black', shrink=0.05),)

		plt.subplot(212)
		plt.plot(emaFast, 'r--')

		plt.xlabel("Data Time")
		plt.ylabel("Values")
		plt.title("A test graph")
		#plt.savefig("operate.png")
		plt.draw()
		plt.show() 
Example 33
Project: Roy-Coinbase-Trader   Author: gincarbone   File: botindicators.py    GNU General Public License v3.0 5 votes vote down vote up
def plot2(self, prices, signals, emaSlow, emaFast, RSI):
		
		# PRICES
		self.ax.clear()
		self.ax.grid(True)
		self.ax.plot(prices)
		
		#if interpolation == "yes":
		#	x_smooth = np.linspace(prices.min(), prices.max(), 200)
		#	y_smooth = spline(prices, prices, x_smooth)


		#EMASLOW EMAFAST
		self.ax1.clear()
		self.ax1.grid(True)
		self.ax1.plot(emaSlow, 'r--')
		self.ax1.plot(emaFast, 'b-')
		

		# PLOT RSI
		#self.ax2.clear()
		self.ax2.plot((RSI), 'g--')
		
		for idx, a in enumerate (signals):
			if not a[3]:
				self.ax.annotate(a[2],
							xy=(idx, a[1]), xycoords='data',
							xytext=(-60, 30), textcoords='offset points',
							bbox=dict(boxstyle="round", fc="0.8"),
							arrowprops=dict(arrowstyle="->",facecolor='red',
											connectionstyle="angle,angleA=0,angleB=90,rad=10"))
			

		plt.draw()

		#plt.show()
		plt.savefig("www/operatorio.png") 
Example 34
Project: Roy-Coinbase-Trader   Author: gincarbone   File: botindicators.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_annotation(self, text, x, y, color ):
		
		self.ax.annotate(text, xy=(x, y), xytext=(3, 1.5),arrowprops=dict(facecolor=color, shrink=0.05),)

		plt.draw()
		plt.savefig("www/operatorio.png")


		#ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05) ) 
Example 35
Project: HMM   Author: birlrobotics   File: hmm_model_train_real_baxter.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def matplot_list(list_data,
                 figure_index,
                 title,
                 label_string,
                 save=False,
                 linewidth='3.0'):
    # if you want to save, title is necessary as a save name.
    
    global n_state
    global covariance_type_string
    plt.figure(figure_index, figsize=(40,30), dpi=80)
    ax = plt.subplot(111)
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['bottom'].set_position(('data',0))
    plt.grid(True)
    i = 0
    for data in list_data:
        i = i + 1
        index = np.asarray(data).shape
        O = (np.arange(index[0])*0.01).tolist()
        plt.plot(O, data, label=label_string[i-1],linewidth=linewidth)
    plt.legend(loc='best', frameon=True)

    plt.title(title)

    plt.annotate('State=4 Sub_State='+str(n_state)+' GaussianHMM_cov='+covariance_type_string,
             xy=(0, 0), xycoords='data',
             xytext=(+10, +30), textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

    if save:
        plt.savefig(title+".eps", format="eps") 
Example 36
Project: HMM   Author: birlrobotics   File: csv_to_data.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def matplot_list(list_data,
                 figure_index,
                 title,
                 label_string,
                 save=False,
                 linewidth='3.0'):
    # if you want to save, title is necessary as a save name.
    
    global n_state
    global covariance_type_string
    plt.figure(figure_index, figsize=(40,30), dpi=80)
    ax = plt.subplot(111)
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['bottom'].set_position(('data',0))
    plt.grid(True)
    i = 0
    for data in list_data:
        i = i + 1
        index = np.asarray(data).shape
        O = (np.arange(index[0])*0.01).tolist()
        plt.plot(O, data, label=label_string[i-1],linewidth=linewidth)
    plt.legend(loc='best', frameon=True)

    plt.title(title)

    plt.annotate('State=4 Sub_State='+str(n_state)+' GaussianHMM_cov='+covariance_type_string,
             xy=(0, 0), xycoords='data',
             xytext=(+10, +30), textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

    if save:
        plt.savefig(title+".eps", format="eps") 
Example 37
Project: spatial_patterns   Author: sim-web   File: plotting.py    GNU General Public License v3.0 5 votes vote down vote up
def indicate_grid_spacing(self, maxima_positions, y):
        """
        Plots an arrow between two most central peaks and labels it

        Parameters
        ----------
        maxima_positions : ndarray
            Positions of all ocurring maxima
        y : float
            Vertical position of array in data coordinates
        """
        # Number of maxima
        n_maxima = len(maxima_positions)
        # Index of most central maximum
        central_index = int(np.floor(n_maxima/2.))
        # The two most central maxima positions
        central_maxima_pos = maxima_positions[central_index-1:central_index+1]
        # Plot the arrow
        # Note: mutation_scale can adjust the arrow head size in relation
        # to the arrow size. I don't know what a particular value means.
        # It might be percentage.
        plt.annotate(
             '', xy=(central_maxima_pos[0], y), xycoords='data',
            xytext=(central_maxima_pos[1], y), textcoords='data',
            arrowprops={'arrowstyle': '<->', 'shrinkA': 1, 'shrinkB': 1,
                        'mutation_scale': 5.})
        # Plot the text label. xytext is used as an offset here
        plt.annotate(r'$\ell$',
            xy=((central_maxima_pos[1]+central_maxima_pos[0])/2, y),
            xycoords='data',
            xytext=(0, 2), textcoords='offset points',
            ha='center') 
Example 38
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 5 votes vote down vote up
def grid_score_arrow(grid_score, color):
	if not np.isnan(grid_score):
		ax = plt.gca()
		trans = mpl.transforms.blended_transform_factory(
							ax.transData, ax.transAxes)
		plt.annotate(
			 '', xy=(grid_score, 0.25), xycoords=trans,
			xytext=(grid_score, 0), textcoords=trans,
			arrowprops={'arrowstyle': '<-', 'shrinkA': 1, 'shrinkB': 1, 'lw':1.5,
						'mutation_scale': 10., 'color': color})
	else:
		pass 
Example 39
Project: NAUM   Author: YinpeiDai   File: run_model.py    MIT License 5 votes vote down vote up
def testing(self):
        '''
        using TSNE for to visual the distribution of word vectors
        :return: picture
        '''
        with open(os.path.join(self.save_dir, self.output_filename+'.pkl'), 'rb') as f:
            vocab = pickle.load(f)

        self.reverse_dictionary = {}
        self.embeddings = np.zeros(shape=[len(vocab), self.word_emb_size], dtype=np.float32)
        count = 0
        for k, v in vocab.items():
            self.reverse_dictionary[count] = k
            for i, num in enumerate(v):
                self.embeddings[count, i] = float(num)
            count += 1
        plot_only = 500
        print('tsne is working ... ')
        tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
        low_dim_embs = tsne.fit_transform(self.embeddings[:plot_only, :])
        labels = [self.reverse_dictionary[i] for i in range(plot_only)]
        plt.figure(figsize=(18, 18))  # in inches
        for i, label in enumerate(labels):
            x, y = low_dim_embs[i, :]
            plt.scatter(x, y)
            plt.annotate(label,
                         xy=(x, y),
                         xytext=(5, 2),
                         textcoords='offset points',
                         ha='right',
                         va='bottom',
                         size=8)
        plt.show() 
Example 40
Project: voronoi-europe   Author: blumdrew   File: largecities.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_maker(vframe, geo_frame, color_map = 'tab20'):
    if geo_frame.crs['init'] != 'epsg:4326':
        geo_frame = geo_frame.to_crs(epsg = 4326)

    if vframe.crs['init'] != 'epsg:4326':
        vframe = vframe.to_crs(epsg = 4326)

    top_cities = pd.read_csv('europe_1mil.csv')
    x, y = top_cities['lng'].tolist(), top_cities['lat'].tolist()
    name = top_cities['city_ascii'].tolist()
    city_data = [(name[index], (float(x[index]), float(y[index]))) for index in range(len(name))]

    plt.figure(dpi = 1000)
    ax = plt.gca()
    ax.set_xlim(X_RANGE)
    ax.set_ylim(Y_RANGE)
    ax.set_aspect('equal')
    ax.axis('off')
    for city in city_data:
        city_name = city[0]
        #plt.annotate(city_name, city[1], fontsize = 3)
        plt.plot(city[1][0], city[1][1], 'ko', markersize = 0.5)

    geo_frame.plot(ax = ax, edgecolor = 'black', facecolor = 'None', linewidth = 0.1, zorder = 2)
    vframe.plot(ax = ax, column = 'color',cmap = color_map, zorder = 1)
    plt.savefig('onemilano.png', bbox_inches = 'tight', pad_inches = 0) 
Example 41
Project: LOFAR-LIM   Author: Bhare8972   File: find_pulses_GUI.py    MIT License 5 votes vote down vote up
def plt_sname_annotations(self):
        for height, sname in self.itter():
            plt.annotate(sname, (0.0, height), textcoords=self.transform, xycoords=self.transform) 
Example 42
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_basic_annotate():
    # Setup some data
    t = np.arange(0.0, 5.0, 0.01)
    s = np.cos(2.0*np.pi * t)

    # Offset Points

    fig = plt.figure()
    ax = fig.add_subplot(111, autoscale_on=False, xlim=(-1, 5), ylim=(-3, 5))
    line, = ax.plot(t, s, lw=3, color='purple')

    ax.annotate('local max', xy=(3, 1), xycoords='data',
                xytext=(3, 3), textcoords='offset points') 
Example 43
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_annotate_default_arrow():
    # Check that we can make an annotation arrow with only default properties.
    fig, ax = plt.subplots()
    ann = ax.annotate("foo", (0, 1), xytext=(2, 3))
    assert ann.arrow_patch is None
    ann = ax.annotate("foo", (0, 1), xytext=(2, 3), arrowprops={})
    assert ann.arrow_patch is not None 
Example 44
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_polar_annotations():
    # you can specify the xypoint and the xytext in different
    # positions and coordinate systems, and optionally turn on a
    # connecting line and mark the point with a marker.  Annotations
    # work on polar axes too.  In the example below, the xy point is
    # in native coordinates (xycoords defaults to 'data').  For a
    # polar axes, this is in (theta, radius) space.  The text in this
    # example is placed in the fractional figure coordinate system.
    # Text keyword args like horizontal and vertical alignment are
    # respected

    # Setup some data
    r = np.arange(0.0, 1.0, 0.001)
    theta = 2.0 * 2.0 * np.pi * r

    fig = plt.figure()
    ax = fig.add_subplot(111, polar=True)
    line, = ax.plot(theta, r, color='#ee8d18', lw=3)
    line, = ax.plot((0, 0), (0, 1), color="#0000ff", lw=1)

    ind = 800
    thisr, thistheta = r[ind], theta[ind]
    ax.plot([thistheta], [thisr], 'o')
    ax.annotate('a polar annotation',
                xy=(thistheta, thisr),  # theta, radius
                xytext=(0.05, 0.05),    # fraction, fraction
                textcoords='figure fraction',
                arrowprops=dict(facecolor='black', shrink=0.05),
                horizontalalignment='left',
                verticalalignment='baseline',
                )

    ax.tick_params(axis='x', tick1On=True, tick2On=True, direction='out') 
Example 45
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_polar_coord_annotations():
    # You can also use polar notation on a catesian axes.  Here the
    # native coordinate system ('data') is cartesian, so you need to
    # specify the xycoords and textcoords as 'polar' if you want to
    # use (theta, radius)
    from matplotlib.patches import Ellipse
    el = Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5)

    fig = plt.figure()
    ax = fig.add_subplot(111, aspect='equal')

    ax.add_artist(el)
    el.set_clip_box(ax.bbox)

    ax.annotate('the top',
                xy=(np.pi/2., 10.),      # theta, radius
                xytext=(np.pi/3, 20.),   # theta, radius
                xycoords='polar',
                textcoords='polar',
                arrowprops=dict(facecolor='black', shrink=0.05),
                horizontalalignment='left',
                verticalalignment='baseline',
                clip_on=True,  # clip to the axes bounding box
                )

    ax.set_xlim(-20, 20)
    ax.set_ylim(-20, 20) 
Example 46
Project: hera_mc   Author: HERA-Team   File: geo_handling.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def plot_stations(self, locations, **kwargs):  # pragma: no cover
        """
        Plot a list of stations.

        Parameters:
        ------------
        stations_to_plot_list:  list containing station_names (note:  NOT antenna_numbers)
        kwargs:  arguments for marker_color, marker_shape, marker_size, label, xgraph, ygraph
        """
        if not len(locations) or not self.graph or self.testing:
            return
        displaying_label = bool(kwargs['label'])
        if displaying_label:
            label_to_show = kwargs['label'].lower()
        fig_label = "{} vs {} Antenna Positions".format(kwargs['xgraph'], kwargs['ygraph'])
        import matplotlib.pyplot as plt
        for a in locations:
            pt = {'easting': a.easting, 'northing': a.northing, 'elevation': a.elevation}
            X = pt[self.coord[kwargs['xgraph']]]
            Y = pt[self.coord[kwargs['ygraph']]]
            plt.plot(X, Y, color=kwargs['marker_color'], label=a.station_name,
                     marker=kwargs['marker_shape'], markersize=kwargs['marker_size'])
            if displaying_label:
                labeling = self.get_antenna_label(label_to_show, a, self.query_date)
                if labeling:
                    plt.annotate(labeling, xy=(X, Y), xytext=(X + 2, Y))
        if not self.axes_set:
            self.axes_set = True
            if kwargs['xgraph'].upper() != 'Z' and kwargs['ygraph'].upper() != 'Z':
                plt.axis('equal')
            plt.xlabel(kwargs['xgraph'] + ' [m]')
            plt.ylabel(kwargs['ygraph'] + ' [m]')
            plt.title(fig_label)
        return 
Example 47
Project: numerate-language-models   Author: uclnlp   File: ploty.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_pca(W,  # (n_samples, n_features)
             vocab,
             title=None
             ):
    X_tsne = PCA(n_components=2).fit_transform(W)
    plt.scatter(X_tsne[:, 0], X_tsne[:, 1])
    for row_id, target_word in enumerate(vocab):
        x = X_tsne[row_id, 0]
        y = X_tsne[row_id, 1]
        plt.annotate(str(target_word), (x, y))
    if title:
        plt.title(title)
    plt.show() 
Example 48
Project: numerate-language-models   Author: uclnlp   File: ploty.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_tsne(W,  # (n_samples, n_features)
              vocab,
              title=None
              ):
    X_tsne = TSNE(n_components=2).fit_transform(W)
    plt.scatter(X_tsne[:, 0], X_tsne[:, 1])
    for row_id, target_word in enumerate(vocab):
        x = X_tsne[row_id, 0]
        y = X_tsne[row_id, 1]
        plt.annotate(str(target_word), (x, y))
    if title:
        plt.title(title)
    plt.show() 
Example 49
Project: HiguchiFractalDimension   Author: inuritdino   File: examples.py    MIT License 5 votes vote down vote up
def apply_hfd(x,name=None):
    print("##################")
    print("#### "+str(name))
    print("##################")
    ## HFD optimized
    print("*** HFD optimized")
    t = time.time()
    print("\tHFD=",hfd(x,opt=True))
    print("\ttiming:",time.time() - t)
    ## HFD, not optimized
    print("*** HFD non-optimized")
    t = time.time()
    print("\tHFD=",hfd(x,opt=False))
    print("\ttiming:",time.time() - t)
    ##
    print("*** step-by-step (not-optimized)")
    t = time.time()
    k, L = curve_length(x,opt=False)
    HFD = lin_fit_hfd(np.log2(k),np.log2(L),log=False)
    print("\tHFD=",HFD)
    print("\ttiming:",time.time()-t)
    plt.plot(np.log2(k),np.log2(L),'.')
    plt.annotate("HFD = "+str(HFD),(0.05,0.1),xycoords='axes fraction')
    plt.xlabel('Log interval')
    plt.ylabel('Log curve length')
    if name:
        plt.title(name)

    return HFD;

### Higuchi original data: random Gaussian increments = Brownian 
Example 50
Project: convenience_py   Author: ronrest   File: labelled_scatter.py    Apache License 2.0 5 votes vote down vote up
def labelled_scatter(points, labels, new_fig=True, color="#FF8000"):
    """
    Plots a scatterplot, with text labels right next to each of the scatter
    points labelling what that point represents.

    Is useful for things like visualising word embeddings in 2D space.

    :param points:
        An array like object, with 2 columns, the first one for x coordinate,
        and the second one for the y coordinate.
    :param labels:
        List of strings, with each element being the label for each
        corresponding row in the `points` array.
    :param new_fig: {boolean} (default = True)
        Plot as a new figure?
        If True (default) then it creates the plot in a new figure window.
        If False, then it creates the plot in the existing figure window.
    :param color: {str} (default="#FF8000")
        Color to use for the scatter points.
    """
    # ==========================================================================
    if new_fig:
        plt.figure()

    # Plot the scatter points
    plt.scatter(points[:,0], points[:,1], s=100, linewidths=0,
                c=color, alpha=0.7)

    # Attach labels to the scatter points
    for pos, label in zip(points, labels):
        plt.annotate(label, xy=(pos[0], pos[1]), xytext=(7, 0),
                     textcoords='offset points',
                     ha='left', va='center')
    plt.show()