Python matplotlib.pyplot.bar() Examples

The following are code examples for showing how to use matplotlib.pyplot.bar(). 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: helloworld   Author: pip-uninstaller-python   File: matplotlibTest.py    GNU General Public License v2.0 6 votes vote down vote up
def bar():
    fig = plt.figure()  # 建立一个表格
    fig.add_subplot(332)  # n>10不可用这个数值
    n = 10  # 10个点
    X = np.arange(n)  # 构建一个数列 0-9
    # 营造出来一种有变化的效果
    Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)  # *随机数, 随机数范围在0.5-1.0之间
    Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
    # 然后画出来
    plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
    plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
    for x, y in zip(X, Y1):  # 添加注释 位置, 格式, ha水平位置, va垂直位置
        plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom')
    for x, y in zip(X, Y1):
        plt.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va='top')
    plt.show() 
Example 2
Project: recaptcha-cracker   Author: nocturnaltortoise   File: main.py    GNU General Public License v3.0 6 votes vote down vote up
def graph_query_amounts(captcha_queries, query_amounts):
    queries_and_amounts = zip(captcha_queries, query_amounts)
    queries_and_amounts = sorted(queries_and_amounts, key=lambda x:x[1], reverse=True)
    captcha_queries, query_amounts = zip(*queries_and_amounts)

    # colours = cm.Dark2(np.linspace(0,1,len(captcha_queries)))
    # legend_info = zip(query_numbers, colours)
    # random.shuffle(colours)
    # captcha_queries = [textwrap.fill(query, 10) for query in captcha_queries] 
    bars = plt.bar(left=range(len(query_amounts)), height=query_amounts)
    plt.xlabel('CAPTCHA queries.')
    plt.ylabel('Query frequencies.')
    plt.xticks([])
    # plt.xticks(range(len(captcha_queries)), captcha_queries, rotation='vertical')
    
    # colours = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w', ]

    patches = [mpatches.Patch(color=colours[j], label=captcha_queries[j]) for j in range(len(captcha_queries))]
    plt.legend(handles=patches)

    for i, bar in enumerate(bars):
        bar.set_color(colours[i])
    
    plt.show() 
Example 3
Project: recaptcha-cracker   Author: nocturnaltortoise   File: main.py    GNU General Public License v3.0 6 votes vote down vote up
def graph_correct_captchas(captcha_queries, correct_captchas):
    queries_and_correct_scores = zip(captcha_queries, correct_captchas)
    queries_and_correct_scores = sorted(queries_and_correct_scores, key=lambda x:x[1], reverse=True)
    captcha_queries, correct_captchas = zip(*queries_and_correct_scores)

    captcha_queries = [textwrap.fill(query, 10) for query in captcha_queries]
    bars = plt.bar(left=range(len(correct_captchas)), height=correct_captchas)

    patches = [mpatches.Patch(color=colours[j], label=captcha_queries[j]) for j in range(len(captcha_queries))]
    plt.legend(handles=patches)
    plt.xticks([])

    for i, bar in enumerate(bars):
        bar.set_color(colours[i])

    plt.show()

# graph_correct_captchas(captcha_queries, correct_captchas)
# graph_query_amounts(captcha_queries, query_amounts) 
Example 4
Project: IntentionPrediction   Author: djp42   File: eval_util.py    MIT License 6 votes vote down vote up
def plotAccuracies(accuracies, models, title, plot_savepath, doAvg=True):
    colors = ['r', 'b', 'g', 'y', 'k', 'c', 'm', '0.75']
    width=0.8/len(models)
    i = 0
    x_poses = []
    for key in models:#accuracies.keys():
        x = [0]
        if not doAvg:
            x = list(range(len(accuracies[key])))
        x = [j + (width*i) for j in x]
        plt.bar(x, accuracies[key], width=width, color = colors[i])
        i += 1
        x_poses.extend(x)
    plt.xticks([i + width/2 for i in x_poses], models)
    plt.ylim((.40,1.00))
    this_title = title + "_overall_accuracies" 
    this_title = this_title.replace(".","-")
    plt.title(this_title)
    plt.savefig(plot_savepath+this_title)
    plt.show() 
Example 5
Project: celer   Author: mathurinm   File: plot_utils.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_path_hist(results, labels, tols, figsize, ylim=None):
    configure_plt()
    sns.set_palette('colorblind')
    n_competitors = len(results)
    fig, ax = plt.subplots(figsize=figsize)
    width = 1. / (n_competitors + 1)
    ind = np.arange(len(tols))
    b = (1 - n_competitors) / 2.
    for i in range(n_competitors):
        plt.bar(ind + (i + b) * width, results[i], width,
                label=labels[i])
    ax.set_ylabel('path computation time (s)')
    ax.set_xticks(ind + width / 2)
    plt.xticks(range(len(tols)), ["%.0e" % tol for tol in tols])
    if ylim is not None:
        plt.ylim(ylim)

    ax.set_xlabel(r"$\epsilon$")
    plt.legend(loc='upper left')
    plt.tight_layout()
    plt.show(block=False)
    return fig 
