Example #1
0
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=(12, 12))  # in inches
    texts = []
    for i, label in enumerate(labels):
        pos = nltk.pos_tag([label])
        # ignore_tags = ['DT', 'PRP', 'VB', 'RB', 'IN', 'JJ']
        # if label.lower() not in stopwords and pos[0][1] not in ignore_tags and pos[0][1] == 'NN':
        if label.lower() not in stopwords \
        and label not in punctuation \
        and label[0].isupper() \
        or label.lower() in emolex_positive or label.lower() in emolex_negative:
            x, y = low_dim_embs[i, :]
            texts.append(plt.text(x, y, label))
            plt.scatter(x, y)
    # Implements adjusted text labels from external lib. Else, activate plt.annotate() below.
    adjust_text(texts, arrowprops=dict(arrowstyle='-', color='k', lw=0.5))
    # plt.annotate(label,
    #              xy=(x, y),
    #              xytext=(5, 2),
    #              textcoords='offset points',
    #              ha='right',
    #              va='bottom')
    plt.savefig(filename, dpi=600)

    subprocess.call(["say 'program completed'"],
                    shell=True)  # notification for OS X
Example #2
0
    def draw(self, pvalue_cut=100, adjust_lim=5, show=True):
        '''
        draw volcano plot
        param pvalue_cut :-log10Pvalue for cutoff
        '''
        from adjustText import adjust_text
        plt.figure(figsize=(6, 6))

        xpos = np.array(self.fc)
        ypos = -np.log10(np.array(self.pval))
        ypos[ypos == np.inf] = np.max(ypos[ypos != np.inf])

        sig = (np.abs(xpos) > 1) & (ypos > pvalue_cut)

        plt.scatter(xpos, ypos, s=1, color='k', alpha=0.5, rasterized=True)
        plt.scatter(xpos[sig], ypos[sig], s=3, color='red', rasterized=True)

        texts = []
        for i, gene in enumerate(self.genelist[sig]):
            texts.append(plt.text(xpos[sig][i], ypos[sig][i], gene,
                                  fontsize=5))

        adjust_text(texts, only_move={'texts': 'xy'}, lim=adjust_lim)
        if show:
            plt.show()
Example #3
0
def plot_full_text(data: DataFrame, ax_in: Axes) -> list:
    """Performs standard formatted full-text plot on ax_in.

    Arguments:
        data {DataFrame} -- DataFrame with x,y coordinates, smoke,
         names, times.
        ax_in {Axes} -- Axes to receive plot.

    Returns:
        list -- Returns any extra ents generated during process.

    """

    plot_map(ax_in)
    data = label_smoke_name_time(data)

    text_style = {
        'color': 'blue',
        'va': 'bottom',
        'ha': 'left',
        'path_effects': [PathEffects.withStroke(linewidth=3, foreground="w")]
    }
    text_ents = plot_labels(data, ax_in, text_style)

    arrow_style = dict(arrowstyle='->', color='r', lw=2)
    adjust_text(text_ents, ax=ax_in, arrowprops=arrow_style)

    return text_ents
Example #4
0
def plot_num_table(data: DataFrame, ax_in: Axes) -> list:
    """Plots standard formatted plot with number labels on map and table summary.

    Arguments:
        data {DataFrame} -- Table with xCoordinate, yCoordinate, time,
         smoke and Name
        ax_in {Axes} -- Target axes for plot

    Returns:
        list -- Returns list of generated plot entities.
    """
    # Map
    plot_map(ax_in)

    # Add labels
    data['label'] = [str(x + 1) for x in range(data.shape[0])]
    text_style = {
        'color': 'blue',
        'va': 'bottom',
        'ha': 'left',
        'path_effects': [PathEffects.withStroke(linewidth=3, foreground="w")],
        'fontsize': 14
    }
    text_ents = plot_labels(data, ax_in, text_style)

    # Adjust the labels
    adjust_text(text_ents, ax=ax_in)

    # Add summary table
    table = plot_sum_table(data, ax_in)

    return text_ents.append(table)
Example #5
0
def plot_influscore(infile, outfile):
    """Plot TF influence score to expression."""

    mogrify = pd.read_table(infile, index_col="factor")
    mogrify = mogrify.dropna()
    factors = list(mogrify.sort_values("sumScaled").tail(20).index)
    # factors = list(mogrify.sort_values("sumScaled").tail(20).index)
    xcol = "factor_fc"
    plt.figure(figsize=(8, 6))
    sns.regplot(
        data=mogrify,
        x=xcol,
        y="sumScaled",
        fit_reg=False,
        scatter_kws={
            "s": mogrify["directTargets"] / 10,
            "alpha": 0.5
        },
    )
    x = mogrify.loc[factors, xcol]
    y = mogrify.loc[factors, "sumScaled"]
    texts = []
    for s, xt, yt in zip(factors, x, y):
        texts.append(plt.text(xt, yt, s))
    adjust_text(texts, arrowprops=dict(arrowstyle="-", color="black"))
    plt.xlabel("Log2 fold change of TF")
    plt.ylabel("Influence score")
    plt.savefig(outfile, dpi=300)
Example #6
0
def plot_residual_var(pysct_results, topngenes=30, label_genes=True, ax=None):
    if ax is None:
        fig, ax = plt.subplots(figsize=(8, 5))
    else:
        fig = None

    gene_attr = pysct_results["gene_attr"]
    gene_attr_sorted = gene_attr.sort_values(by=["residual_variance"],
                                             ascending=False).reset_index()
    # TODO: error check
    topn = gene_attr_sorted.iloc[:topngenes]
    gene_attr = gene_attr_sorted.iloc[topngenes:]
    ax.set_xscale("log")

    ax.scatter(gene_attr["gene_gmean"],
               gene_attr["residual_variance"],
               s=1.5,
               color="black")
    ax.scatter(topn["gene_gmean"],
               topn["residual_variance"],
               s=1.5,
               color="deeppink")
    ax.axhline(1, linestyle="dashed", color="red")
    ax.set_xlabel("Gene gmean")
    ax.set_ylabel("Residual variance")
    if label_genes:
        texts = [
            plt.text(row["gene_gmean"], row["residual_variance"], row["index"])
            for index, row in topn.iterrows()
        ]
        adjust_text(texts, arrowprops=dict(arrowstyle="-", color="k", lw=0.5))
    # fig.tight_layout()
    return fig
Example #7
0
def autolabel(rects, **kwargs):
    """
    Attach a text label above each bar in *rects*, displaying its height.

    list of kwargs:
        + bool original
        + string truncate: in the '{}' format. Can be filled in with '{:.5f}'
        + dict arrowprops:
            usage: pass in `arrowprops=dict(arrowstyle='->', color='r')`
    """
    if "original" in kwargs and kwargs["original"] == True:
        if "truncate" in kwargs:
            ori_autolabel(rects, kwargs["truncate"])
            return
        else:
            ori_autolabel(rects)
        return

    texts = []
    for rect in rects:
        height = rect.get_height()
        if "truncate" in kwargs:
            texts.append(plt.text(s=kwargs["truncate"].format(height),
                                  x=(rect.get_x() + rect.get_width() / 2),
                                  y=(height)))
        else:
            texts.append(plt.text(s='{}'.format(height),
                                  x=(rect.get_x() + rect.get_width() / 2),
                                  y=(height)))

    if "arrowprops" in kwargs:
        adjust_text(texts, arrowprops=kwargs['arrowprops'])
