Python matplotlib.pyplot.bar() Examples

The following are 30 code examples of matplotlib.pyplot.bar(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: main.py    From recaptcha-cracker with GNU General Public License v3.0 7 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 #2
Source File: main.py    From recaptcha-cracker with GNU General Public License v3.0 7 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 #3
Source File: plot_utils.py    From celer with BSD 3-Clause "New" or "Revised" License 7 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 #4
Source File: activedays.py    From telegram-analysis with MIT License 6 votes vote down vote up
def make_ddict_in_range(json_file,start,end):
    """
    return a defaultdict(int) of dates with activity on those dates in a date range
    """
    events = (loads(line) for line in json_file)
    #generator, so whole file is not put in mem
    msg_infos = (extract_info(event) for event in events if 'text' in event)
    msg_infos = ((date,weekday,length) for (date,weekday,length) in msg_infos if date >= start and date <= end)
    counter = defaultdict(int)
    #a dict with days as keys and frequency as values
    day_freqs = defaultdict(int)
    for date_text,day_text,length in msg_infos:
       counter[day_text] += length
       day_freqs[day_text] += 1

    for k,v in counter.items():
        counter[k] = v/day_freqs[k]
    #divide each day's activity by the number of times the day appeared.
    #this makes the bar height = average chars sent on that day
    #and makes the graph a more accurate representation, especially with small date ranges

    return counter 
Example #5
Source File: draw_plot.py    From TaobaoAnalysis with MIT License 6 votes vote down vote up
def draw_rate_time_plot(reviews, ignore_default=False, fix_y_limit=True):
    """
    画评价数量-时间图
    """

    good_counts, bad_counts, min_date = usefulness.get_n_rates_and_time(reviews, ignore_default)
    if not good_counts:
        return [], [], []
    bad_counts = list(map(int.__neg__, bad_counts))
    dates = [min_date + timedelta(days=day_offset)
             for day_offset in range(len(good_counts))]

    # 画图
    plt.title('评价数量-时间图')
    plt.xlabel('时间')
    plt.ylabel('评价数量')
    good_bars = plt.bar(dates, good_counts)
    bad_bars = plt.bar(dates, bad_counts)
    if fix_y_limit:
        plt.ylim(-10, 40)

    return dates, good_bars, bad_bars 
Example #6
Source File: rnn_with_tensorflow.py    From Neural-Network-Programming-with-TensorFlow with MIT License 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 batchSeriesIdx in range(5):
        oneHotOutputSeries = np.array(predictions_series)[:, batchSeriesIdx, :]
        singleOutputSeries = np.array([(1 if out[0] < 0.5 else 0) for out in oneHotOutputSeries])

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

    plt.draw()
    plt.pause(0.0001) 
Example #7
Source File: plot_tools.py    From ctw-baseline with 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
Source File: test_pickle.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_simple():
    fig = plt.figure()
    pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)

    ax = plt.subplot(121)
    pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)

    ax = plt.axes(projection='polar')
    plt.plot(np.arange(10), label='foobar')
    plt.legend()

    pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)

#    ax = plt.subplot(121, projection='hammer')
#    pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)

    plt.figure()
    plt.bar(x=np.arange(10), height=np.arange(10))
    pickle.dump(plt.gca(), BytesIO(), pickle.HIGHEST_PROTOCOL)

    fig = plt.figure()
    ax = plt.axes()
    plt.plot(np.arange(10))
    ax.set_yscale('log')
    pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL) 
Example #9
Source File: plotting.py    From RegRCNN with Apache License 2.0 6 votes vote down vote up
def label_bar(ax, rects, labels=None, colors=None, fontsize=10):
    """Attach a text label above each bar displaying its height

    :param ax:
    :param rects: rectangles as returned by plt.bar()
    :param labels:
    :param colors:
    """
    for ix, rect in enumerate(rects):
        height = rect.get_height()
        if labels is not None and labels[ix] is not None:
            label = labels[ix]
        else:
            label = '{:g}'.format(height)
        if colors is not None and colors[ix] is not None and np.any(np.array(colors[ix])<1):
            color = colors[ix]
        else:
            color = 'black'
        ax.text(rect.get_x() + rect.get_width() / 2., 1.007 * height, label, color=color, ha='center', va='bottom',
                bbox=dict(facecolor=(1., 1., 1.), edgecolor='none', clip_on=True, pad=0, alpha=0.75), fontsize=fontsize) 