Example 6
Project: TF_RL   Author: Rowing0914   File: visualise.py    MIT License 6 votes vote down vote up
def plot_Q_values(data, xmin=-1, xmax=4, ymin=0, ymax=2):
    """
    Real time Bar plot of Q_values

    :param data:
    :param xmin:
    :param xmax:
    :param ymin:
    :param ymax:
    :return:
    """
    plt.axis([xmin, xmax, ymin, ymax])
    # print(data)
    length = np.arange(data.shape[0])
    plt.bar(length, data, align='center')
    plt.xticks(length)
    plt.xlabel("Actions")
    plt.ylabel("Q_values")
    plt.pause(0.02)
    plt.clf() 
Example 7
Project: ctw-baseline   Author: yuantailing   File: plot_tools.py    MIT License 6 votes vote down vote up
def draw_bar(data, labels, width=None, xticks_font_fname=None, legend_kwargs=dict()):
    n = len(labels)
    m = len(data)
    if not width:
        width = 1. / (m + .6)
    off = 1.
    legend_bar = []
    legend_text = []
    for i, a in enumerate(data):
        for j, b in enumerate(a):
            assert n == len(b['data'])
            ind = [off + k + (i + (1 - m) / 2) * width for k in range(n)]
            bottom = [sum(d) for d in zip(*[c['data'] for c in a[j + 1:]])] or None
            p = plt.bar(ind, b['data'], width, bottom=bottom, color=b.get('color'))
            legend_bar.append(p[0])
            legend_text.append(b['legend'])
    ind = [off + i for i, label in enumerate(labels) if label is not None]
    labels = [label for label in labels if label is not None]
    font = FontProperties(fname=xticks_font_fname)
    plt.xticks(ind, labels, fontproperties=font, ha='center')
    plt.legend(legend_bar, legend_text, **legend_kwargs) 
Example 8
Project: QFiPy   Author: kouzapo   File: equities.py    MIT License 6 votes vote down vote up
def plot_price(self):
		closeDF, dates = self.get_prices(return_dates = True)
		rolling_mean = pd.DataFrame(closeDF).rolling(window = 60, min_periods = 0).mean()
		dates = pd.to_datetime(dates)
		volume = self.get_volume()

		fig, (ax1, ax2) = plt.subplots(2, sharex = True, gridspec_kw = {'height_ratios': [4, 1]})
		fig.autofmt_xdate()

		ax1.plot(dates, closeDF, color = 'blue', linewidth = 1.8, label = "Price")
		ax1.plot(dates, rolling_mean, color = 'red', linewidth = 1.0, label = "Rolling Mean")

		ax2.bar(dates, volume, width = 2, color = 'blue', label = "Volume")

		plt.suptitle(str(self.quote) + " value movement and Volume", fontsize = 20)
		ax1.set_ylabel("Price", fontsize = 12)
		ax2.set_ylabel("Volume", fontsize = 12)
		ax1.legend(loc = 2)
		xfmt = mdates.DateFormatter('%Y-%m-%d')
		ax1.xaxis.set_major_formatter(xfmt)

		plt.show() 
Example 9
Project: QFiPy   Author: kouzapo   File: equities.py    MIT License 6 votes vote down vote up
def plot_ACF(self, max_lag, confidence = 0.05):
		lags = np.arange(1, max_lag + 1, 1)
		ACF = self.calc_ACF(lags)

		confidence_interval = stats.norm.ppf(1 - confidence / 2) / np.sqrt(len(self.calc_log_returns()))

		plt.bar(lags, ACF, width = 0.7, color = 'blue', label = 'ACF')

		plt.plot([0, max_lag], [confidence_interval, confidence_interval], color = 'red', linestyle = ':')
		plt.plot([0, max_lag], [-confidence_interval, -confidence_interval], color = 'red', linestyle = ':')

		plt.ylabel('ACF')
		plt.xlabel('Lag')
		plt.legend(loc = 2)
		plt.title('Autocorrelation Function for ' + self.quote, fontsize = 15)

		plt.show() 
Example 10
Project: QFiPy   Author: kouzapo   File: equities.py    MIT License 6 votes vote down vote up
def plot_PACF(self, max_lag, confidence = 0.05):
		lags = np.arange(1, max_lag + 1, 1)
		PACF = self.calc_PACF(lags)

		confidence_interval = stats.norm.ppf(1 - confidence / 2) / np.sqrt(len(self.calc_log_returns()))

		plt.bar(lags, PACF, width = 0.7, color = 'blue', label = 'PACF')

		plt.plot([0, max_lag], [confidence_interval, confidence_interval], color = 'red', linestyle = ':')
		plt.plot([0, max_lag], [-confidence_interval, -confidence_interval], color = 'red', linestyle = ':')

		plt.ylabel('PACF')
		plt.xlabel('Lag')
		plt.legend(loc = 2)
		plt.title('Partial Autocorrelation Function for ' + self.quote, fontsize = 15)

		plt.show() 
Example 11
Project: Bag-of-Visual-Words-Python   Author: kushalvyas   File: helpers.py    MIT License 6 votes vote down vote up
def plotHist(self, vocabulary = None):
		print "Plotting histogram"
		if vocabulary is None:
			vocabulary = self.mega_histogram

		x_scalar = np.arange(self.n_clusters)
		y_scalar = np.array([abs(np.sum(vocabulary[:,h], dtype=np.int32)) for h in range(self.n_clusters)])

		print y_scalar

		plt.bar(x_scalar, y_scalar)
		plt.xlabel("Visual Word Index")
		plt.ylabel("Frequency")
		plt.title("Complete Vocabulary Generated")
		plt.xticks(x_scalar + 0.4, x_scalar)
		plt.show() 