Example #8
0
def compare_pvr(A, store=None, **others):
    if store is None:
        assert A is not None, ("A ground-truth `A` must be passed"
                               " if no `store` is given!")
        results = test_multi(A, **others)
    else:
        results = store

    pvr = partial(pvr_plot, A)

    plt.figure(figsize=(4, 5))
    _plot_f_iso()
    sns.despine()
    # TODO make this part variadic...
    custom_cycler = (cycler(color=sns.color_palette(n_colors=len(results))) +
                     cycler(ls=['-', ':', '--', '-.']) +
                     cycler(marker=['o', 's', 'X', 'd']))
    plt.gca().set_prop_cycle(custom_cycler)
    # results = {name: pvr(B, plot_name=name)
    #            for name, B in others.items()}
    for style, (name, d) in zip(custom_cycler, results.items()):
        pvr(d['x'], store=d, plot_name=name, **style)
    plt.legend(loc='upper center',
               bbox_to_anchor=(0.5, -0.2),
               ncol=len(results) // 2)
    plt.tight_layout()

    plt.gca().set_aspect('equal')
    plt.xlim(0, 1.05)
    plt.ylim(0, 1.05)
    adjust_text([i['pyplot_text'] for i in results.values()])
Example #9
0
def allPlot(allStats):
    #print(allStats)
    plt.style.use('seaborn-darkgrid')
    plt.figure(figsize=(8, 6))
    num = 0
    texts = []

    for player in allStats:
        num += 1
        playerName = player.pop(0)
        texts.append(
            plt.text(len(player) - 1,
                     player[len(player) - 1],
                     playerName,
                     fontsize=6))
        plt.plot(player, marker='', linewidth=1, alpha=0.9, label=playerName)
    plt.title("All Playerstats")
    plt.xlabel("Games Played")
    plt.ylabel("Net Points")
    plt.axis([None, None, -10, 10])
    plt.axhline(0, color='black')
    plt.axvline(0, color='black')
    plt.yticks(np.arange(-10, 10, 2))
    adjust_text(texts,
                autoalign='',
                only_move={'text': 'y'},
                force_text=0.75,
                avoid_points=False)
    print("allPlot.png created.")
    plt.savefig('allPlot.png', dpi=300)
 def plot_tsne(self, window, vector_size):
     cprint("モデルのt-NSEによる出力を始めます。", "yellow")
     os.chdir(self.model_dir)
     model = Doc2Vec.load("model_v{}_w{}".format(vector_size, window))
     figsize(15, 15)
     plt.rcParams['font.family'] = 'IPAexGothic'
     tag_name = [i.split("_")[0] for i in os.listdir(self.train_dir)]
     train_data = [model[tag] for tag in tag_name]
     reduced_data = TSNE(n_components=2,
                         random_state=0).fit_transform(train_data)
     for i, tag in enumerate(tag_name):
         plt.scatter(reduced_data[i, 0],
                     reduced_data[i, 1],
                     color=cm.hsv(i / 160))
     texts = [
         plt.text(reduced_data[i, 0],
                  reduced_data[i, 1],
                  str(tag_name[i]),
                  ha='center',
                  va='center') for i in range(len(reduced_data))
     ]
     adjust_text(texts)
     plt.xticks(color="None")
     plt.yticks(color="None")
     os.chdir(self.image_dir)
     plt.savefig("image_tsne_w{}_v{}.png".format(window, vector_size))
Example #11
0
def drawTimes(plots, title, ylabel, xlabel, fname):
    print(fname)
    texts = []
    for plot in plots:
        path = plot[1]
        label = plot[0]
        keys = []
        values = []
        with open(path) as f:
            reader = csv.DictReader(f)
            for d in reader:
                keys.append(float(d["parameter"]))
                values.append(float(d["median"]) * 1000) # seconds -> milliseconds

        texts.append(plt.text(keys[-1], values[-1], f"{values[-1]:.0f}ms", va="center"))
        plt.plot(keys, values, "o-", label=label)

    adjust_text(texts)
    plt.gca().xaxis.set_major_formatter(FuncFormatter(lambda val, pos: f"{val:.0f}kB"))
    plt.gca().yaxis.set_major_formatter(FuncFormatter(lambda val, pos: f"{val:.0f}ms"))
    plt.xticks(keys, rotation=40)
    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.legend()
    plt.savefig(fname, bbox_inches="tight")
    plt.clf()
Example #12
0
def scatter_label(df, outf, rd):
    x = df['coarse_count_percent']
    y = df['fine_count_percent']

    labels = df['country_name']

    plt.scatter(x, y, s=2)

    texts = list()

    for label, x, y in zip(labels, x, y):
        # plt.annotate(label.decode('utf-8'), xy=(x, y))
        label = label.decode('utf-8')
        texts.append(plt.text(x, y, label))

    # force_text: r1 = 1.0; r2=1.0; r3=1.0; r4=; r5=1.6; r6=

    adjust_text(texts,
                force_text=0.8,
                autoalign='y',
                precision=1,
                arrowprops=dict(arrowstyle="-|>", color='r', alpha=0.3,
                                lw=0.5))

    plt.xlabel('Coarse location percentage')
    plt.ylabel('Fine location percentage')

    title = "Location accuracy of each country in round: " + str(rd)
    plt.title(title)
    plt.savefig(outf, dpi=900)
def prediction():
    model = word2vec.load('all.bin')
    vocabs = []
    vecs = []
    for vocab in model.vocab:
        vocabs.append(vocab)
        vecs.append(model[vocab])
    vecs = np.array(vecs)[:k]
    vocabs = vocabs[:k]

    #Dimensionality Reduction

    tsne = TSNE(n_components=2)
    reduced = tsne.fit_transform(vecs)

    # filtering
    use_tags = set(['JJ', 'NNP', 'NN', 'NNS'])
    puncts = ["'", '.', ':', ";", ',', "?", "!", u"’"]

    plt.figure()
    texts = []
    for i, label in enumerate(vocabs):
        pos = nltk.pos_tag([label])
        if (label[0].isupper() and len(label) > 1 and pos[0][1] in use_tags
                and all(c not in label for c in puncts)):
            x, y = reduced[i, :]
            texts.append(plt.text(x, y, label))
            plt.scatter(x, y)

    adjust_text(texts, arrowprops=dict(arrowstyle='-', color='k', lw=0.5))

    plt.show()
Example #14
0
def plot_one_traj(x,
                  y,
                  doNote=True,
                  sample_traj_file=None,
                  x_range=None,
                  y_range=None):
    fig, ax = plt.subplots(1, 1, figsize=(6, 5))
    ax.plot(x,
            y,
            marker='+',
            markersize=8,
            markeredgecolor='red',
            linestyle='--',
            linewidth=0.5)
    if doNote:
        texts = []
        for i in range(len(x)):
            texts.append(plt.text(
                x[i],
                y[i],
                str(i + 1),
            ))
        adjust_text(texts)
    # ax.grid()
    if x_range: ax.set_xlim(x_range)
    if y_range: ax.set_ylim(y_range)
    plt.tight_layout()
    plt.box(on=None)
    if sample_traj_file:
        plt.savefig(sample_traj_file, dpi=120)
        plt.close()
    else:
        plt.show()
Example #15
0
def graph(name, ratings, oscars):
    years = []
    rat = []
    for rating in ratings:
        rat.append(rating[0])
        years.append(int(rating[2]))
    years = list(reversed(years))
    rat = list(reversed(rat))
    corr = np.corrcoef(years, rat)[0][1]
    if corr >= 0.9:
        print(name + " become better solely due to age")
    elif corr >= 0.7:
        print(name + " got significantly better with age")
    elif corr >= 0.5:
        print(name + " seems to have improved at least in part due to age")
    elif corr >= 0.3:
        print("Age might have impacted " + name + "a little bit")
    else:
        print("Age did not affect " + name + "s work at all")
    fig, ax = plt.subplots(figsize=(12, 4))
    ax.scatter(years, rat)
    texts = []
    for rating in ratings:
        v = oscars.get(rating[1])
        if v != None:
            txt = v[1] + " , " + rating[1] + " (" + rating[2] + ")"
            texts.append(ax.text(int(rating[2]), rating[0], txt))
    adjust_text(texts)
    plt.ylabel("Rating")
    plt.xlabel("Time")
    plt.title("Scatterplot of " + name + "'s ratings")
    plt.show()
def make_plot_color_map(x, y, map2ix):

    # divide maps to their own categories
    attacks, defenses, controls = [], [], []
    for name, idx in map2ix.items():
        name = name.split('_')
        if name[1] == 'Attack':
            attacks.append(idx)
        elif name[1] == 'Defense':
            defenses.append(idx)
        else:
            controls.append(idx)

    # plot attack, defense, controls map respectively
    att_x, att_y = x[attacks], y[attacks]
    den_x, den_y = x[defenses], y[defenses]
    con_x, con_y = x[controls], y[controls]

    fig = plt.figure(figsize=(16, 12), dpi = 100)
    ax = plt.subplot(111)
    marker_size = 200
    ax.scatter(att_x, att_y, c= 'tomato', s=marker_size)
    ax.scatter(den_x, den_y, c = 'darkcyan', s=marker_size)
    ax.scatter(con_x, con_y, c = 'royalblue', s=marker_size)

    texts = []
    # annotate each map's name
    for name, i in map2ix.items():
        # ax.annotate(name, (x[i], y[i]))
        texts.append(ax.text(x[i], y[i], name))
    adjust_text(texts)
    plt.show()
    fig.savefig('./output/map/map_embddings_2d_adjusted.png')
Example #17
0
def distance_scatter(d, topk=10, show=True, save_path=None):
    """ Distance vs adaptation scatter plots as used in the OTDD paper. 
    Args:
        d (dict): dictionary of task pair (string), distance (float)
        topk (int): number k of top/bottom distances that will be annotated
    """
    sorted_d = sorted(d.items(), key=lambda kv: kv[1])
    keys, dists = zip(*sorted_d)
    if type(keys[0]) is tuple and len(keys[0]) == 2:
        labels = ['{}<->{}'.format(p, q) for (p, q) in keys]
    else:
        labels = ['{}'.format(p) for p in keys]
    x_coord = np.linspace(0, 1, len(keys))

    fig, ax = plt.subplots(figsize=(10, 10))
    ax.scatter(x_coord, dists, s=min(100 / len(keys), 1))
    texts = []
    for i, (x, y, name) in enumerate(zip(x_coord, dists, keys)):
        if i < topk or i >= len(keys) - topk:
            label = '{}<->{}'.format(
                *name) if type(name) is tuple else str(name)
            texts.append(ax.text(x, y, label))
    adjust_text(texts,
                force_text=0.05,
                arrowprops=dict(arrowstyle="-|>", color='r', alpha=0.5))

    ax.set_title('Pairwise Distance Between MNIST Binary Classification Tasks')
    ax.set_ylabel('Dataset Distance')
    if save_path:
        plt.savefig(save_path, format='pdf', dpi=300)  #bbox_inches='tight',
    if show: plt.show()
Example #18
0
def plot_embedding_dimension(emb, dim, charpoints):
  plt.figure(figsize=(20,4))
  plt.axis([
    np.min(emb[charpoints][:,dim]),
    np.max(emb[charpoints][:,dim]),
    .3, .7
  ])
  plt.yticks([])
  plt.ylabel('')
  plt.title('Dimension {}'.format(dim+1))
  texts = []
  for cp in charpoints:
    #y = random.random()
    y = .4 + random.random() * .2
    t = plt.text(emb[cp][dim], y, charify(cp)
    )
    color = char_color(chr(cp))
    t.set_bbox(dict(color=color, alpha=.5, boxstyle='round'))
    texts.append(t)

  adjust_text(texts,
    only_move={'text': 'y'},
    force_text=14.5,
    expand_points=(1.2, 1.2),
    lim=5000,
  )

  fname = 'vis/d{}{}.png'.format(
    ALLOWED_TYPES[0] if len(ALLOWED_TYPES) == 1 else '',
  dim)
  plt.savefig(fname, bbox_inches='tight')
  plt.clf()
def pca_parties_scatter(df):
    """
    A function that performs PCA on the 10 largest parties in the election.
    :param df: The election data.
    :return: None.
    """
    df = df[df.columns[10:]]
    df_par_freq = df.div(df.sum(axis=1), axis=0)
    df_par_freq_nona = df_par_freq.fillna(0).transpose()
    pca = PCA(n_components=2)
    mapped_df = pd.DataFrame(pca.fit_transform(df_par_freq_nona),
                             index=df.keys())
    fig, ax = plt.subplots()
    ax.scatter(mapped_df[0][size_order],
               mapped_df[1][size_order],
               label='Large Parties',
               c='b')
    ax.scatter(mapped_df[0][list(set(df.keys()) - set(size_order))],
               mapped_df[1][list(set(df.keys()) - set(size_order))],
               label='Small Parties',
               c='r')
    adjust_text([
        plt.text(mapped_df[0][i],
                 mapped_df[1][i],
                 party_code_dict[i][::-1],
                 fontsize=9) for i in size_order
    ])
    plt.xlabel("PCA 2 weight per ballot")
    plt.ylabel("PCA 1 weight per ballot")
    plt.title("PCA of parties")
    plt.legend()
    plt.show()
Example #20
0
def plot_gradients(coeff, corr, ax=plt.gca()):
    import matplotlib
    matplotlib.use('Agg')
    # V=coeff.values
    # ax=plt.gca()
    origin = [0, 0]  # origin point
    # origin = [0], [0] # origin point
    # q=ax.quiver(*origin, V[:,0], V[:,1])
    from adjustText import adjust_text
    texts = []
    for i in range(len(corr)):
        # if (corr.loc[coeff.index[i]].round(2).iloc[0])>0.5:
        grad = coeff[coeff.index == corr.index[i]].values[0]
        x = [origin[0], grad[0]]
        y = [origin[1], grad[1]]
        ax.plot(x, y, lw=2)
        # ax.legend()
        # ax.annotate(coeff.index[i], xy=(grad[0], grad[1]), xycoords='data')
        feat_name = corr.index[i].replace('_sma3', ' ').replace(
            'nz',
            '').replace('_',
                        '').replace('amean',
                                    'mean').replace('semitoneFrom27.5Hz', '')
        texts.append(
            ax.text(grad[0],
                    grad[1],
                    feat_name + ' ' + str(corr.iloc[i].iloc[0].round(2)),
                    fontsize=9))
    adjust_text(texts,
                force_text=0.05,
                autoalign='xy',
                arrowprops=dict(arrowstyle="->", color='b', lw=1))
    plt.show()
Example #21
0
def plot_volcano(grouped_loci, fc_cutoff=4, p_val_cutoff=.05, labels=False, title='Volcano Plot'):
    import seaborn as sns
    sns.set_style('whitegrid')    


    df = build_loci.get_sig_df(grouped_loci, fc_cutoff=fc_cutoff, p_val_cutoff=p_val_cutoff)
    df['gene_name'] = df['name'].apply(build_loci.get_gene_name)
    
    X = df['logfc'].values
    Y = df['-logp'].values
    
    # Plot the points
    fig = plt.figure(figsize=(15, 9))
    fig.set_tight_layout(False)
    plt.scatter(X, Y, c = df['passes'], s=50, cmap='Paired')
    
    if labels:
        texts = []
        for name, x, y in zip(df['gene_name'],X, Y):
            if abs(x) > np.log2(fc_cutoff) and y > -1*np.log10(p_val_cutoff) and name != '' and name != 'Amy2':
                texts.append(plt.text(x, y, name, size = 12, weight='extra bold'))
                

    
    # Plot asjustments
    plt.title(title, size=24)
    plt.xlabel('log2 Fold Change', size=18)
    plt.ylabel('-log10 p-value', size=18)
    plt.xticks(size=12)
    plt.yticks(size=12)
    plt.ylim(bottom=-0.2);
    if labels:
        adjust_text(texts, arrowprops=dict(arrowstyle="-", color='k', lw=0.5))
Example #22
0
def main():
    words, pos_tags = load_data('all.txt')
    word2vec.word2phrase('all.txt', 'word2phrase.txt', verbose=False)
    word2vec.word2vec('word2phrase.txt',
                      'word2vec.bin',
                      alpha=0.087,
                      hs=1,
                      size=100,
                      verbose=False)
    model = word2vec.load('word2vec.bin')
    words_table, words_vec = get_most_frequent_words(500, model, pos_tags)
    tsne = TSNE(n_components=2, random_state=87)
    words_t_vec = tsne.fit_transform(words_vec)
    # show
    figure = pyplot.figure(figsize=(12, 6), dpi=150)
    pyplot.scatter(words_t_vec[:, 0],
                   words_t_vec[:, 1],
                   c='b',
                   alpha=0.2,
                   s=15)
    texts = []
    for vec, text in zip(words_t_vec, words_table):
        texts.append(pyplot.text(vec[0], vec[1], text, size=5))
    adjust_text(texts, arrowprops=dict(arrowstyle='-', color='k', lw=0.5))
    pyplot.show()
    figure.savefig('figure.png')
Example #23
0
def drawMem(plots, title, ylabel, xlabel, fname):
    print(fname)
    texts = []
    rssrx = re.compile(r".* (.*?)maxresident.*")
    sizerx = re.compile(r".*-(.*?)k\.txt")
    for plot in plots:
        pathglob = plot[1]
        label = plot[0]
        keys = []
        values = []
        for path in glob.iglob(pathglob):
            with open(path) as f:
                kb = rssrx.match(f.readline()).group(1)
                size = sizerx.match(path).group(1)
                keys.append(float(size))
                values.append(float(kb) / 1024)

        keys, values = zip(*sorted(zip(keys, values), key=lambda kv: kv[0]))
        texts.append(plt.text(keys[-1], values[-1], f"{values[-1]:.0f}MB", va="center"))
        plt.plot(keys, values, "o-", label=label)

    adjust_text(texts)
    plt.gca().xaxis.set_major_formatter(FuncFormatter(lambda val, pos: f"{val:.0f}kB"))
    plt.gca().yaxis.set_major_formatter(FuncFormatter(lambda val, pos: f"{val:.0f}MB"))
    plt.xticks(keys, rotation=40)
    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.legend()
    plt.savefig(fname, bbox_inches="tight")
    plt.clf()
Example #24
0
def plot_corr(data, xcol, ycol, ax, labellist, offset):
    """plot correlation between xcol and ycol, label their pcc value
    """
    ax = sns.regplot(x=xcol,
                     y=ycol,
                     data=data,
                     ax=ax,
                     scatter=False,
                     line_kws={"linewidth": 0.8},
                     truncate=False)
    adjusttext = []
    for x, y, code, color in zip(data[xcol], data[ycol], data.Code,
                                 data.NodeColor):
        ax.scatter(x, y, s=9, c=color)
        if code in labellist and not np.isnan(x) and not np.isnan(y):
            adjusttext.append(ax.text(x, y, code))
            #ax.text(x+offset,y,code, horizontalalignment='right',verticalalignment='top')
    adjust_text(adjusttext,
                force_text=0.02,
                arrowprops=dict(arrowstyle="-", color='dimgray', lw=0.5),
                fontsize="small")
    xvalue = data[xcol].values
    yvalue = data[ycol].values
    nas = np.logical_or(np.isnan(xvalue), np.isnan(yvalue))
    pcc = np.around(np.corrcoef(xvalue[~nas], yvalue[~nas])[0, 1], decimals=2)
    #pcc_filter = np.around(np.corrcoef(data_filter[xcol], data_filter[ycol])[0,1],decimals=2)
    #pcc_all = '{}({})'.format(pcc,pcc_filter)
    text = '{}={}'.format("PCC", pcc)
    plt.text(0.05, 0.9, text, transform=ax.transAxes, fontsize=17)
    ax.tick_params(labelsize=16)
    return ax
Example #25
0
def Plot(datas, title):
    fig, axes = plt.subplots(ncols=len(datas))
    for n, data in enumerate(datas):
        box_dict = axes[n].boxplot(data['dist'])
        flier = box_dict['fliers']
        position = [(flier[i].get_xdata(), flier[i].get_ydata())
                    for i in range(len(flier))]
        post = [(position[0][0][i], position[0][1][i])
                for i in range(len(position[0][0]))]
        pep_name = [
            data[data['dist'] == y]['pep_only'].values[0] for x, y in post
        ]
        [
            axes[n].text(x + 0.02,
                         y + 0.02,
                         s=data[data['dist'] == y]['pep_only'].values[0],
                         color='r') for x, y in post
        ]
        axes[n].set_xticks([], [])
        axes[n].set_title(title[n], color='b')
        axes[n].set_ylabel('Khoảng cách trung bình (Angstrom)')
        texts = [
            axes[n].annotate(data.iloc[i]['pep_only'],
                             color='r',
                             xy=(1, data.iloc[i]['dist']),
                             xytext=(1.12, data.iloc[i]['dist'] + 0.05),
                             arrowprops=dict(
                                 arrowstyle="fancy",
                                 color='r',
                                 connectionstyle="angle3,angleA=0,angleB=-90"))
            for i in range(4) if all(~data.iloc[i].isin(pep_name))
        ]
        adjust_text(texts)
Example #26
0
    def __init__(self,x,y,amps, x0s, sigmas, c,title):
        #figWH = (8,5) # in
        self.fig = plt.figure()#figsize=figWH)
        self.ax = self.fig.add_subplot(111)
        self.ax.set_title(title)

        for j in range(len(amps)):
            self.ax.plot(x, lorentz(x, amps[j], x0s[j], sigmas[j]))# + c)

        self.ax.plot(x, y, linestyle='', marker='.')
        y_fit = lorentzSum(x, *popt)
        self.ax.plot(x, y_fit, color='black')

        indices = np.zeros(len(amps), dtype=np.int)
        for j in range(len(x0s)):
            indices[j] = (np.abs(x - x0s[j])).argmin()
        print(indices)

        texts = []
        for j in range(len(indices)):
            texts.append(self.ax.text(x[indices[j]], y_fit[indices[j]], str(int(round(x0s[j])))))

        adjust_text(texts, x, y, only_move={'points': 'y', 'text': 'y'},
                    arrowprops=dict(arrowstyle="->", color='k', lw=1),
                    expand_points=(1.7, 1.7),
                    )  # force_points=0.1)

        self.good = False

        self.connect = self.ax.figure.canvas.mpl_connect
        self.disconnect = self.ax.figure.canvas.mpl_disconnect

        self.clickCid = self.connect("button_press_event",self.onClick)
Example #27
0
    def visualize_embeddings(self,
                             embeddings=[],
                             labels={},
                             fromlabel="Source",
                             tolabel="target",
                             adjust=True):
        if labels == {}:
            labels = self.index2alfa_from

        if embeddings == []:
            embeddings = self.embeddings

        mds = MDS(n_components=2)
        mds_result = mds.fit_transform(embeddings)
        maxwidth = max(mds_result[:, 0]) - min(mds_result[:, 0])
        maxheight = max(mds_result[:, 1]) - min(mds_result[:, 1])

        plt.scatter(mds_result[:, 0],
                    mds_result[:, 1],
                    s=100,
                    c=range(len(embeddings)))
        if adjust:
            texts = [
                plt.text(mds_result[i, 0], mds_result[i, 1], labels[i])
                for i in range(len(embeddings))
            ]
            adjust_text(texts)
        else:
            for i in range(len(embeddings)):
                plt.annotate(labels[i], (mds_result[i, 0] + 0.01 * maxwidth,
                                         mds_result[i, 1] + 0.02 * maxheight))

        plt.title(fromlabel + " to " + tolabel + " embeddings")
Example #28
0
def plot_segments(Data, Settings, segments):
    """Plots bandstructure overlaid with the DFT-calculated points for each Segment
    instance. Each Segment is labelled with it's direction in reciprocal space
    and index number from the segments argument.

    Args:
        Data (Data): instance of the :class:`Data` class.
        Settings (Settings): instance of the :class:`Settings` class.
        segments (list(Segment)): A list of instances of the :class:`Segment` class.

    Returns:
        Figure, Axes: tuple containing instance of the `matplotlib.pyplot.figure <https://matplotlib.org/api/figure_api.html>`_ class and `matplotlib.pyplot.axes <https://matplotlib.org/api/axes_api.html>`_ class.

    Notes:
        The x-axis of the plot is not to scale.
    """
   
    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(111)

    [ax.plot(range(len(Data.energies[i])), Data.energies[i] - Data.VBM) for i in range(len(Data.energies))]
    points = [ax.scatter(segments[i].kpoint_indices, segments[i].energies - Data.VBM) for i in range(len(segments))]
    texts = [ax.text(segments[i].kpoint_indices[-1], segments[i].energies[-1] - Data.VBM, str(i)+", "+str(np.round(segments[i].direction,3))) for i in range(len(segments))]    
    adjust_text(texts, arrowprops=dict(arrowstyle='->', color='red'), autoalign='x', force_text=(0.01,0.025))

    ax.set_ylim([
        -(Settings.extrema_search_depth + Settings.energy_range + 1),
        (Data.CBM - Data.VBM) +
        (Settings.extrema_search_depth + Settings.energy_range + 1)
    ])

    return fig, ax
Example #29
0
def draw_scatter_speices_ct_v2(ct,
                               fc,
                               version,
                               fig_folder,
                               percentile_thres=99.5,
                               adjust_lim=3,
                               fontsize=5):
    v3 = fc[ct]['h_m']
    v4 = fc[ct]['mks']

    xpos = np.array(v3.fc)
    ypos = np.array(v4.fc)

    ymax = np.percentile(ypos, percentile_thres)
    xmax = np.percentile(np.abs(xpos), percentile_thres)

    sig1 = (((ypos) > ymax) & (-np.log10(v4.pval) > 5))
    sig2 = ((np.abs(xpos) > xmax) & (-np.log10(v3.pval) > 5))

    sig = sig1

    plt.scatter(xpos, ypos, s=1, color='k', alpha=0.5, rasterized=True)
    plt.title(ct)
    texts = []
    for i, gene in enumerate(v3.genelist[sig]):
        texts.append(
            plt.text(xpos[sig][i], ypos[sig][i], gene, fontsize=fontsize))
    if adjust_lim:
        adjust_text(texts, only_move={'texts': 'xy'}, lim=adjust_lim)
    plt.grid(False)
    jp_save_fig(version, 'FigS1_species_v2_%s' % ct, fig_folder=fig_folder)
Example #30
0
def ew_v_w(df):
    agg = df.rename(columns = {"Win":"Wins", "Exp Win": "Exp Wins"})\
            .sort_values(by="Exp Wins")

    print("get plot")
    ax = agg.plot(kind="scatter",
                  x="Exp Wins",
                  y="Wins",
                  title="Exp Wins vs. Wins")

    ann = []
    for x, y, val in zip(agg['Exp Wins'], agg['Wins'], agg.index.to_series()):
        ann.append(ax.text(x, y, val))

    #identiy line:
    maxW = agg['Wins'].max()
    ident = range(maxW + 1)
    maxWs = [maxW for i in ident]

    #ax.plot(ident, ident, color='black)
    ax.fill_between(ident, ident, color='red', alpha=0.3)
    ax.fill_between(ident, ident, maxWs, color='blue', alpha=0.3)

    ax.set_xlim(0, maxW)
    ax.set_ylim(-.25, maxW + .25)
    ax.text(.125, maxW - .25, "Lucky", color='blue')
    ax.text(maxW - .5, .25, "Unlucky", color='red')

    adjust_text(ann, agg['Exp Wins'], agg['Wins'])

    plt.show()
def plot_motif_logo(motif_ls, site_num_ls, pvalue_ls, tomtom_file, rbp_name):
    dd = pd.DataFrame({'site_num': site_num_ls, 'pvalue': pvalue_ls})
    dd['-log10(pvalue)'] = -np.log10(dd['pvalue'])
    dd['log2(site_num)'] = np.log2(dd['site_num'])
    dd['motif'] = motif_ls
    print dd

    sns.set_style('ticks')
    fig, ax = plt.subplots(figsize=(25, 20))
    dd.plot(kind='scatter', x='log2(site_num)', y='-log10(pvalue)', ax=ax)
    ax.set_xlim(0, )

    tomtom = read_tomtom(tomtom_file, rbp_name)

    texts = []
    for x, y, t in zip(dd['log2(site_num)'], dd['-log10(pvalue)'],
                       dd['motif']):
        if tomtom.has_key(t):
            RBP = t + '\n' + '\n'.join(tomtom[t])
        else:
            RBP = t
        if t in ['TDTWV', 'TDWDT', 'AMACAMAC', 'TAANC', 'ACAYT']:
            texts.append(plt.text(x, y, RBP, fontsize=12))
    adjust_text(texts, only_move={'text': 'xy'})

    plt.title(tomtom_file.split('/')[-2])

    plt.tight_layout()
    savefn = '/Share2/home/zhangqf7/gongjing/zebrafish/script/zebrafish_structure/results/FS3.motif_scatter_dreme_tomtom.egg_1cell.pdf'
    plt.savefig(savefn)
def plot(name, qualities_mes, costs_mes, qualities_th, costs_th):
    fig, axes = plt.subplots(2,1)

    ax1= axes[0]

    texts_mes= []
    for (i, (quality, cost)) in enumerate(zip(qualities_mes, costs_mes)):
        texts_mes.append(ax1.text(quality, cost, str(i), ha='center', va='center'))

    #print("Measured: ", q, c_cycle)

    color='tab:red'

    ax1.set_ylabel("cost per cycle (µs)")
    ax1.set_xlabel("quality")
    ax1.scatter(qualities_mes, costs_mes,  label="Measured", color=color)
    ax1.tick_params(axis='y', labelcolor=color)
    ax1.grid(True)

    ax2 = axes[1]

    texts_th = []
    for (i, (quality, cost)) in enumerate(zip(qualities_th, costs_th)):
        texts_th.append(ax2.text(quality, cost, str(i), ha='center', va='center'))

    color = 'tab:blue'
    ax2.set_ylabel("cost")
    ax2.set_xlabel("quality")

    ax2.scatter(qualities_th, costs_th,  label="Model", color=color)
    ax2.tick_params(axis='y', labelcolor=color)
    ax2.grid(True)


    adjust_text(texts_mes, ax=ax1)
    adjust_text(texts_th, ax=ax2)

    kendalltau = GraphResults("Kendall's tau")
    kendalltau.costs = stats.kendalltau(costs_mes, costs_th, nan_policy='raise')
    kendalltau.quality = stats.kendalltau(qualities_mes, qualities_th, nan_policy='raise')

    spearmanr = GraphResults("Spearman's R")
    spearmanr.costs = stats.spearmanr(costs_mes, costs_th, nan_policy='raise')
    spearmanr.quality = stats.spearmanr(qualities_mes, qualities_th, nan_policy='raise')

    print(kendalltau.name, " Kendal's tau: cost=", kendalltau.costs, " and quality=", kendalltau.quality)
    print(spearmanr.name, " Spearman's r: cost=", spearmanr.costs, " and quality=", spearmanr.quality)


    fig.tight_layout()
    fig.legend()
    if args.tikz:
        tikz_save(name+".tex")
    plt.show()
Example #33
0
    def plot_graph_labels(self, labels, ulabels=None, start=0, ax=None, cmap='magma',
                          cmap_index=None, box=True, text_kwargs=None, estimate_direction=False,
                          adjust=True, adjust_kwargs=dict(arrowprops=dict(arrowstyle="fancy",
                                                                          fc=".6", ec="none"),
                                                          force_text=.5, precision=.5),
                          ):
        #Tango = GPy.plotting.Tango
        #Tango.reset()

        if ulabels is None:
            ulabels = []
            for l in labels:
                if l not in ulabels:
                    ulabels.append(l)
            ulabels = np.asarray(ulabels)

        if ax is None:
            fig, ax = plt.subplots()

        X = self.Xgplvm[:, self.gplvm.get_most_significant_input_dimensions()[:2]]
        pt = self.get_pseudo_time(start, estimate_direction)

        label_pos, col, mi, ma = _get_label_pos(X, pt, labels, ulabels)
        colors = _get_colors(cmap, col, mi, ma, cmap_index)
        texts = []
        for l in ulabels:
            #c = Tango.nextMedium()
            c, r = colors[l]
            p = label_pos[l]
            rgbc = c#[_c/255. for _c in Tango.hex2rgb(c)]
            if box:
                if r <.5:
                    ec = 'w'
                else:
                    ec = 'k'
                fc = list(rgbc)
                #fc[-1] = .7
                props = dict(boxstyle='round', facecolor=fc, alpha=0.6, edgecolor=ec, pad=0.2)
            else:
                props = dict()
                ec='k'
            texts.append(ax.text(p[0], p[1], l, alpha=.9, ha='center', va='center',
                                 color=ec, bbox=props, **text_kwargs or {}))
        if adjust:
            try:
                from adjustText import adjust_text
                xlim, ylim = ax.get_xlim(), ax.get_ylim()
                x1, y1 = np.mgrid[xlim[0]:xlim[1]:100j,ylim[0]:ylim[1]:2j]
                x2, y2 = np.mgrid[xlim[0]:xlim[1]:2j,ylim[0]:ylim[1]:100j]
                x, y = np.r_[x1[:,0], x2[1], x1[::-1,1], x2[0]], np.r_[y1[:,0], y2[1], y1[:,1], y2[0,::-1]]
                adjust_text(texts, x, y, ax=ax, **adjust_kwargs)
            except ImportError:
                print("Could not find adjustText package, resuming without adjusting")
        return ax
Example #34
0
plt.plot(C2H4Eads110, C2H4vib110,'g^')
plt.plot(C2H4Eads100, C2H4vib100,'bo')
plt.xlabel('${\Delta}$E$_{ads,C_{2}H_{4}}$ [eV]',size=32)
plt.ylabel(r'$\mathbf{\nu}_{\perp,C_{2}H_{4}} [cm^{-1}]$',size=32)
plt.legend(['111','110','100']
,loc=1,prop={'size':24},frameon=False)
plt.xticks(size=28)
plt.yticks(size=28)
plt.xlim([-1.9,-0.2])
plt.ylim([45,460])
plt.gcf().subplots_adjust(bottom=0.15)
plt.gcf().subplots_adjust(left=0.15)
texts = []
for x, y, s in zip(C2H4Eads, C2H4vib, C2H4Metal):
    texts.append(plt.text(x, y, s, bbox={'pad':0, 'alpha':0}, size=32, fontweight='bold',style='normal',name ='Calibri'))
adjustText.adjust_text(texts,autoalign=True,only_move={'points':'y','text':'y'}, arrowprops=dict(arrowstyle="-", color='k', lw=2))
plt.show()

#plt.figure(2)
#plt.figure(figsize=(12,10))
mat.rcParams['lines.markersize'] = 10
G = gridspec.GridSpec(2, 2)
#plt.figure(figsize=(15,10.5))
plt.figure(figsize=(18,15))
ax1 = plt.subplot(G[0,1])
pNH = np.polyfit(N**2, NH**2, 1)
Narray = np.linspace(np.min(N),np.max(N),50,endpoint=True)
NHfit = (pNH[0]*Narray**2+pNH[1])**0.5
pNH2 = np.polyfit(N**2, NH2**2, 1)
NH2fit = (pNH2[0]*Narray**2+pNH2[1])**0.5
plt.plot(N, NH,'g^')
Example #35
0
def plot_labels_other(X, pt, labels, ulabels=None, ax=None, cmap='magma',
                      box=True,
                      adjust=True,
                      expand_points=(.3, .3),
                      adjust_kwargs=dict(arrowprops=dict(arrowstyle="fancy",
                                            fc=".6", ec="none",
                                            ),
                                        ha='center', va='center',
                                        force_text=.2,
                                        force_points=2.,
                                        precision=.1),

                      **text_kwargs):
    """
    Plot the labels ontop of the figure.

    :param array_like X: two dimensional array for cell positions in landscape.
    :param array_like pt: one dimensional array for pseudotime assignments.
    :param array_like labels: the labels for the cells.
    :param array_like ulabels: the unique labels, for ordering of labels.
    :param axis ax: the matplotlib axis to plot on.
    :param str cmap: the colormap to use for the cells.
    :param bool box: whether to plot a box around the label.
    :param bool adjust: whether to move labels around to not overlap.
    :param dict adjust_kwargs: the keyword arguments to pass to adjust_text
    :param dict text_kwargs: keyword arguments to pass on to ax.text
    """
    if ulabels is None:
        ulabels = []
        for l in labels:
            if l not in ulabels: ulabels.append(l)
        ulabels = np.asarray(ulabels)
    if ax is None:
        _, ax = plt.subplots()
    label_pos, col, mi, ma = _get_label_pos(X, pt, labels, ulabels)
    colors = _get_colors(cmap, col, mi, ma, None)
    texts = []
    for l in ulabels:
        #c = Tango.nextMedium()
        c, r = colors[l]
        p = label_pos[l]
        rgbc = c#[_c/255. for _c in Tango.hex2rgb(c)]
        if r <.5:
            ec = 'w'
        else:
            ec = 'k'
        if box:
            fc = list(rgbc)
            #fc[-1] = .7
            props = dict(boxstyle='round', facecolor=fc, alpha=0.6, edgecolor=ec, pad=0.2)
        else:
            props = dict()
        texts.append(ax.text(p[0], p[1], l, alpha=.9, ha='center', va='center', color=ec, bbox=props, **text_kwargs or {}))
    if adjust:
        try:
            from adjustText import adjust_text
            #xlim, ylim = ax.get_xlim(), ax.get_ylim()
            #x1, y1 = np.mgrid[xlim[0]:xlim[1]:100j,ylim[0]:ylim[1]:2j]
            #x2, y2 = np.mgrid[xlim[0]:xlim[1]:2j,ylim[0]:ylim[1]:100j]
            #x, y = np.r_[x1[:,0], x2[1], x1[::-1,1], x2[0]], np.r_[y1[:,0], y2[1], y1[:,1], y2[0,::-1]]
            #ax.scatter(x,y,c='r')
            if not 'only_move' in adjust_kwargs:
                adjust_text(texts, ax=ax, **adjust_kwargs)
            else:
                adjust_text(texts, ax=ax, **adjust_kwargs)
        except ImportError:
            print("Could not find adjustText package, resuming without adjusting")
    ax.autoscale()
    return ax
Example #36
0
def main(argv):
    parser = argparse.ArgumentParser(description='Create an Identity/Divergence plot.')
    parser.add_argument('repertoire', help='file containing repertoire sequence identities (CSV)')
    parser.add_argument('-a', '--adjust', help='Adjust labels to prevent overlap (requires package adjustText)', action='store_true')
    parser.add_argument('-b', '--bar', help='Plot a colour bar', action='store_true')
    parser.add_argument('-c', '--colourmap', help='colourmap')
    parser.add_argument('-g', '--background', help='Set the contour colourwhere the density is zero')
    parser.add_argument('-mx', '--maxx', help='max divergence value to show')
    parser.add_argument('-my', '--miny', help='min identity value to show')
    parser.add_argument('-p', '--points', help='comma-seperated list of identity files and formats')
    parser.add_argument('-s', '--save', help='Save output to file (as opposed to interactive display)')
    args = parser.parse_args()

    if args.adjust:
        from adjustText import adjust_text
        
    colourmap = args.colourmap if args.colourmap else 'hot_r'

    plist = args.points.split(',')
    points = []
    
    repertoire = read_file(args.repertoire)
    
    def pairwise(iterable):
        a = iter(iterable)
        return izip(a, a)
    
    if len(plist) > 0:
        try:
            for file, format in pairwise(plist):
                points.append((read_file(file), format))
        except IOError:
            print 'file "%s" cannot be opened.' % file  
        except:
            print '"points" must consist of pairs of files and formats.'
            quit()

    max_divergence = int(args.maxx) if args.maxx else None
    min_identity = int(args.miny) if args.miny else None
    savefile = args.save if args.save else None

    if not max_divergence:
        max_divergence = max(repertoire['GermlineDist'])
        for point in points:
            max_divergence = max(max_divergence, max(point[0]['GermlineDist']))
        max_divergence = int(max_divergence) + 1
        
    if not min_identity:
        min_identity = min(repertoire['TargetDist'])
        for point in points:
            min_identity = min(min_identity, min(point[0]['TargetDist']))
        min_identity = int(min_identity)

    H, yedges, xedges = np.histogram2d(repertoire['TargetDist'], repertoire['GermlineDist'], bins=[101-min_identity, max_divergence+1], range=[[min_identity, 101], [-1, max_divergence]], normed=False)

    # For alternative interpolations and plots, see http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram2d.html
    # For colour maps, see http://matplotlib.org/examples/color/colormaps_reference.html

    fig = plt.figure()
    
    cm = plt.cm.get_cmap(colourmap)
    
    if args.background:
        cm.set_under(color=args.background)

    ax = fig.add_subplot(1,1,1)
    im = plt.imshow(H, interpolation='bilinear', origin='low', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], vmin=0.0000001, cmap=cm)
    ax.set_xlim(xedges[0], xedges[-1])
    ax.set_ylim(yedges[0], yedges[-1])
    
    if args.bar:
        cb = plt.colorbar(im, shrink=0.8, extend='neither')
        cb.ax.set_ylabel('sequences', rotation=90)

    texts = []
    
    for point in points:
        df, format = point
        markersize = 5
        label = False
        labelcolour = 'black'
        fmt = format.split('/')
        format = fmt[0]
        for f in fmt[1:]:
            if f[0] == 'm':
                markersize = int(f[1:])
            elif f[0] == 'l':
                label = True
                if len(f) > 1:
                    labelcolour = f[1:]
            else:
                print 'Unrecognised format string: %s' % format
        for index, row in df.iterrows():
            if label:
                if args.adjust:
                    texts.append(plt.text(row['GermlineDist'], row['TargetDist'], row['SequenceId'], bbox={'pad':0, 'alpha':0}, fontdict={ 'color': labelcolour}))
                else:
                    texts.append(plt.text(row['GermlineDist'] + 0.2, row['TargetDist'] - 0.2, row['SequenceId'], bbox={'pad':0, 'alpha':0}, fontdict={ 'color': labelcolour}))
            ax.plot(row['GermlineDist'], row['TargetDist'], format, markersize=markersize)

    if args.adjust:
        adjust_text(texts)

    plt.xlabel('Germline Divergence (%)')
    plt.ylabel('Target Ab Identity (%)')
    
    if savefile:
        plt.savefig(savefile)
    else:
        plt.show()