Example #10
Source File: rnn_with_ms.py    From Neural-Network-Programming-with-TensorFlow with MIT License 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 batchSeriesIdx in range(5):
        oneHotOutputSeries = np.array(predictions_series)[:, batchSeriesIdx, :]
        singleOutputSeries = np.array([(1 if out[0] < 0.5 else 0) for out in oneHotOutputSeries])

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

    plt.draw()
    plt.pause(0.0001) 
Example #11
Source File: lstm_with_tensorflow.py    From Neural-Network-Programming-with-TensorFlow with MIT License 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 batchSeriesIdx in range(5):
        oneHotOutputSeries = np.array(predictions_series)[:, batchSeriesIdx, :]
        singleOutputSeries = np.array([(1 if out[0] < 0.5 else 0) for out in oneHotOutputSeries])

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

    plt.draw()
    plt.pause(0.0001) 
Example #12
Source File: plot.py    From info-flow-experiments with GNU General Public License v3.0 6 votes vote down vote up
def histogramPlots(list):
	a, b = converter.ad_vectors(list)
	obs = np.array(a)
	l = []
	colors = ['b', 'r', 'g', 'm', 'k']							# Can plot upto 5 different colors
	for i in range(0, len(list)):
		l.append([int(i) for i in obs[i]])
	pos = np.arange(1, len(obs[0])+1)
	width = 0.5     # gives histogram aspect to the bar diagram
	gridLineWidth=0.1
	fig, ax = plt.subplots()
	ax.xaxis.grid(True, zorder=0)
	ax.yaxis.grid(True, zorder=0)
	for i in range(0, len(list)):
		lbl = "ads"+str(i)
		plt.bar(pos, l[i], width, color=colors[i], alpha=0.5, label = lbl)
	#plt.xticks(pos+width/2., obs[0], rotation='vertical')		# useful only for categories
	#plt.axis([-1, len(obs[2]), 0, len(ran1)/2+10])
	plt.legend()
	plt.show() 
Example #13
Source File: plot.py    From westpa with MIT License 6 votes vote down vote up
def __generic_histo__(self, vector, labels):
        # This function just calls the appropriate plot function for our available
        # interface.  Same thing as generic_ci, but for a histogram.
        if self.interface == 'text':
            self.__terminal_histo__(vector, labels)
        else:
            try:
                import matplotlib
                matplotlib.use('TkAgg')
                from matplotlib import pyplot as plt
                plt.bar(list(range(0, np.array(vector).shape[0])), vector, linewidth=0, align='center', color='gold', tick_label=labels)
                plt.show()
            except:
                print('Unable to import plotting interface.  An X server ($DISPLAY) is required.')
                self.__terminal_histo__(h5file, vector, labels)
                return 1 
Example #14
Source File: helpers.py    From Bag-of-Visual-Words-Python with 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 #15
Source File: gaia.py    From AiGEM_TeamHeidelberg2017 with MIT License 6 votes vote down vote up
def plotdisttooriginal(self, f_width=16, f_height=8, res=200, name='hist_rel.png'):
        """
        Plots how often a position was not the original residue
        Args:
            f_width (float): specifies the width of the plot that is written
            f_height (float): specifies the height of the plot that is written
            res (float): specifies the resolution of the plot that is written
            name (str): specifies the name of plots that is written
        """

        plt.figure(1, figsize=(f_width, f_height), dpi=res, facecolor='w', edgecolor='k')
        seqpos = range(self.lenseq)
        plt.bar(seqpos, height=self.mutated_aas[:self.lenseq-1], width=1)
        plt.ylabel('Number of mutations')
        plt.xlabel('Sequence position')
        plt.title('Distribution of mutations')
        plt.savefig(os.path.join(self.savedir, name))
        plt.gcf().clear() 