Example 12
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def plot(loss_list, predictions_series, batchX, batchY):
    plt.subplot(2, 3, 1)
    plt.cla()
    plt.plot(loss_list)

    for batch_series_idx in range(5):
        one_hot_output_series = np.array(predictions_series)[:, batch_series_idx, :]
        single_output_series = np.array([(1 if out[0] < 0.5 else 0) for out in one_hot_output_series])

        plt.subplot(2, 3, batch_series_idx + 2)
        plt.cla()
        plt.axis([0, truncated_backprop_length, 0, 2])
        left_offset = range(truncated_backprop_length)
        plt.bar(left_offset, batchX[batch_series_idx, :], width=1, color="blue")
        plt.bar(left_offset, batchY[batch_series_idx, :] * 0.5, width=1, color="red")
        plt.bar(left_offset, single_output_series * 0.3, width=1, color="green")

    plt.draw()
    plt.pause(0.0001) 
Example 13
Project: aug   Author: cta-ai   File: performance_test.py    Apache License 2.0 6 votes vote down vote up
def main():
    img = cv2.imread('lena.jpg')
    results = {}

    for op in ops:
        # show(images)
        op_result = op.time(img.copy())
        results = {**results, **op_result}
        # show(op.apply(images.copy()))

    print(json.dumps(results, indent=4))
    print('Total: {}'.format(sum(results.values())))

    plt.bar(range(len(results)), list(results.values()), align='center')
    plt.yscale('log')
    plt.xticks(range(len(results)), list(results.keys()), rotation='vertical')

    plt.show()
    with open('ops_performance.csv', 'w') as f:
        w = csv.DictWriter(f, fieldnames=['name', 'time'])
        w.writeheader()
        for k, v in results.items():
            w.writerow({'name': k, 'time': v}) 
Example 14
Project: carla-training-data   Author: enginBozkurt   File: data_stats.py    MIT License 6 votes vote down vote up
def read_data_dir(label_dirpath):
    datapoints = []
    cars_per_image = defaultdict(int)
    for filepath in os.listdir(label_dirpath):
        num_cars = 0
        for line in open(os.path.join(label_dirpath, filepath), "r").readlines():
            datapoint = Object3d(line)
            datapoints.append(datapoint)
            num_cars += 1
        cars_per_image[num_cars] += 1
    num_cars = len([x for x in datapoints if x.type == "Car"])

    print("Total number of cars: ", num_cars)

    print("Cars per image: ", cars_per_image)
    keys = cars_per_image.keys()
    values = cars_per_image.values()
    #plt.bar(keys, values)
    #plt.yticks(range(0, 13000, 1000))
    #plt.xlabel("Cars per image")
    #plt.ylabel("Number of images")
    #plt.show()
    print_stats(datapoints) 
Example 15
Project: counting-strokes-in-chinese-characters   Author: yienxu   File: logistic_maxpooling.py    MIT License 6 votes vote down vote up
def plot_df_counts(df):
    x_ticks = np.asarray(list(set(df['count'])))
    xx = np.arange(np.max(x_ticks) + 1)
    yy = np.bincount(df['count'])

    for x, y in zip(xx, yy):
        print("{}->{}\t".format(x, y), end='')

    plt.bar(xx, yy)
    plt.title('Stroke Counts of Characters')
    plt.xlabel('Number of Strokes')
    plt.ylabel('Number of Characters')
    plt.show()


# plot_df_counts(df) 
Example 16
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 6 votes vote down vote up
def empty_plot_with_size_bar(self, gridspec, sizelabel):
		"""
		Adds an empty plot with the x axis as a size bar

		Parameters
		----------
		gridspec : gridspec
		sizelabel : str
			This label is place in the center
		"""
		plt.subplot(gridspec)
		plt.plot([0, 1], alpha=0)
		ax = plt.gca()
		trans = mpl.transforms.blended_transform_factory(
							ax.transAxes, ax.transAxes)
		plt.annotate(
			 '', xy=(0, 0), xycoords=trans,
			xytext=(1, 0), textcoords=trans,
			arrowprops={'arrowstyle': '<->', 'shrinkA': 1, 'shrinkB': 1,
						'lw':1.5,
						'mutation_scale': 10., 'color': 'black'})
		general_utils.plotting.remove_all_ticks(ax)
		general_utils.plotting.invisible_axis(ax)
		plt.setp(ax, xticks=[0.5], xticklabels=[sizelabel]) 
Example 17
Project: whatsapp-stats   Author: nielsrolf   File: analyze.py    Apache License 2.0 5 votes vote down vote up
def actual_categorical_plot(group, stat, keys, values):
    name = stat + " " + group
    plt.clf()
    plt.bar(range(len(keys)), values)
    plt.xticks(range(len(keys)), keys)
    plt.title(name)
    plt.savefig(PLOT_PATH + "/" + name+".png")
    plt.clf() 