Example #37
0
    Marker.append(Metal_Info[i,0])
for i in range(0,len(vMN)):
    Marker.append(Metal_Info[i,0])
for i in range(0,len(vMH)):
    Marker.append(Metal_Info[i,0])
mat.rc('text', usetex = False)
texts = []
vM = np.concatenate((vMO,vMN,vMH))
Gibbsvib = np.concatenate((GibbsvibO,GibbsvibN,GibbsvibH))
idx = np.isfinite(vM) & np.isfinite(Gibbsvib)
vM = vM[idx]
Gibbsvib = Gibbsvib[idx]
Marker = np.array(Marker)[idx]
for x, y, s in zip(vM, Gibbsvib, Marker):
    texts.append(plt.text(x, y, s, bbox={'pad':0, 'alpha':0}, size=16, fontweight='bold',style='normal',name ='Calibri'))
adjustText.adjust_text(texts,autoalign=True,arrowprops=dict(arrowstyle="-", color='k', lw=2))
plt.show()
"""Plotting vibrational multiplier to Keq"""

plt.figure(2)
#plt.figure(figsize=(18,10),dpi=500)
plt.figure(figsize=(16,8))
Keq = np.exp(-GibbsvibO*JeV/(kB*T))
Keqfit = np.exp(-GibbsvibOfit*JeV/(kB*T))
fGO = interp1d(vMOx,Keqfit)
R2O = 1 - sum((fGO(vMO[idxO])-Keq[idxO])**2)/sum((fGO(vMO[idxO])-np.mean(Keq[idxO]))**2)
MAEO = np.mean(abs(fGO(vMO[idxO])-Keq[idxO]))
plt.plot(vMO,Keq,'ob')
plt.plot(vMOx,Keqfit,'-b')