Example #16
Source File: gaia.py    From AiGEM_TeamHeidelberg2017 with MIT License 6 votes vote down vote up
def plotdistoverseq(self, f_width=16, f_height=8, res=200, name='hist.png'):
        """
        Plots how often a position was mutated in a bar plot, including backmutations
        Args:
            f_width (float): specifies the width of the plot that is written
            f_height (float): specifies the height of the plot that is written
            res (float): specifies the resolution of the plot that is written
            name (str): specifies the name of plots that is written
        """

        plt.figure(1, figsize=(f_width, f_height), dpi=res, facecolor='w', edgecolor='k')
        seqpos = range(self.lenseq)
        plt.bar(seqpos, height=self.mutatingpositions, width=1)
        plt.ylabel('Number of mutations')
        plt.xlabel('Sequence position')
        plt.title('Distribution of mutations')
        plt.savefig(os.path.join(self.savedir, name))
        plt.gcf().clear() 
Example #17
Source File: measures.py    From nolds with MIT License 6 votes vote down vote up
def plot_histogram_matrix(data, name, fname=None):
  # local import to avoid dependency for non-debug use
  import matplotlib.pyplot as plt
  nhists = len(data[0])
  nbins = 25
  ylim = (0, 0.5)
  nrows = int(np.ceil(np.sqrt(nhists)))
  plt.figure(figsize=(nrows * 4, nrows * 4))
  for i in range(nhists):
    plt.subplot(nrows, nrows, i + 1)
    absmax = max(abs(np.max(data[:, i])), abs(np.min(data[:, i])))
    rng = (-absmax, absmax)
    h, bins = np.histogram(data[:, i], nbins, rng)
    bin_width = bins[1] - bins[0]
    h = h.astype("float32") / np.sum(h)
    plt.bar(bins[:-1], h, bin_width)
    plt.axvline(np.mean(data[:, i]), color="red")
    plt.ylim(ylim)
    plt.title("{:s}[{:d}]".format(name, i))
  if fname is None:
    plt.show()
  else:
    plt.savefig(fname)
  plt.close() 
Example #18
Source File: combine_score.py    From visual_foresight with MIT License 6 votes vote down vote up
def make_stats(dir, score, name, bounds):
    bin_edges = np.linspace(bounds[0], bounds[1], 11)
    binned_ind = np.digitize(score, bin_edges)
    occurrence, _ = np.histogram(score, bin_edges, density=False)
    bin_width = bin_edges[1] - bin_edges[0]
    bin_mid = bin_edges + bin_width / 2
    plt.figure()
    plt.bar(bin_mid[:-1], occurrence, bin_width, facecolor='b', alpha=0.5)
    plt.title(name)
    plt.xlabel(name)
    plt.ylabel('occurences')
    plt.savefig(dir + '/' + name + '.png')
    plt.close()
    f = open(dir + '/{}_histo.txt'.format(name), 'w')
    for i in range(bin_edges.shape[0]-1):
        f.write('indices for bin {}, {} to {} : {} \n'.format(i, bin_edges[i], bin_edges[i+1], np.where(binned_ind == i+1)[0].tolist())) 