Example 18
Project: phoneticSimilarity   Author: ronggong   File: baseline1_oracle_GOP.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def disLinePlot(dis, list_phn):
    """plot the dissimilarity list line"""
    plt.figure()
    plt.bar(np.arange(len(dis)), dis, alpha=0.7, align='center')
    plt.xticks(np.arange(len(list_phn)), list_phn)
    plt.show() 
Example 19
Project: phoneticSimilarity   Author: ronggong   File: baseline3_oracle_Embedding_classifier.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def disLinePlot(dis, list_phn):
    """plot the dissimilarity list line"""
    plt.figure()
    plt.bar(np.arange(len(dis)), dis, alpha=0.7, align='center')
    plt.xticks(np.arange(len(list_phn)), list_phn)
    plt.show() 
Example 20
Project: phoneticSimilarity   Author: ronggong   File: baseline4_oracle_Embedding_frame_level.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def disLinePlot(dis, list_phn):
    """plot the dissimilarity list line"""
    plt.figure()
    plt.bar(np.arange(len(dis)), dis, alpha=0.7, align='center')
    plt.xticks(np.arange(len(list_phn)), list_phn)
    plt.show() 
Example 21
Project: L3C-PyTorch   Author: fab-jul   File: histogram_plotter.py    GNU General Public License v3.0 5 votes vote down vote up
def _plot_histogram(data, plt, width, offset):
    name, values = data
    plt.bar(np.arange(len(values)) + offset, values,
            width=width,
            label=name, align='edge') 
Example 22
Project: tripp   Author: mjamesruggiero   File: munge.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_histogram(points, bucket_size, title="", asset="histogram.png"):
    """generate plot for bucketed data"""
    histogram = make_histogram(points, bucket_size)
    pyplot.bar(histogram.keys(), histogram.values(), width=bucket_size)
    pyplot.title(title)
    pyplot.savefig(asset) 
Example 23
Project: bitcointalk-sentiment   Author: DolphinBlockchainIntelligence   File: graph_builder.py    MIT License 5 votes vote down vote up
def build_graph(input_file, save_to):

    with open(str(input_file),'r') as file:
        sentiment_dict = json.load(file)

    dates = []
    positives = []
    neutral = []
    negatives = []

    for date in sentiment_dict.keys():
        dates.append(date)
        positives.append(sentiment_dict[date]['positive'])
        neutral.append(sentiment_dict[date]['neutral'])
        negatives.append(sentiment_dict[date]['negative'])

    ind = np.arange(len(dates))
    plt.figure(figsize=(len(dates)/4, 5))
    p1 = plt.bar(ind, negatives, color='red')
    p2 = plt.bar(ind, neutral, bottom=negatives, color='yellow')
    p3 = plt.bar(ind, positives, bottom=[a + b for a, b in zip(neutral, negatives)], color='green')

    plt.ylabel('Number of posts')
    plt.xlabel('Day')
    plt.title('Sentiment')
    plt.xticks(ind, dates, rotation='vertical',fontsize='x-small')
    plt.legend((p1[0], p2[0], p3[0]), ('Negative', 'Neutral', 'Positive'))
    plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)

    if save_to != '':
        plt.savefig(save_to, bbox_inches='tight')

    plt.show() 
Example 24
Project: Life   Author: MyNameBeMrRandom   File: imaging.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def do_bar_chart(title, x_label, y_label, values, names):

    # Clear the plot.
    plt.clf()

    #Create a bar graph with grid lines
    plt.bar(names, values, width=0.5, zorder=3)
    plt.grid(zorder=0)

    # Add labels
    plt.ylabel(y_label)
    plt.xlabel(x_label)
    plt.title(title)

    # Rotate x-labels by 90 degrees
    plt.xticks(rotation=-90)

    # Make the layout of plot conform to the text
    plt.tight_layout()

    # Save the image to a buffer.
    bar_chart = BytesIO()
    plt.savefig(bar_chart)

    # Close the image.
    plt.close()

    # Return image
    bar_chart.seek(0)
    return bar_chart 
Example 25
Project: twitter_analysis   Author: urmilkadakia   File: analysis_methods.py    Apache License 2.0 5 votes vote down vote up
def ngram_histogram(input_file, output_file, n=1, cutoff_freq=5, alpha_numeric_flag=0, stop_words_flag=0):
    """
    The function to plot and store the histogram of the specified ngram and their frequencies for the ngrams which has
    frequency greater than cutoff_freq
    :param input_file: Path to input file
    :param output_file: Path to output file
    :param n: n represents the n in n-gram which is a contiguous sequence of n items. The default vale is 1 which
              represents unigram.
    :param cutoff_freq: The ngrams that has less frequency than the cut off frequency will not be included in the
                        output file.  The default value is 5.
    :param alpha_numeric_flag: filter all non alpha numeric words. Default is false.
    :param stop_words_flag: filter all stop words. Default is false.
    """
    ngram_freq = count_ngram_frequency(input_file, n, alpha_numeric_flag, stop_words_flag)
    ngram_freq = ngram_freq.most_common()

    xdata = []
    ydata = []

    for x, y in ngram_freq:
        if y < cutoff_freq:
            break

        # if not any(elem in x for elem in stop_words):
        # Checking the ngram is unigram or not
        if n == 1:
            xdata.append(x[0])
        else:
            xdata.append(str(x))
        ydata.append(y)

    # Plotting the ngrams of the given file
    plt.bar(xdata, ydata)
    plt.xlabel('Ngrams', fontsize=12)
    plt.xticks(xdata, xdata, rotation=80)
    plt.ylabel('Frequency', fontsize=12)
    plt.title('Ngram frequency distribution ', fontsize=14)
    plt.gcf().subplots_adjust(bottom=0.45)
    plt.savefig(output_file) 