#plt.title('The Scaling of M-O Entropy',size=12, fontweight='bold')
Example #38
0
EO2 = -(Data.O2-5.1158)/2
p = np.polyfit(EH2,EO2, 1) 
m1 = p[0]
b1=p[1]
R2 = 1 - sum(((m1*EH2+b1)-EO2)**2)/sum((EO2-np.mean(EO2))**2) 
plt.figure(1)
plt.figure(figsize=(14,10))
plt.plot(np.array([np.min(EH2),np.max(EH2)]), m1*np.array([np.min(EH2),np.max(EH2)])+b1,'-b')
plt.plot(EH2, EO2,'ro')
plt.xlabel('${\Delta}$E$_{H}$ (eV)',size=32)
plt.ylabel('${\Delta}$E$_{O}$ (eV)',size=32)
plt.legend(['${\Delta}$E$_{O}$=%s${\Delta}$E$_{H}$ + %s eV' %(round(m1,2),(round(b1,2)))],loc=2,prop={'size':32},frameon=False)
plt.xticks(size=28)
plt.yticks(size=28)
plt.xlim([1.97,3.2])
plt.ylim([2.4,6])
plt.gcf().subplots_adjust(bottom=0.15)
mat.rc('text', usetex = True)

Marker = []
for i in range(0,len(Data.Metal)):
    Marker.append(''.join(Data.Metal[i]))