Example #19
Source File: plot_feature_corr.py    From kaggle-HomeDepot with MIT License 6 votes vote down vote up
def main():
    colors = "rgbcmyk"
    d = grap_all_feat_corr_dict()
    keys = sorted(d.keys())
    N = len(keys)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    for e,k in enumerate(keys, start=1):
        vals = sorted(d[k])
        color = colors[(e-1) % len(colors)]
        plt.bar(np.linspace(e-0.48,e+0.48,len(vals)), vals, 
            width=1./(len(vals)+10), color=color, edgecolor=color)
    plt.xlabel("Feature Group", fontsize=15)
    plt.ylabel("Correlation Coefficient", fontsize=15)
    plt.xticks(range(1,N+1), fontsize=15)
    plt.yticks([-0.4, -0.2, 0, 0.2, 0.4], fontsize=15)
    ax.set_xticklabels(keys, rotation=45, ha="right")
    ax.set_xlim([0, N+1])
    ax.set_ylim([-0.4, 0.4])
    pos1 = ax.get_position()
    pos2 = [pos1.x0 - 0.075, pos1.y0 + 0.175,  pos1.width * 1.2, pos1.height * 0.85] 
    ax.set_position(pos2)
    plt.show() 
Example #20
Source File: iot.py    From SmartBin with MIT License 6 votes vote down vote up
def firebase_plot(firebase):
    """
    This plotting function takes in two dictionaries by calling the firebase_stats function.
    The first the the statistics by user, and the second the statistics by category.
    It then uses matplotlib to plot 2 bar charts based on the data in the respective dictionaries.
    """
    by_user_count, by_category_count = firebase_stats(firebase)

    plt.bar(range(len(by_user_count)), by_user_count.values())
    plt.xticks(range(len(by_user_count)), by_user_count.keys())
    plt.title('Statistics by user')
    plt.xlabel('User name')
    plt.ylabel('Number of items recycled')
    plt.show()

    plt.bar(range(len(by_category_count)), by_category_count.values())
    plt.xticks(range(len(by_category_count)), by_category_count.keys())
    plt.title('Statistics by category')
    plt.xlabel('Recyclable item category')
    plt.ylabel('Number of items recycled')
    plt.show() 
Example #21
Source File: test_pickle.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_simple():
    fig = plt.figure()
    # un-comment to debug
#    recursive_pickle(fig)
    pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)

    ax = plt.subplot(121)
    pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)

    ax = plt.axes(projection='polar')
    plt.plot(list(xrange(10)), label='foobar')
    plt.legend()

    # Uncomment to debug any unpicklable objects. This is slow so is not
    # uncommented by default.
#    recursive_pickle(fig)
    pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)

#    ax = plt.subplot(121, projection='hammer')
#    recursive_pickle(ax, 'figure')
#    pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)

    plt.figure()
    plt.bar(left=list(xrange(10)), height=list(xrange(10)))
    pickle.dump(plt.gca(), BytesIO(), pickle.HIGHEST_PROTOCOL)

    fig = plt.figure()
    ax = plt.axes()
    plt.plot(list(xrange(10)))
    ax.set_yscale('log')
    pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL) 
Example #22
Source File: burst_plot.py    From FRETBursts with GNU General Public License v2.0 5 votes vote down vote up
def hist_fret(
        d, i=0, ax=None, binwidth=0.03, bins=None, pdf=True,
        hist_style='bar',
        weights=None, gamma=1., add_naa=False,            # weights args
        show_fit_stats=False, show_fit_value=False, fit_from='kde',
        show_kde=False, bandwidth=0.03, show_kde_peak=False,  # kde args
        show_model=False, show_model_peaks=True,
        hist_bar_style=None, hist_plot_style=None, model_plot_style=None,
        kde_plot_style=None, verbose=False):
    """Plot FRET histogram and KDE.

    The most used argument is `binwidth` that sets the histogram bin width.

    For detailed documentation see :func:`hist_burst_data`.
    """

    hist_burst_data(
        d, i, data_name='E', ax=ax, binwidth=binwidth, bins=bins,
        pdf=pdf, weights=weights, gamma=gamma, add_naa=add_naa,
        hist_style=hist_style, show_fit_stats=show_fit_stats,
        show_fit_value=show_fit_value, fit_from=fit_from,
        show_kde=show_kde, bandwidth=bandwidth,
        show_kde_peak=show_kde_peak,  # kde args
        show_model=show_model, show_model_peaks=show_model_peaks,
        hist_bar_style=hist_bar_style, hist_plot_style=hist_plot_style,
        model_plot_style=model_plot_style, kde_plot_style=kde_plot_style,
        verbose=verbose) 