Example 26
Project: year2018   Author: baijiangliang   File: report.py    MIT License 5 votes vote down vote up
def draw_commit_distribution(self):
        img = Image.new('RGBA', default_size, 'white')
        self.add_header(img)
        self.add_footer(img)
        stat = self.repos.get_commit_times_by_hour()
        most_hour = max(stat.keys(), key=lambda x: stat[x])
        most_percent = max(util.get_percents(list(stat.values()), digits=1))
        texts1 = [
            '你提交代码最多的时间段是 ',
            '{0}:00 - {1}:00'.format(most_hour, most_hour + 1),
        ]
        bolds1 = [1]
        texts2 = [
            '你在这个时间段提交代码的次数占总数的 ',
            str(most_percent) + '%',
        ]
        bolds2 = [1]
        draw_center_with_y(img, 240, texts1, bolds1, self.styles)
        draw_center_with_y(img, 300, texts2, bolds2, self.styles)
        hours = sorted(stat.keys())
        commits = [stat[hour] for hour in hours]
        plt.figure(1, figsize=(5, 3.5))
        plt.bar(hours, commits, width=0.6, color=colors[2], edgecolor='black')
        plt.title('Commit times by hour')
        plt.xticks(hours)
        plt.yticks(range(0, max(commits) + 10, 10))
        fig_path = self.save_fig('commit_bar', 'png')
        commit_bar = Image.open(fig_path)
        img.paste(commit_bar, (100, 400))
        self.save_img(img, '8_commit_distribution', 'png') 
Example 27
Project: datawhisperer   Author: nmannheimer   File: viz.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot(self, *args, **kwargs):
        plt.bar(*args, **kwargs)
        plt.show() 
Example 28
Project: IntentionPrediction   Author: djp42   File: eval_util.py    MIT License 5 votes vote down vote up
def makeConfusionMatrix(actuals, predictions, percentage = True, swap=False,
                      title=None, savepath=None):
    counts = {}
    for i in range(len(actuals)):
        y = int(actuals[i])
        x = int(predictions[i])
        if not y in counts.keys():
            counts[y] = [0] * len(set(predictions))
        counts[y][x-1] += 1
    print(counts)
    width =  0.5
    colors = ['r', 'b', 'g', 'y', 'k', 'c', 'm', '0.75']
    numKeys = len(list(counts.keys()))
    numVals = len(counts[list(counts.keys())[0]])
    heights = [[0] * numKeys] * numVals  #yes, its flipped on purpose
    for key in sorted(list(counts.keys())):
        cumsum = 0
        tot = sum(counts[key])
        for i in range(numVals):
            num = counts[key][i]
            height = (tot - cumsum) 
            if percentage: height /= tot
            plt.bar(key, height, width, color=colors[i])
            heights[i][int(key)] = height
            cumsum += num
    plt.title(title)
    if title:
        plt.savefig(savepath+title, format="png")
    plt.show()

    return heights 
Example 29
Project: BiLatticeRNN-data-processing   Author: alecokas   File: lattice_dataset_exploration.py    MIT License 5 votes vote down vote up
def histogram_image(hist, bin_edges, file_name):
    plt.bar(bin_edges[:-1], hist, width=1, color='r')
    plt.xlim(min(bin_edges), max(bin_edges))
    plt.savefig(file_name) 
Example 30
Project: ml-helper-funcs   Author: numb3r33   File: feature_selection.py    MIT License 5 votes vote down vote up
def ensemble_learning(X, y):
	"""
	Fit Random Forest Classifier and use variable importance
	"""
	clf = RandomForestClassifier(n_estimators=100)
	clf.fit(X, y)
	
	plt.bar(range(100), clf.feature_importances_)
	plt.show()
	
	return clf.feature_importances_ 
Example 31
Project: ml-helper-funcs   Author: numb3r33   File: feature_selection.py    MIT License 5 votes vote down vote up
def feature_importance_plots(feature_importances, len_X):
	start = 0
	step = 50
	
	while start < len_X:
		sel = np.arange(start, min(start + step, len_X))
		plt.figure(figsize=(17, 3))
		plt.bar(sel, feature_importances[sel])
		plt.ylabel('Importance')
		start += step
	
	plt.show() 
Example 32
Project: RiboCode   Author: xryanglab   File: metaplots.py    MIT License 5 votes vote down vote up
def lengthDistribution(length_counter,outname):
	w,h = plt.figaspect(0.4)
	plt.figure(figsize=(w,h))
	x = sorted(length_counter.keys())
	y = [length_counter[i] for i in x]
	plt.bar(x,y,width=0.95,edgecolor="white",align="center",color="#297FFF")
	plt.savefig(outname + "_readlength_distribution.pdf")
	plt.close() 