mat.rc('text', usetex = False)

texts = []
for x, y, s in zip(EH2, EO2, Data.Metal):
    texts.append(plt.text(x, y, s, bbox={'pad':0, 'alpha':0}, size=32, fontweight='bold',style='normal',name ='Calibri'))
adjustText.adjust_text(texts,autoalign=True,only_move={'points':'y','text':'y'}, )
plt.show()
print(R2)
Example #39
0
ord = ord.sort_values(ascending=False)
plt.figure(figsize=(8, 7))
plt.axhline(0, c="black")
ax = sns.pointplot(x="name", y="tot_flux", hue="metabolite",
                   data=scfa[scfa.name.isin(ord.index[ord > 1])], ci="sd",
                   order=ord.index[ord > 1], join=False, dodge=True)
ax.grid(axis="x", color="gainsboro")
ax.xaxis.set_tick_params(rotation=90)
sns.despine(left=True, bottom=True)
plt.xlabel("")
plt.tight_layout()
plt.savefig("scfas.svg")
plt.close()


mat = fluxes.pivot("taxa", "reaction", "flux").fillna(0.0)
taxa = mat.index.str.split("_").str[0]
tsne = TSNE(n_components=2).fit_transform(mat)
tsne = pd.DataFrame(tsne, columns=["x", "y"], index=mat.index)
tsne["taxa"] = taxa
sns.set(font_scale=1.5, style="ticks")
g = sns.FacetGrid(tsne, hue="taxa", size=10, aspect=16/10)
gm = g.map(plt.scatter, "x", "y", alpha=0.25)
means = tsne.groupby(taxa).agg("median").reset_index()
texts = means.apply(lambda df: plt.text(df.x, df.y, df.taxa, alpha=0.65),
                    axis=1)
