当前位置: 首页>>代码示例>>Python>>正文


Python pyplot.bar方法代码示例

本文整理汇总了Python中matplotlib.pyplot.bar方法的典型用法代码示例。如果您正苦于以下问题:Python pyplot.bar方法的具体用法?Python pyplot.bar怎么用?Python pyplot.bar使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.pyplot的用法示例。


在下文中一共展示了pyplot.bar方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: data_stat

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
def data_stat():
    """data statistic"""
    audio_path = './data/esc10/audio/'
    class_list = [os.path.basename(i) for i in glob(audio_path + '*')]
    nums_each_class = [len(glob(audio_path + cl + '/*.ogg')) for cl in class_list]
    rects = plt.bar(range(len(nums_each_class)), nums_each_class)

    index = list(range(len(nums_each_class)))
    plt.title('Numbers of each class for ESC-10 dataset')
    plt.ylim(ymax=60, ymin=0)
    plt.xticks(index, class_list, rotation=45)
    plt.ylabel("numbers")

    for rect in rects:
        height = rect.get_height()
        plt.text(rect.get_x() + rect.get_width() / 2, height, str(height), ha='center', va='bottom')

    plt.tight_layout()
    plt.show() 
开发者ID:JasonZhang156,项目名称:Sound-Recognition-Tutorial,代码行数:21,代码来源:data_analysis.py

示例2: _plot_global_imp

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
def _plot_global_imp(self, top_words, top_importances, label_name):
        """ Function to plot the global importances
        :param top_words: The tokenized words
        :type top_words: str[]
        :param top_importances: The associated feature importances
        :type top_importances: float[]
        :param label_name: The label predicted
        :type label_name: str
        """

        plt.figure(figsize=(8, 4))
        plt.title(
            "most important words for class label: " + str(label_name), fontsize=18
        )
        plt.bar(range(len(top_importances)), top_importances, color="b", align="center")
        plt.xticks(range(len(top_importances)), top_words, rotation=60, fontsize=18)
        plt.show() 
开发者ID:interpretml,项目名称:interpret-text,代码行数:19,代码来源:unified_information.py

示例3: graph_query_amounts

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
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() 
开发者ID:nocturnaltortoise,项目名称:recaptcha-cracker,代码行数:26,代码来源:main.py

示例4: graph_correct_captchas

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
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) 
开发者ID:nocturnaltortoise,项目名称:recaptcha-cracker,代码行数:21,代码来源:main.py

示例5: plot_path_hist

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
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 
开发者ID:mathurinm,项目名称:celer,代码行数:24,代码来源:plot_utils.py

示例6: draw_bar

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
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) 
开发者ID:yuantailing,项目名称:ctw-baseline,代码行数:23,代码来源:plot_tools.py

示例7: histogramPlots

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
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() 
开发者ID:tadatitam,项目名称:info-flow-experiments,代码行数:22,代码来源:plot.py

示例8: __generic_histo__

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
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 
开发者ID:westpa,项目名称:westpa,代码行数:18,代码来源:plot.py

示例9: plotHist

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
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() 
开发者ID:kushalvyas,项目名称:Bag-of-Visual-Words-Python,代码行数:18,代码来源:helpers.py

示例10: make_stats

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
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())) 
开发者ID:SudeepDasari,项目名称:visual_foresight,代码行数:18,代码来源:combine_score.py

示例11: main

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
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() 
开发者ID:ChenglongChen,项目名称:kaggle-HomeDepot,代码行数:25,代码来源:plot_feature_corr.py

示例12: firebase_plot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
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() 
开发者ID:tlkh,项目名称:SmartBin,代码行数:23,代码来源:iot.py

示例13: make_ddict_in_range

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
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 
开发者ID:expectocode,项目名称:telegram-analysis,代码行数:24,代码来源:activedays.py

示例14: plot_histogram_matrix

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
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() 
开发者ID:CSchoel,项目名称:nolds,代码行数:26,代码来源:measures.py

示例15: plot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import bar [as 别名]
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) 
开发者ID:PacktPublishing,项目名称:Neural-Network-Programming-with-TensorFlow,代码行数:21,代码来源:lstm_with_tensorflow.py


注:本文中的matplotlib.pyplot.bar方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。