Example 33
Project: 20180116-FullStack-Day   Author: PdxCodeGuild   File: l24_rain.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_year_totals(dict_list):
    totals = []
    year_list = []
    for year in range(1998, 2019):
        totals.append(get_yearly_total(dict_list, year))
        year_list.append(year)
    plt.bar(year_list, totals)
    plt.ylabel('Rainfall in inches')
    plt.xlabel('Year')
    plt.suptitle('Total collected rainfall per year: 1998-2018')
    plt.show()


# Statistical function calls 
Example 34
Project: lightwood   Author: mindsdb   File: infersent.py    MIT License 5 votes vote down vote up
def visualize(self, sent, tokenize=True):

        sent = sent.split() if not tokenize else self.tokenize(sent)
        sent = [[self.bos] + [word for word in sent if word in self.word_vec] + [self.eos]]

        if ' '.join(sent[0]) == '%s %s' % (self.bos, self.eos):
            import warnings
            warnings.warn('No words in "%s" have w2v vectors. Replacing \
                           by "%s %s"..' % (sent, self.bos, self.eos))
        batch = self.get_batch(sent)

        if self.is_cuda():
            batch = batch.cuda()
        output = self.enc_lstm(batch)[0]
        output, idxs = torch.max(output, 0)
        # output, idxs = output.squeeze(), idxs.squeeze()
        idxs = idxs.data.cpu().numpy()
        argmaxs = [np.sum((idxs == k)) for k in range(len(sent[0]))]

        # visualize model
        import matplotlib.pyplot as plt
        x = range(len(sent[0]))
        y = [100.0 * n / np.sum(argmaxs) for n in argmaxs]
        plt.xticks(x, sent[0], rotation=45)
        plt.bar(x, y)
        plt.ylabel('%')
        plt.title('Visualisation of words importance')
        plt.show()

        return output, idxs 
Example 35
Project: morty   Author: altugkarakurt   File: pitchdistribution.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def bar(self):
        bars = plt.bar(self.bins, self.vals, width=self.step_size,
                       align='center')
        self.label_figure()

        return bars 
Example 36
Project: Visualization-of-sort-algorithms   Author: ForeverPs   File: SORT.py    MIT License 5 votes vote down vote up
def draw(self, s, fun):
		if len(s):
			self.count += 1
			plt.clf()
			plt.bar(range(len(s)), s, width = 0.3, color = 'purple')
			plt.title(fun)
			plt.savefig('sp/' + str(self.count))
			plt.pause(0.01) 
Example 37
Project: RCK   Author: aganezov   File: rck_adj_stats.py    MIT License 5 votes vote down vote up
def add_bar_values(ax, bars):
    for bar in bars:
        height = bar.get_height()
        ax.text(bar.get_x() + bar.get_width() / 2., 1.01 * height,
                '%d' % int(height),
                ha='center', va='bottom', fontsize=20) 
Example 38
Project: fanalysis   Author: OlivierGarciaDev   File: base.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_eigenvalues(self, type="absolute", figsize=None):
        """ Plot the eigen values graph
        
        Parameters
        ----------
        type : string
            Select the graph to plot :
                - If "absolute" : plot the eigenvalues.
                - If "percentage" : plot the percentage of variance.
                - If "cumulative" : plot the cumulative percentage of
                  variance.
        figsize : tuple of integers or None
            Width, height of the figure in inches.
            If not provided, defaults to rc figure.figsize

        Returns
        -------
        None
        """
        plt.figure(figsize=figsize)
        if type == "absolute":
            plt.bar(np.arange(1, self.eig_[0].shape[0] + 1), self.eig_[0],
                    color="steelblue", align="center")
            plt.xlabel("Axis")
            plt.ylabel("Eigenvalue")
        elif type == "percentage":
            plt.bar(np.arange(1, self.eig_[1].shape[0] + 1), self.eig_[1],
                    color="steelblue", align="center")
            plt.xlabel("Axis")
            plt.ylabel("Percentage of variance")
        elif type == "cumulative":
            plt.bar(np.arange(1, self.eig_[2].shape[0] + 1), self.eig_[2],
                    color="steelblue", align="center")
            plt.xlabel("Axis")
            plt.ylabel("Cumulative percentage of variance")
        else:
            raise Exception("Error : 'type' variable must be 'absolute' or \
                            'percentage' or 'cumulative'")
        plt.title("Scree plot")
        plt.show() 
Example 39
Project: kaggle-spark-ml   Author: imgoodman   File: explore.py    MIT License 5 votes vote down vote up
def generateImage(itemCountByValue,itemName="", is_type=True):
    if True==is_type:
        plt.bar(range(len(itemCountByValue.keys())),itemCountByValue.values(), tick_label=itemCountByValue.keys())
    else:
        plt.bar([float(k) for k in itemCountByValue.keys()], itemCountByValue.values())
    plt.savefig("%s%s.png" % (image_file_path, itemName)) 