Example #23
Source File: get_stats_about_length.py    From MSMARCO-Question-Answering with MIT License 5 votes vote down vote up
def compute_stats(histogram, title):
    average = get_stats(histogram)
    print("###################################\n")
    print("Statistics about {}\n".format(title))
    print("Average length:{}",format(average))
    print("###################################\n")
    plt.bar(list(histogram.keys()), histogram.values(), color='g')
    plt.show()
    for key in sorted(histogram.keys()):
        print("{}:{}".format(key, histogram[key])) 
Example #24
Source File: test_bbox_tight.py    From neural-network-animation with MIT License 5 votes vote down vote up
def test_bbox_inches_tight():
    #: Test that a figure saved using bbox_inches='tight' is clipped correctly
    data = [[ 66386, 174296,  75131, 577908,  32015],
            [ 58230, 381139,  78045,  99308, 160454],
            [ 89135,  80552, 152558, 497981, 603535],
            [ 78415,  81858, 150656, 193263,  69638],
            [139361, 331509, 343164, 781380,  52269]]

    colLabels = rowLabels = [''] * 5

    rows = len(data)
    ind = np.arange(len(colLabels)) + 0.3  # the x locations for the groups
    cellText = []
    width = 0.4     # the width of the bars
    yoff = np.array([0.0] * len(colLabels))
    # the bottom values for stacked bar chart
    fig, ax = plt.subplots(1, 1)
    for row in xrange(rows):
        plt.bar(ind, data[row], width, bottom=yoff)
        yoff = yoff + data[row]
        cellText.append([''])
    plt.xticks([])
    plt.legend([''] * 5, loc=(1.2, 0.2))
    # Add a table at the bottom of the axes
    cellText.reverse()
    the_table = plt.table(cellText=cellText,
                          rowLabels=rowLabels,
                          colLabels=colLabels, loc='bottom') 
Example #25
Source File: burst_plot.py    From FRETBursts with GNU General Public License v2.0 5 votes vote down vote up
def hist_asymmetry(d, i=0, bin_max=2, binwidth=0.1, stat_func=np.median):
    burst_asym = bext.asymmetry(d, ich=i, func=stat_func)
    bins_pos = np.arange(0, bin_max+binwidth, binwidth)
    bins = np.hstack([-bins_pos[1:][::-1], bins_pos])
    izero = (bins.size - 1)/2.
    assert izero == np.where(np.abs(bins) < 1e-8)[0]

    counts, _ = np.histogram(burst_asym, bins=bins)
    asym_counts_neg = counts[:izero] - counts[izero:][::-1]
    asym_counts_pos = counts[izero:] - counts[:izero][::-1]
    asym_counts = np.hstack([asym_counts_neg, asym_counts_pos])

    plt.bar(bins[:-1], width=binwidth, height=counts, fc=blue, alpha=0.5)
    plt.bar(bins[:-1], width=binwidth, height=asym_counts, fc=red,
            alpha=0.5)
    plt.grid(True)
    plt.xlabel('Time (ms)')
    plt.ylabel('# Bursts')
    plt.legend(['{func}$(t_D)$ - {func}$(t_A)$'.format(func=stat_func.__name__),
                'positive half - negative half'],
               frameon=False, loc='best')
    skew_abs = asym_counts_neg.sum()
    skew_rel = 100.*skew_abs/counts.sum()
    print('Skew: %d bursts, (%.1f %%)' % (skew_abs, skew_rel))