texts = adjust_text(texts, force_text=(0.02, 0.5),
                    arrowprops=dict(arrowstyle='-|>', alpha=0.5, color="k"))
plt.savefig("individual_media.png", dpi=200)
plt.close()
Example #40
0
plt.figure(figsize=(16,8),dpi=500)
plt.plot(vMO,MrO,'o',markersize=12)
plt.title('Reduced Mass for Oxygen adsorbed on Metals Calculated from DFT',size=12, fontweight='bold')
plt.xlabel('v(M-O) $cm^{-1}$',size=20, fontweight='bold')
plt.ylabel('$Mr^{0.5}$ $(g/mol)^{0.5}$',size=20, fontweight='bold')
plt.xticks(size=16)
plt.yticks(size=16)
mat.rc('text', usetex = True)
Marker = []
for i in range(0,len(vMO)):
    Marker.append(''.join(Metal_Info[i,0]+'${^{'+str(round(Data[i,10])).rstrip('.0'))+'}}$')
mat.rc('text', usetex = False)
texts = []
for x, y, s in zip(vMO, MrO, Marker):
    texts.append(plt.text(x, y, s, bbox={'pad':0, 'alpha':0}, size=20, fontweight='bold',style='normal',name ='Calibri'))
adjustText.adjust_text(texts, vMO,MrO,autoalign=True,va='bottom',
                ha='right',arrowprops=dict(arrowstyle="-", color='k', lw=2))
plt.show()

#Plotting Reduced Masses
plt.figure(1)
plt.figure(figsize=(10,10),dpi=500)
plt.plot(vMO,MrH,'or',markersize=16)
plt.title('Atomic H on hollow sites: PBE-D3',size=24, fontweight='bold')
plt.xlabel('v(M-O) $cm^{-1}$',size=24, fontweight='bold')
plt.ylabel('$Mr^{0.5}$ $(g/mol)^{0.5}$',size=24, fontweight='bold')
plt.xticks(size=20)
plt.yticks(size=20)
mat.rc('text', usetex = True)
Marker = []
for i in range(0,len(vMO)):
    Marker.append(''.join(Metal_Info[i,0]+'${^{'+str(round(Data[i,10])).rstrip('.0'))+'}}$')