Example 40
Project: timetrack   Author: ravenscroftj   File: timetrack.py    MIT License 5 votes vote down vote up
def report_graph(args, echo=False):
    """Generate a bar chart report for the given timeframe."""
    start_date, end_date = parse_time_args(args)
    report_data = OrderedDict(sorted(project_report(start_date, end_date, echo).items()))

    fig = pyplot.figure()
    titleString = "Project Breakdown: {}".format(start_date.strftime("%Y-%m-%d"))

    if start_date != end_date:
        titleString+=" to {}".format(end_date.strftime("%Y-%m-%d"))

    fig.suptitle(titleString, fontsize=14, fontweight='bold')

    ax = fig.add_subplot(1,1,1)
    fig.subplots_adjust(top=0.85)
    num_reports = len(report_data)

    my_colors = ['c','m','y','r', 'g', 'b']

    for key in report_data.keys():
        report_data[key] = report_data[key]/60.0

    if args.pie:
        pyplot.axis('equal')
        pyplot.pie(report_data.values(), labels=list(report_data.keys()), autopct='%1.1f%%', colors=my_colors, startangle=90)
    else:
        ax.set_xlabel('Project')
        ax.set_ylabel('Hours')
        pyplot.bar(range(num_reports), report_data.values(), align='center', color=my_colors)
        pyplot.xticks(range(num_reports), list(report_data.keys()))

    pyplot.show() 
Example 41
Project: ikinci_duzey_plotlar   Author: lyk2018-python   File: ufo.py    GNU General Public License v3.0 5 votes vote down vote up
def show_graphics():
    ufo_data_list = get_ufo_data()
    shapes = [ufo["shape"] for ufo in ufo_data_list]
    counts = [ufo["count"] for ufo in ufo_data_list]

    plt.title("National UFO Reporting Center\nReport Index by Shape of Craft")
    plt.bar(shapes, counts)
    plt.xticks(rotation=45)
    plt.show() 
Example 42
Project: image-compression-cnn   Author: iamaaditya   File: read_log.py    MIT License 5 votes vote down vote up
def plot(values, metric_name):

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import sys

    plt.style.use('ggplot')

    fig, ax = plt.subplots(1, 1, figsize=(25, 3))
    ax.margins(0)

    x = []
    y = []
    for index,v in enumerate( values ):
        # if not index: continue
        # plt.plot(x, new_recall, linewidth=2, label='Condensed Mem Network')
        x.append(index)
        y.append(v[1]['our']-v[1]['jpeg'])

    # plt.plot(x,y, 'o')
    # plt.semilogy(x,y)
    y_neg = [max(0,i) for i in y]
    y_pos = [min(0,i) for i in y]

    plt.bar(x,y_neg)
    plt.bar(x,y_pos, color='r')
    plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='off')

    plt.title(metric_name.upper(), x=0.5, y=0.8, fontsize=14)
    plt.legend(loc='')
    ax.get_xaxis().set_visible(False)
    ax.xaxis.set_major_formatter(plt.NullFormatter())
    fig.tight_layout()
    # plt.savefig('plot_size_' + metric_name + '.png', bbox_inches='tight_layout', pad_inches=0)
    plt.savefig('plot_kodak_' + metric_name + '.png') 
Example 43
Project: counting-strokes-in-chinese-characters   Author: yienxu   File: df_visualization.py    MIT License 5 votes vote down vote up
def plot_df_counts(df):
    x_ticks = np.asarray(list(set(df['count'])))
    xx = np.arange(np.max(x_ticks) + 1)
    yy = np.bincount(df['count'])

    for x, y in zip(xx, yy):
        print("{}->{}\t".format(x, y), end='')

    plt.bar(xx, yy)
    plt.title('Stroke Counts of Characters')
    plt.xlabel('Number of Strokes')
    plt.ylabel('Number of Characters')
    #     plt.savefig('counts.eps')
    plt.show() 
Example 44
Project: canvas-api-python   Author: dkloz   File: plotting.py    MIT License 5 votes vote down vote up
def plot_bars(data, legend, color='blue'):
    plt.bar(range(len(data)), data, color=color, label=legend, alpha=0.75) 
Example 45
Project: verb-attributes   Author: uwnlp   File: fig_4.py    MIT License 5 votes vote down vote up
def att_plot(top_labels, gt_ind, probs, fn):
    # plt.figure(figsize=(5, 5))
    #
    # color_dict = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
    # colors = [color_dict[c] for c in
    #           ['lightcoral', 'steelblue', 'forestgreen', 'darkviolet', 'sienna', 'dimgrey',
    #            'darkorange', 'gold']]
    # colors[gt_ind] = color_dict['crimson']
    # w = 0.9
    # plt.bar(np.arange(len(top_labels)), probs, w, color=colors, alpha=.9, label='data')
    # plt.axhline(0, color='black')
    # plt.ylim([0, 1])
    # plt.xticks(np.arange(len(top_labels)), top_labels, fontsize=6)
    # plt.subplots_adjust(bottom=.15)
    # plt.tight_layout()
    # plt.savefig(fn)
    lab = deepcopy(top_labels)
    lab[gt_ind] += ' (gt)'
    d = pd.DataFrame(data={'probs': probs, 'labels':lab})
    fig, ax = plt.subplots(figsize=(4,5))
    ax.tick_params(labelsize=15)

    sns.barplot(y='labels', x='probs', ax=ax, data=d, orient='h', ci=None)
    ax.set(xlim=(0,1))

    for rect, label in zip(ax.patches,lab):
        w = rect.get_width()
        ax.text(w+.02, rect.get_y() + rect.get_height()*4/5, label, ha='left', va='bottom',
                fontsize=25)

    # ax.yaxis.set_label_coords(0.5, 0.5)
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.get_yaxis().set_visible(False)
    ax.get_xaxis().label.set_visible(False)
    fig.savefig(fn, bbox_inches='tight', transparent=True)
    plt.close('all') 
