Python seaborn.barplot() Examples

The following are 30 code examples of seaborn.barplot(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module seaborn , or try the search function .
Example #1
Source File: brute_force_plotter.py    From brute-force-plotter with MIT License 7 votes vote down vote up
def bar_box_violin_dot_plots(data, category_col, numeric_col, axes, file_name=None):
    sns.barplot(category_col, numeric_col, data=data, ax=axes[0])
    sns.boxplot(
        category_col, numeric_col, data=data[data[numeric_col].notnull()], ax=axes[2]
    )
    sns.violinplot(
        category_col,
        numeric_col,
        data=data,
        kind="violin",
        inner="quartile",
        scale="count",
        split=True,
        ax=axes[3],
    )
    sns.stripplot(category_col, numeric_col, data=data, jitter=True, ax=axes[1])
    sns.despine(left=True) 
Example #2
Source File: plaidplotter.py    From plaidbench with Apache License 2.0 6 votes vote down vote up
def plot(data, column, column_order, ymax):
    g = sns.FacetGrid(
        data,
        col=column,
        col_order = column_order,
        sharex=False,
        size = 3.5,
        aspect = .7
    )

    g.map(
        sns.barplot,
        "model", "GFLOP/s", "batch",
        hue_order = list(set(data['batch'])).sort(),
        order = list(set(data['batch'])).sort()
    )

    if ymax == 0:
        ymax = 1
    else:
        plt.yticks(np.arange(0, ymax + (ymax * .1), ymax/10))

    axes = np.array(g.axes.flat)
    #hue_start = random.random()
    for ax in axes:
        #ax.hlines(.0003, -0.5, 0.5, linestyle='--', linewidth=1, color=getColor(hue_start, .6, .9))
        ax.set_ylim(0, ymax)

    return plt.gcf(), axes 
Example #3
Source File: dqn_atari_visual.py    From cleanrl with MIT License 6 votes vote down vote up
def render(self, mode="human"):
        if mode=="rgb_array":
            env_rgb_array = super().render(mode)
            fig, ax = plt.subplots(figsize=(self.image_shape[1]/100,self.image_shape[0]/100), constrained_layout=True, dpi=100)
            df = pd.DataFrame(np.array(self.q_values).T)
            sns.barplot(x=df.index, y=0, data=df, ax=ax)
            ax.set(xlabel='actions', ylabel='q-values')
            fig.canvas.draw()
            X = np.array(fig.canvas.renderer.buffer_rgba())
            Image.fromarray(X)
            # Image.fromarray(X)
            rgb_image = np.array(Image.fromarray(X).convert('RGB'))
            plt.close(fig)
            q_value_rgb_array = rgb_image
            return np.append(env_rgb_array, q_value_rgb_array, axis=1)
        else:
            super().render(mode)

# TRY NOT TO MODIFY: setup the environment 
Example #4
Source File: ppo_atari_visual.py    From cleanrl with MIT License 6 votes vote down vote up
def render(self, mode="human"):
        if mode=="rgb_array":
            env_rgb_array = super().render(mode)
            fig, ax = plt.subplots(figsize=(self.image_shape[1]/100,self.image_shape[0]/100), constrained_layout=True, dpi=100)
            df = pd.DataFrame(np.array(self.probs).T)
            sns.barplot(x=df.index, y=0, data=df, ax=ax)
            ax.set(xlabel='actions', ylabel='probs')
            fig.canvas.draw()
            X = np.array(fig.canvas.renderer.buffer_rgba())
            Image.fromarray(X)
            # Image.fromarray(X)
            rgb_image = np.array(Image.fromarray(X).convert('RGB'))
            plt.close(fig)
            q_value_rgb_array = rgb_image
            return np.append(env_rgb_array, q_value_rgb_array, axis=1)
        else:
            super().render(mode)

# TRY NOT TO MODIFY: setup the environment 
Example #5
Source File: helpers.py    From AiGEM_TeamHeidelberg2017 with MIT License 6 votes vote down vote up
def plot_histogram(log_file, save_dir):
    count_dict = {}
    with open(log_file, "r") as in_fobj:
        for line in in_fobj:
            pred_labels = line.strip().split()
            for label in pred_labels:
                try:
                    count_dict[label] += 1
                except KeyError:
                    count_dict[label] = 0
    bars = [count_dict[label] for label in count_dict.keys()]
    labels = [label for label in count_dict.keys()]
    set_style("whitegrid")
    fig, ax = plt.subplots()
    ax = barplot(x=bars, y=labels)
    fig.save(os.path.join(save_dir, 'negative_test.png')) 
Example #6
Source File: flower_classifier.py    From deep-learning-flower-identifier with MIT License 6 votes vote down vote up
def plot_solution(image_path, model):
    """
    Plot an image with the top 5 class prediction
    :param image_path:
    :param model:
    :return:
    """
    # Set up plot
    plt.figure(figsize=(6, 10))
    ax = plt.subplot(2, 1, 1)
    # Set up title
    flower_num = image_path.split('/')[3]
    title_ = cat_to_name[flower_num]
    # Plot flower
    img = process_image(image_path)
    imshow(img, ax, title=title_);
    # Make prediction
    probs, labs, flowers = predict(image_path, model)
    # Plot bar chart
    plt.subplot(2, 1, 2)
    sns.barplot(x=probs, y=flowers, color=sns.color_palette()[0]);
    plt.show() 
Example #7
Source File: chart.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 6 votes vote down vote up
def image(path: str, costs: Dict[str, int]) -> str:
    ys = ['0', '1', '2', '3', '4', '5', '6', '7+', 'X']
    xs = [costs.get(k, 0) for k in ys]
    sns.set_style('white')
    sns.set(font='Concourse C3', font_scale=3)
    g = sns.barplot(ys, xs, palette=['#cccccc'] * len(ys))
    g.axes.yaxis.set_ticklabels([])
    rects = g.patches
    sns.set(font='Concourse C3', font_scale=2)
    for rect, label in zip(rects, xs):
        if label == 0:
            continue
        height = rect.get_height()
        g.text(rect.get_x() + rect.get_width()/2, height + 0.5, label, ha='center', va='bottom')
    g.margins(y=0, x=0)
    sns.despine(left=True, bottom=True)
    g.get_figure().savefig(path, transparent=True, pad_inches=0, bbox_inches='tight')
    plt.clf() # Clear all data from matplotlib so it does not persist across requests.
    return path 
Example #8
Source File: step3.py    From mexican-government-report with MIT License 6 votes vote down vote up
def plot_most_used_words(df):
    """Generates a bar plot with the counts of the most used lemmas.

    Parameters
    ----------
    df : pandas.DataFrame
        The DataFrame to be plotted.

    """

    # Small fix for programa and programar.
    df.loc[df["lemma_lower"] == "programa", "lemma_lower"] = "programar"

    # Only take into account alphabet tokens that are longer than 1 character and are not stop words.
    words = df[
        (df["is_alphabet"] == True) &
        (df["is_stopword"] == False) &
        (df["lemma_lower"].str.len() > 1)
    ]["lemma_lower"].value_counts()[:20]

    sns.barplot(x=words.values, y=words.index, palette="Blues_d", linewidth=0)
    plt.xlabel("Occurrences Count")
    plt.title("Most Frequent Words")
    plt.savefig("words_counts.png", facecolor="#5C0E10") 
Example #9
Source File: site_stability.py    From CatLearn with GNU General Public License v3.0 6 votes vote down vote up
def plot_features(self,
                      labels=None,
                      frequencies=None,
                      show=True):
        """Plots feature frequencies"""
        print('Plotting feature frequencies.')
        if labels is None:
            labels = list(self.feature_frequencies.keys())
        if frequencies is None:
            frequencies = list(self.feature_frequencies.values())
        fig, ax = plt.subplots(figsize=(12, int(len(labels)*0.6)))
        ax = sns.barplot(x=frequencies, y=labels)
        ax.set_xlabel(r'Occurrence probability (\%)')
        plt.tight_layout()

        if show:
            plt.show()

        return fig, ax 
Example #10
Source File: helpers.py    From AiGEM_TeamHeidelberg2017 with MIT License 6 votes vote down vote up
def plot_histogram(log_file, save_dir):
    """Simple plotting function to plot a hist from a specified file containing counts per labels.

    Args:
        log_file: A `str` to the file containing the histogram data.
    """
    count_dict = {}
    with open(log_file, "r") as in_fobj:
        for line in in_fobj:
            pred_labels = line.strip().split()
            for label in pred_labels:
                try:
                    count_dict[label] += 1
                except KeyError:
                    count_dict[label] = 0
    bars = [count_dict[label] for label in count_dict.keys()]
    labels = [label for label in count_dict.keys()]
    set_style("whitegrid")
    fig, ax = plt.subplots()
    ax = barplot(x=bars, y=labels)
    fig.save(os.path.join(save_dir, 'negative_test.png')) 
Example #11
Source File: plot.py    From chainer-chemistry with MIT License 6 votes vote down vote up
def save_evaluation_plot(x, y, metric, filename):
    plt.figure()

    sns.set()
    ax = sns.barplot(y=x, x=y)

    for n, (label, _y) in enumerate(zip(x, y)):
        ax.annotate(
            '{:.3f}'.format(abs(_y)),
            xy=(_y, n),
            ha='right',
            va='center',
            xytext=(-5, 0),
            textcoords='offset points',
            color='white')

    plt.title('Performance on own dataset')
    plt.xlabel(metric)
    plt.savefig(filename) 
Example #12
Source File: summary_eval_molnet.py    From chainer-chemistry with MIT License 6 votes vote down vote up
def save_evaluation_plot(x, y_mean, metric, dataset_name, filename):
    plt.figure()

    sns.set()
    ax = sns.barplot(y=x, x=y_mean)

    # If "text" does not work, change the attribute name to "s"
    for n, (label, _y) in enumerate(zip(x, y_mean)):
        ax.annotate(
            s='{:.3f}'.format(abs(_y)),
            xy=(_y, n),
            ha='right',
            va='center',
            xytext=(-5, 0),
            textcoords='offset points',
            color='white')

    plt.title('Performance on ' + dataset_name)
    plt.xlabel(metric)
    plt.savefig(filename) 
Example #13
Source File: analyze_action.py    From L2RPN with GNU Lesser General Public License v3.0 6 votes vote down vote up
def analyze():
  action_count = np.load(action_count_dir, allow_pickle=True)
  print('action count loaded')

  # action taken > 0
  count_dict = {}
  for i, v in enumerate(action_count):
    if v > 0:
      count_dict[i] = v

  print('\n\n')
  for k, v in sorted(count_dict.items()):
    print('action: {}, count: {}'.format(k, v))

  # y = np.load(data_dir + '/y_all_3695_score.npy')
  # print(y[:20])

  # plot barplot
  seaborn.lineplot(list(count_dict.keys()), list(count_dict.values()))
  plt.title('Action Count')
  plt.xlabel('Action Index')
  plt.ylabel('Count')
  plt.show() 
Example #14
Source File: bam_multi_qc.py    From wub with Mozilla Public License 2.0 6 votes vote down vote up
def plot_bars_sns(data_map, title, xlab, ylab, plotter):
    """Barplot using seaborn backend.
    :param data_map: A dictionary of labels and values.
    :param title: Plot title.
    :param xlab: X axis label.
    :param ylab: Y axis label.
    :param plotter: A wub.vis.report.Report instance.
    """
    data = pd.DataFrame({'Value': list(data_map.values()), 'Label': list(data_map.keys()),
                         'x': np.arange(len(data_map))})
    ax = sns.barplot(x="x", y="Value", hue="Label", data=data, hue_order=list(data_map.keys()))
    ax.set_title(title)
    ax.set_xlabel(xlab)
    ax.set_ylabel(ylab)
    ax.set_xticks([])
    plotter.pages.savefig()
    plotter.plt.clf() 
Example #15
Source File: plot.py    From chainer-chemistry with MIT License 6 votes vote down vote up
def save_evaluation_plot(x, y, metric, filename):
    plt.figure()

    sns.set()
    ax = sns.barplot(y=x, x=y)

    for n, (label, _y) in enumerate(zip(x, y)):
        ax.annotate(
            s='{:.4g}'.format(abs(_y)),
            xy=(_y, n),
            ha='left',
            va='center',
            xytext=(5, 0),
            textcoords='offset points',
            color='gray')

    plt.title('Performance on qm9: {}'.format(metric))
    plt.xlabel(metric)
    plt.savefig(filename)
    plt.close() 
Example #16
Source File: thesis_charts.py    From yelp with GNU Lesser General Public License v2.1 6 votes vote down vote up
def plot_context_richness_score_specific_vs_generic():
    prefix = Constants.RESULTS_FOLDER + Constants.ITEM_TYPE + \
             '_topic_model_context_richness'
    csv_file_path = prefix + '.csv'
    json_file_path = prefix + '.json'

    review_type_field = 'Review type'

    data_frame = pandas.read_csv(csv_file_path)
    data_frame.drop(columns=['cycle_time'], inplace=True)
    data_frame['num_topics'].astype('category')
    data_frame['bow_type'].fillna('All', inplace=True)
    data_frame.rename(columns=
        {Constants.TOPIC_MODEL_TARGET_REVIEWS_FIELD: review_type_field}, inplace=True)
    data_frame = data_frame.loc[data_frame['bow_type'] == 'NN']
    print(data_frame.describe())
    print(data_frame.head())

    g = seaborn.barplot(
        x='num_topics', y='probability_score', hue=review_type_field,
        data=data_frame)
    g.set(xlabel='Number of topics', ylabel='Context-richness')
    plt.ylim(0, 0.14)
    g.figure.savefig(prefix + '_specific_vs_generic.pdf')
    # plt.show() 
Example #17
Source File: thesis_charts.py    From yelp with GNU Lesser General Public License v2.1 6 votes vote down vote up
def plot_context_richness_score_pos_types():
    prefix = Constants.RESULTS_FOLDER + Constants.ITEM_TYPE + \
             '_topic_model_context_richness'
    csv_file_path = prefix + '.csv'
    json_file_path = prefix + '.json'

    bow_type_field = 'POS type'
    # bow_type_field = 'bow_type'

    data_frame = pandas.read_csv(csv_file_path)
    data_frame.drop(columns=['cycle_time'], inplace=True)
    data_frame['num_topics'].astype('category')
    data_frame['bow_type'].fillna('All', inplace=True)
    data_frame.rename(columns={'bow_type': bow_type_field}, inplace=True)
    data_frame = data_frame.loc[data_frame[
        Constants.TOPIC_MODEL_TARGET_REVIEWS_FIELD] == Constants.SPECIFIC]
    print(data_frame.describe())
    print(data_frame.head())

    g = seaborn.barplot(
        x='num_topics', y='probability_score', hue=bow_type_field, data=data_frame)
    g.set(xlabel='Number of topics', ylabel='Context richness score')
    plt.ylim(0, 0.14)
    g.figure.savefig(prefix + '_pos_types.pdf') 
Example #18
Source File: analyze.py    From TTS with Mozilla Public License 2.0 5 votes vote down vote up
def plot_phonemes(train_path, cmu_dict_path, save_path):
    cmudict = CMUDict(cmu_dict_path)

    phonemes = {}

    with open(train_path, 'r') as f:
        data = csv.reader(f, delimiter='|')
        phonemes["None"] = 0
        for row in data:
            words = row[3].split()
            for word in words:
                pho = cmudict.lookup(word)
                if pho:
                    indie = pho[0].split()
                    for nemes in indie:
                        if phonemes.get(nemes):
                            phonemes[nemes] += 1
                        else:
                            phonemes[nemes] = 1
                else:
                    phonemes["None"] += 1

    x, y = [], []
    for key in phonemes:
        x.append(key)
        y.append(phonemes[key])

    plt.figure()
    plt.rcParams["figure.figsize"] = (50, 20)
    barplot = sns.barplot(x, y)
    if save_path:
        fig = barplot.get_figure()
        fig.savefig(os.path.join(save_path, "phoneme_dist")) 
Example #19
Source File: analyze.py    From TTS with Mozilla Public License 2.0 5 votes vote down vote up
def plot_phonemes(train_path, cmu_dict_path, save_path):
    cmudict = CMUDict(cmu_dict_path)

    phonemes = {}

    with open(train_path, 'r') as f:
        data = csv.reader(f, delimiter='|')
        phonemes["None"] = 0
        for row in data:
            words = row[3].split()
            for word in words:
                pho = cmudict.lookup(word)
                if pho:
                    indie = pho[0].split()
                    for nemes in indie:
                        if phonemes.get(nemes):
                            phonemes[nemes] += 1
                        else:
                            phonemes[nemes] = 1
                else:
                    phonemes["None"] += 1

    x, y = [], []
    for key in phonemes:
        x.append(key)
        y.append(phonemes[key])

    plt.figure()
    plt.rcParams["figure.figsize"] = (50, 20)
    barplot = sns.barplot(x, y)
    if save_path:
        fig = barplot.get_figure()
        fig.savefig(os.path.join(save_path, "phoneme_dist")) 
Example #20
Source File: analyze.py    From TTS with Mozilla Public License 2.0 5 votes vote down vote up
def plot_phonemes(train_path, cmu_dict_path, save_path):
    cmudict = CMUDict(cmu_dict_path)

    phonemes = {}

    with open(train_path, 'r') as f:
        data = csv.reader(f, delimiter='|')
        phonemes["None"] = 0
        for row in data:
            words = row[3].split()
            for word in words:
                pho = cmudict.lookup(word)
                if pho:
                    indie = pho[0].split()
                    for nemes in indie:
                        if phonemes.get(nemes):
                            phonemes[nemes] += 1
                        else:
                            phonemes[nemes] = 1
                else:
                    phonemes["None"] += 1

    x, y = [], []
    for key in phonemes:
        x.append(key)
        y.append(phonemes[key])

    plt.figure()
    plt.rcParams["figure.figsize"] = (50, 20)
    barplot = sns.barplot(x, y)
    if save_path:
        fig = barplot.get_figure()
        fig.savefig(os.path.join(save_path, "phoneme_dist")) 
Example #21
Source File: analyze.py    From TTS with Mozilla Public License 2.0 5 votes vote down vote up
def plot_phonemes(train_path, cmu_dict_path, save_path):
    cmudict = CMUDict(cmu_dict_path)

    phonemes = {}

    with open(train_path, 'r') as f:
        data = csv.reader(f, delimiter='|')
        phonemes["None"] = 0
        for row in data:
            words = row[3].split()
            for word in words:
                pho = cmudict.lookup(word)
                if pho:
                    indie = pho[0].split()
                    for nemes in indie:
                        if phonemes.get(nemes):
                            phonemes[nemes] += 1
                        else:
                            phonemes[nemes] = 1
                else:
                    phonemes["None"] += 1

    x, y = [], []
    for key in phonemes:
        x.append(key)
        y.append(phonemes[key])

    plt.figure()
    plt.rcParams["figure.figsize"] = (50, 20)
    barplot = sns.barplot(x, y)
    if save_path:
        fig = barplot.get_figure()
        fig.savefig(os.path.join(save_path, "phoneme_dist")) 
Example #22
Source File: analyze.py    From TTS with Mozilla Public License 2.0 5 votes vote down vote up
def plot_phonemes(train_path, cmu_dict_path, save_path):
    cmudict = CMUDict(cmu_dict_path)

    phonemes = {}

    with open(train_path, 'r') as f:
        data = csv.reader(f, delimiter='|')
        phonemes["None"] = 0
        for row in data:
            words = row[3].split()
            for word in words:
                pho = cmudict.lookup(word)
                if pho:
                    indie = pho[0].split()
                    for nemes in indie:
                        if phonemes.get(nemes):
                            phonemes[nemes] += 1
                        else:
                            phonemes[nemes] = 1
                else:
                    phonemes["None"] += 1

    x, y = [], []
    for key in phonemes:
        x.append(key)
        y.append(phonemes[key])

    plt.figure()
    plt.rcParams["figure.figsize"] = (50, 20)
    barplot = sns.barplot(x, y)
    if save_path:
        fig = barplot.get_figure()
        fig.savefig(os.path.join(save_path, "phoneme_dist")) 
Example #23
Source File: analyze.py    From TTS with Mozilla Public License 2.0 5 votes vote down vote up
def plot_phonemes(train_path, cmu_dict_path, save_path):
    cmudict = CMUDict(cmu_dict_path)

    phonemes = {}

    with open(train_path, 'r') as f:
        data = csv.reader(f, delimiter='|')
        phonemes["None"] = 0
        for row in data:
            words = row[3].split()
            for word in words:
                pho = cmudict.lookup(word)
                if pho:
                    indie = pho[0].split()
                    for nemes in indie:
                        if phonemes.get(nemes):
                            phonemes[nemes] += 1
                        else:
                            phonemes[nemes] = 1
                else:
                    phonemes["None"] += 1

    x, y = [], []
    for key in phonemes:
        x.append(key)
        y.append(phonemes[key])

    plt.figure()
    plt.rcParams["figure.figsize"] = (50, 20)
    barplot = sns.barplot(x, y)
    if save_path:
        fig = barplot.get_figure()
        fig.savefig(os.path.join(save_path, "phoneme_dist")) 
Example #24
Source File: analyze.py    From TTS with Mozilla Public License 2.0 5 votes vote down vote up
def plot_phonemes(train_path, cmu_dict_path, save_path):
    cmudict = CMUDict(cmu_dict_path)

    phonemes = {}

    with open(train_path, 'r') as f:
        data = csv.reader(f, delimiter='|')
        phonemes["None"] = 0
        for row in data:
            words = row[3].split()
            for word in words:
                pho = cmudict.lookup(word)
                if pho:
                    indie = pho[0].split()
                    for nemes in indie:
                        if phonemes.get(nemes):
                            phonemes[nemes] += 1
                        else:
                            phonemes[nemes] = 1
                else:
                    phonemes["None"] += 1

    x, y = [], []
    for key in phonemes:
        x.append(key)
        y.append(phonemes[key])

    plt.figure()
    plt.rcParams["figure.figsize"] = (50, 20)
    barplot = sns.barplot(x, y)
    if save_path:
        fig = barplot.get_figure()
        fig.savefig(os.path.join(save_path, "phoneme_dist")) 
Example #25
Source File: analyze.py    From TTS with Mozilla Public License 2.0 5 votes vote down vote up
def plot_phonemes(train_path, cmu_dict_path, save_path):
    cmudict = CMUDict(cmu_dict_path)

    phonemes = {}

    with open(train_path, 'r') as f:
        data = csv.reader(f, delimiter='|')
        phonemes["None"] = 0
        for row in data:
            words = row[3].split()
            for word in words:
                pho = cmudict.lookup(word)
                if pho:
                    indie = pho[0].split()
                    for nemes in indie:
                        if phonemes.get(nemes):
                            phonemes[nemes] += 1
                        else:
                            phonemes[nemes] = 1
                else:
                    phonemes["None"] += 1

    x, y = [], []
    for key in phonemes:
        x.append(key)
        y.append(phonemes[key])

    plt.figure()
    plt.rcParams["figure.figsize"] = (50, 20)
    barplot = sns.barplot(x, y)
    if save_path:
        fig = barplot.get_figure()
        fig.savefig(os.path.join(save_path, "phoneme_dist")) 
Example #26
Source File: analyze.py    From TTS with Mozilla Public License 2.0 5 votes vote down vote up
def plot_phonemes(train_path, cmu_dict_path, save_path):
    cmudict = CMUDict(cmu_dict_path)

    phonemes = {}

    with open(train_path, 'r') as f:
        data = csv.reader(f, delimiter='|')
        phonemes["None"] = 0
        for row in data:
            words = row[3].split()
            for word in words:
                pho = cmudict.lookup(word)
                if pho:
                    indie = pho[0].split()
                    for nemes in indie:
                        if phonemes.get(nemes):
                            phonemes[nemes] += 1
                        else:
                            phonemes[nemes] = 1
                else:
                    phonemes["None"] += 1

    x, y = [], []
    for key in phonemes:
        x.append(key)
        y.append(phonemes[key])

    plt.figure()
    plt.rcParams["figure.figsize"] = (50, 20)
    barplot = sns.barplot(x, y)
    if save_path:
        fig = barplot.get_figure()
        fig.savefig(os.path.join(save_path, "phoneme_dist")) 
Example #27
Source File: analyze.py    From TTS with Mozilla Public License 2.0 5 votes vote down vote up
def plot_phonemes(train_path, cmu_dict_path, save_path):
    cmudict = CMUDict(cmu_dict_path)

    phonemes = {}

    with open(train_path, 'r') as f:
        data = csv.reader(f, delimiter='|')
        phonemes["None"] = 0
        for row in data:
            words = row[3].split()
            for word in words:
                pho = cmudict.lookup(word)
                if pho:
                    indie = pho[0].split()
                    for nemes in indie:
                        if phonemes.get(nemes):
                            phonemes[nemes] += 1
                        else:
                            phonemes[nemes] = 1
                else:
                    phonemes["None"] += 1

    x, y = [], []
    for key in phonemes:
        x.append(key)
        y.append(phonemes[key])

    plt.figure()
    plt.rcParams["figure.figsize"] = (50, 20)
    barplot = sns.barplot(x, y)
    if save_path:
        fig = barplot.get_figure()
        fig.savefig(os.path.join(save_path, "phoneme_dist")) 
Example #28
Source File: analyze.py    From TTS with Mozilla Public License 2.0 5 votes vote down vote up
def plot_phonemes(train_path, cmu_dict_path, save_path):
    cmudict = CMUDict(cmu_dict_path)

    phonemes = {}

    with open(train_path, 'r') as f:
        data = csv.reader(f, delimiter='|')
        phonemes["None"] = 0
        for row in data:
            words = row[3].split()
            for word in words:
                pho = cmudict.lookup(word)
                if pho:
                    indie = pho[0].split()
                    for nemes in indie:
                        if phonemes.get(nemes):
                            phonemes[nemes] += 1
                        else:
                            phonemes[nemes] = 1
                else:
                    phonemes["None"] += 1

    x, y = [], []
    for key in phonemes:
        x.append(key)
        y.append(phonemes[key])

    plt.figure()
    plt.rcParams["figure.figsize"] = (50, 20)
    barplot = sns.barplot(x, y)
    if save_path:
        fig = barplot.get_figure()
        fig.savefig(os.path.join(save_path, "phoneme_dist")) 
Example #29
Source File: plotting.py    From fitbit-analyzer with Apache License 2.0 5 votes vote down vote up
def _prepareWeekdayByMonthStats(stats):
    # Add day and month columns, and groupby
    stats = stats.copy()
    stats['day'] = stats['date'].dt.weekday
    stats['month'] = stats['date'].dt.month
    dataToPlot = stats.groupby(['day', 'month']).mean()

    dataToPlot = dataToPlot.reset_index()
    dataToPlot['day'].replace(dayOfWeek, inplace=True)
    dataToPlot['month'].replace(months, inplace=True)

    return dataToPlot

# def plotWeekdayStats(stats, columns):
#     """
#     Plot aggregated (mean) stats by dayOfWeek
#     :param stats: data to plot
#     :param columns: columns from stats to plot
#     """
#     MEASURE_NAME = 'weekday'
#     dayOfWeek={0:'Mon', 1:'Tue', 2:'Wed', 3:'Thur', 4:'Fri', 5:'Sat', 6:'Sun'}
#     order = ['Mon','Tue','Wed','Thur','Fri','Sat','Sun']
#     stats[MEASURE_NAME] = stats[MEASURE_NAME].map(dayOfWeek)
#
#     f, axes = getAxes(2,2)
#     for i, c in enumerate(columns):
#         if c in NAMES:
#             c = NAMES[c]
#         g = sns.barplot(x=MEASURE_NAME, y=c, data=stats, order=order, ax=axes[i])
#         g.set_xlabel('')
#     sns.plt.show()
#     #plot(stats, columns, MEASURE_NAME, 2, 3, order=order) 
Example #30
Source File: analyze.py    From TTS with Mozilla Public License 2.0 5 votes vote down vote up
def plot_phonemes(train_path, cmu_dict_path, save_path):
    cmudict = CMUDict(cmu_dict_path)

    phonemes = {}

    with open(train_path, 'r') as f:
        data = csv.reader(f, delimiter='|')
        phonemes["None"] = 0
        for row in data:
            words = row[3].split()
            for word in words:
                pho = cmudict.lookup(word)
                if pho:
                    indie = pho[0].split()
                    for nemes in indie:
                        if phonemes.get(nemes):
                            phonemes[nemes] += 1
                        else:
                            phonemes[nemes] = 1
                else:
                    phonemes["None"] += 1

    x, y = [], []
    for key in phonemes:
        x.append(key)
        y.append(phonemes[key])

    plt.figure()
    plt.rcParams["figure.figsize"] = (50, 20)
    barplot = sns.barplot(x, y)
    if save_path:
        fig = barplot.get_figure()
        fig.savefig(os.path.join(save_path, "phoneme_dist"))