##
#  Scatter plots
# 
Example #26
Source File: test_code_generation.py    From pylustrator with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.filename = Path(self.id().split(".")[-1]+".py")
        with self.filename.open("w") as fp:
            fp.write("""
import matplotlib.pyplot as plt
import numpy as np

# now import pylustrator
import pylustrator

# activate pylustrator
pylustrator.start()

# build plots as you normally would
np.random.seed(1)
t = np.arange(0.0, 2, 0.001)
y = 2 * np.sin(np.pi * t)
a, b = np.random.normal(loc=(5., 3.), scale=(2., 4.), size=(100,2)).T
b += a

plt.figure(1)
plt.subplot(131)
plt.plot(t, y)

plt.subplot(132)
plt.plot(a, b, "o")

plt.subplot(133)
plt.bar(0, np.mean(a))
plt.bar(1, np.mean(b))

# show the plot in a pylustrator window
plt.show(hide_window=True)
""") 
Example #27
Source File: encode_task_fraglen_stat_pe.py    From atac-seq-pipeline with MIT License 5 votes vote down vote up
def fragment_length_plot(data_file, prefix, peaks=None):
    try:
        data = read_picard_histogram(data_file)
    except IOError:
        return ''
    except TypeError:
        return ''

    fig = plt.figure()
    plt.bar(data[:, 0], data[:, 1])
    plt.xlim((0, 1000))

    if peaks:
        peak_vals = [data[peak_x, 1] for peak_x in peaks]
        plt.plot(peaks, peak_vals, 'ro')

    # plot_img = BytesIO()
    # fig.savefig(plot_img, format='png')
    plot_pdf = prefix + '.fraglen_dist.pdf'
    plot_png = prefix + '.fraglen_dist.png'

    fig.savefig(plot_pdf, format='pdf')
    pdf2png(plot_pdf, os.path.dirname(plot_pdf))
    rm_f(plot_pdf)

    return plot_png 
Example #28
Source File: plot.py    From quantified-self with MIT License 5 votes vote down vote up
def make_bar(
        x,
        y,
        f_name,
        title=None,
        legend=None,
        x_label=None,
        y_label=None,
        x_ticks=None,
        y_ticks=None,
    ):
        fig = plt.figure()

        if title is not None:
            plt.title(title, fontsize=16)
        if x_label is not None:
            plt.ylabel(x_label)
        if y_label is not None:
            plt.xlabel(y_label)
        if x_ticks is not None:
            plt.xticks(x, x_ticks)
        if y_ticks is not None:
            plt.yticks(y_ticks)

        plt.bar(x, y, align="center")

        if legend is not None:
            plt.legend(legend)

        plt.savefig(f_name)
        plt.close(fig) 
Example #29
Source File: burst_plot.py    From FRETBursts with GNU General Public License v2.0 5 votes vote down vote up
def hist_S(
        d, i=0, ax=None, binwidth=0.03, bins=None, pdf=True,
        hist_style='bar',
        weights=None, gamma=1., add_naa=False,                # weights args
        show_fit_stats=False, show_fit_value=False, fit_from='kde',
        show_kde=False, bandwidth=0.03, show_kde_peak=False,  # kde args
        show_model=False, show_model_peaks=True,
        hist_bar_style=None, hist_plot_style=None, model_plot_style=None,
        kde_plot_style=None, verbose=False):
    """Plot S histogram and KDE.

    The most used argument is `binwidth` that sets the histogram bin width.

    For detailed documentation see :func:`hist_burst_data`.    """

    hist_burst_data(
        d, i, data_name='S', ax=ax, binwidth=binwidth, bins=bins,
        pdf=pdf, weights=weights, gamma=gamma, add_naa=add_naa,
        hist_style=hist_style, show_fit_stats=show_fit_stats,
        show_fit_value=show_fit_value, fit_from=fit_from,
        show_kde=show_kde, bandwidth=bandwidth,
        show_kde_peak=show_kde_peak,  # kde args
        show_model=show_model, show_model_peaks=show_model_peaks,
        hist_bar_style=hist_bar_style, hist_plot_style=hist_plot_style,
        model_plot_style=model_plot_style, kde_plot_style=kde_plot_style,
        verbose=verbose) 
Example #30
Source File: histogram_plotter.py    From L3C-PyTorch with 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')