Example 46
Project: spatial_patterns   Author: sim-web   File: plotting.py    GNU General Public License v3.0 5 votes vote down vote up
def distance_histogram_for_ratemap(self, frame=-1):
        from .gridscore.ratemaps import RateMaps

        for psp in self.psps:
            self.set_params_rawdata_computed(psp, set_sim_params=True)
            # from gridscore.ratemaps_plotting import Plot
            ratemap = self.get_output_rates(frame=frame, spacing=None,
                                            from_file=True, squeeze=True)
            arena_limits = np.array([[0, 1], [0, 1]])
            rmps = RateMaps(rm=ratemap, arena_limits=arena_limits)
            n, centers = rmps.get_distancehistogram_and_centers()
            rmps.plot_distancehistogram()
            # plot = Plot(ratemap=ratemap)
            # rmps.plot_ratemap()
            # plt.bar(centers, n, align='center', width=width, color='black') 
Example 47
Project: spatial_patterns   Author: sim-web   File: figures.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_xlabel_and_sizebar(self, plot_sizebar=False):
		"""
		Used to add the size bar label and the size bar to rate maps.

		Usable in Figure 2 (grids) and Figure 4 (cell types).
		This plots a sizebar inside the contour plots.
		In order to get it under the figure, you need to create two
		plots, one with sizebars, and one without. The one with sizebars
		your mask and remove leftover with white boxes.
		This is a hack, but it's better than adjusting the sizebars
		manually.

		Parameters
		----------
		plot_sizebar : bool
			If False, only the xlabel is plotted.
			If True, a sizebar is plotted inside the rate map
			or the correlogram or the input tuning
		"""
		r = 0.5
		ax = plt.gca()
		# ax.spines['right'].set_color('none')
		# ax.spines['top'].set_color('none')
		# ax.spines['left'].set_color('none')
		# ax.spines['bottom'].set_color('none')
		plt.setp(ax, xticks=[], yticks=[], xlim=[-r, r], ylim=[-r, r],
				 aspect='equal')
		if plot_sizebar:
			plt.plot([-r, r], [-r, -r], color='black', lw=5)
		ax.set_xlabel('1m') 
Example 48
Project: note_analysis_2stage_tasks   Author: carolfs   File: simulate_2stage_tasks.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_probs(probs, legend=True):
    """Plot probabilities."""
    x = (0, 2)
    plt.bar(left=x, height=[probs[i] for i in x], align='center',
            color='tab:orange', label='common')
    x = (1, 3)
    plt.bar(left=x, height=[probs[i] for i in x], align='center',
            color='tab:green', label='rare')
    plt.xticks((0.5, 2.5), ('rewarded', 'unrewarded'))
    plt.ylabel('stay probability')
    if legend:
        plt.legend(loc='upper right', fontsize='medium')
    plt.ylim(0, 1)
    plt.xlim(-0.5, 3.5) 
Example 49
Project: Resting_State_CFC   Author: palvalab   File: plot_functions.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_histogram(data, N_bins=20):
    import matplotlib.pyplot as plt
    import numpy as np
    
    hist, bins = np.histogram(data, bins=N_bins)
    width = 0.7 * (bins[1] - bins[0])
    center = (bins[:-1] + bins[1:]) / 2
    plt.bar(center, hist, align='center', width=width)
    plt.show() 
Example 50
Project: fc-aaai18   Author: thanhan   File: models.py    MIT License 5 votes vote down vote up
def plot_probs(probs, reps, ss, vera, save_name = 'abc.pdf'):
    import matplotlib
    #matplotlib.rcParams['pdf.fonttype'] = 42
    import matplotlib.pyplot as plt
    from matplotlib import gridspec
    import seaborn as sns
    
    colors = sns.color_palette('colorblind')
    
    probs = np.asarray(probs)
    reps = np.asarray(reps)
    
    m = len(probs)
    for i in range(m):
        if ss[i].startswith('www.'):
            ss[i] = ss[i][4:]
    
    plt.figure(figsize=(8,2.0))
    
    gs = gridspec.GridSpec(1, 2, width_ratios=[2.8, 1])
    
    plt.subplot(gs[1]) 
    plt.ylabel('Claim Vera. Prob.')
    plt.bar(range(3), vera, color = colors[3])
    plt.xticks(range(3), ['False', 'Unk.', 'True'])
    
    plt.subplot(gs[0]) 
    plt.xlabel('Source Reputation')
    plt.yticks( np.arange(m) + 0.0, ss)
    
    p1 = plt.barh(range(m), reps * probs[:, 0], color = colors[0], hatch = '//')
    p2 = plt.barh(range(m), reps * probs[:, 1], left = reps * probs[:, 0], color = colors[1])
    p3 = plt.barh(range(m), reps * probs[:, 2], left = reps * probs[:, 0] \
                  + reps * probs[:, 1], color = colors[2], hatch = '\\\\')
    
    
    plt.legend((p1[0], p2[0], p3[0]), ('Against', 'Observing', 'For'), \
               bbox_to_anchor=(0.2, 1.001, 0.5, 0.01), ncol = 3)
    
    plt.savefig(save_name, bbox_inches = 'tight', pad_inches = 0.001, dpi = 300)