• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python pyplot.bar函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: ExampleWithData

def ExampleWithData(data, path):
    '''modified example from matplotlib gallery.'''

    # skip the uppermost levels as we have no
    # tracks or slices
    N = 5
    ind = np.arange(N)    # the x locations for the groups
    width = 0.35       # the width of the bars: can also be len(x) sequence

    p1 = plt.bar(ind,
                 data["menMeans"],
                 width,
                 color='r',
                 yerr=data["womenStd"])
    p2 = plt.bar(ind,
                 data["womenMeans"],
                 width,
                 color='y',
                 bottom=data["menMeans"],
                 yerr=data["menStd"])

    plt.ylabel('Scores')
    plt.title('Scores by group and gender')
    plt.xticks(ind + width / 2., ('G1', 'G2', 'G3', 'G4', 'G5'))
    plt.yticks(np.arange(0, 81, 10))
    plt.legend((p1[0], p2[0]), ('Men', 'Women'))

    # return a place holder for this figure
    return ResultBlocks(
        ResultBlock("#$mpl 0$#\n", ""),
        title="MyTitle")
开发者ID:WestFlame,项目名称:CGATReport,代码行数:31,代码来源:MyPlots.py


示例2: make_overview_plot

def make_overview_plot(filename, title, noip_arrs, ip_arrs):
    plt.title("Inner parallelism - " + title)

    
    plt.ylabel('Time (ms)', fontsize=12)

    x = 0
    barwidth = 0.5
    bargroupspacing = 1.5

    for z in zip(noip_arrs, ip_arrs):
        noip,ip = z
        noip_mean,noip_conf = conf_stats(noip)
        ip_mean,ip_conf = conf_stats(ip)

        b_noip = plt.bar(x, noip_mean, barwidth, color='r', yerr=noip_conf, ecolor='black', alpha=0.7)
        x += barwidth

        b_ip = plt.bar(x, ip_mean, barwidth, color='b', yerr=ip_conf, ecolor='black', alpha=0.7)
        x += bargroupspacing

    plt.xticks([0.5, 2.5, 4.5], ['50k', '100k', '200k'], rotation='horizontal')

    fontP = FontProperties()
    fontP.set_size('small')

    plt.legend([b_noip, b_ip], \
        ('no inner parallelism', 'inner parallelism'), \
        prop=fontP, loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=2)
   
    plt.ylim([0,62000])
    plt.savefig(output_file(filename))
    plt.clf()
开发者ID:SuperV1234,项目名称:bcs_thesis,代码行数:33,代码来源:plot_ip.py


示例3: statistics_charts

    def statistics_charts(self):
        if plt is None:
            return

        for chart in self.stats_charts:
            if chart["type"] == "plot":
                fig = plt.figure(figsize=(8, 2))
                for xdata, ydata, label in chart["data"]:
                    plt.plot(xdata, ydata, "-", label=label)
                plt.legend(loc="center left", bbox_to_anchor=(1, 0.5))
            elif chart["type"] == "timeline":
                fig = plt.figure(figsize=(16, 2))
                for i, (starts, stops, label) in enumerate(chart["data"]):
                    plt.hlines([i] * len(starts), starts, stops, label=label)
                plt.ylim(-1, len(chart["data"]))
            elif chart["type"] == "bars":
                fig = plt.figure(figsize=(16, 4))
                plt.bar(range(len(chart["data"])), chart["data"])
            elif chart["type"] == "boxplot":
                fig = plt.figure(figsize=(16, 4))
                plt.boxplot(chart["data"])
            else:
                raise Exception("Unknown chart")
            png = serialize_fig(fig)
            yield chart["name"], html_embed_img(png)
开发者ID:spirali,项目名称:aislinn,代码行数:25,代码来源:report.py


示例4: barPlot

	def barPlot(self, datalist, threshold, figname):

		tally = self.geneCount(datalist)

		#Limit the items plotted to those over 1% of the read mass
		geneplot = defaultdict()
		for g, n in tally.iteritems():
			if n > int(sum(tally.values())*threshold):
				geneplot[g] = n

		#Get plotting values
		olist = OrderedDict(sorted(geneplot.items(),key=lambda t: t[0]))
		summe = sum(olist.values())
		freq = [float(x)/float(summe) for x in olist.values()]
		
		#Create plot
		fig = plt.figure()
		width = .35
		ind = np.arange(len(geneplot.keys()))
		plt.bar(ind, freq)
		plt.xticks(ind + width, geneplot.keys())
		locs, labels = plt.xticks() 
		plt.setp(labels, rotation=90)
		plt.show()

		fig.savefig(figname)
		print("Saved bar plot as: "+figname)
开发者ID:cnellington,项目名称:Antibody-Statistics,代码行数:27,代码来源:annotationstats.py


示例5: plot_top_candidates

def plot_top_candidates(tweets, n, gop, save_to = None): 
  '''
  Plots the counts of top n candidate pair mentions given a Tweets class.
  Note: used for task 2.  
  ''' 
  counts = tweets.top_pairs(n, gop)

  pairs = [] 
  mentions = [] 
  for pair, ment in counts: 
    p = pair.split("|")
    c0 = CANDIDATE_NAMES[ p[0] ] 
    c1 = CANDIDATE_NAMES[ p[1] ]
    pairs.append(c0 + "\n" + c1)
    mentions.append(ment)

  

  fig = plt.figure(figsize = (FIGWIDTH, FIGHEIGHT)) 
  plt.bar(range(len(counts)), mentions)
  plt.xticks(range(len(counts)), pairs, rotation = 'vertical')

  if gop: 
    plt.title("Pairs of GOP Candidates Mentioned most Frequently together")
  else: 
    plt.title("Pairs of Candidates Mentioned most Frequently together")
  plt.xlabel("Number of Mentions")
  plt.ylabel("Number of Tweets")

  plt.show()
  if save_to: 
    fig.savefig(save_to)
开发者ID:karljiangster,项目名称:Python-Fun-Stuff,代码行数:32,代码来源:debate_tweets.py


示例6: freq_bar_clicked

 def freq_bar_clicked(self):
     if not self.current_patient:
         QtGui.QMessageBox.about(self, 'Error', 'Pick a Patient!')
     all_sessions = []
     freq_voltages = ''.join(self.freq_line_edit.text().split(' ')).split(',')
     freq_voltages = [float(v) for v in freq_voltages]
     print(self.current_patient.name)
     print(self.current_patient.sessions[0].freq_bc_scores, freq_voltages)
     if type(self.current_patient) == Patient:
         all_sessions = [s for s in self.current_patient.sessions if s.frequency_voltages == freq_voltages]
     else:
         for p in self.current_patient.patients:
             all_sessions += [s for s in p.sessions if s.frequency_voltages == freq_voltages]
     if not all_sessions:
         QtGui.QMessageBox.about(self, 'Error', 'No sessions that match these frequencies were found!')
     bc_counts = [0 for entry in freq_voltages]
     time_count = 0
     for s in all_sessions:
         time_count += s.time
         for i, perc in enumerate(s.freq_bc_scores):
             bc_counts[i] += perc * s.time
     bc_percentages = [(count/time_count) * 100 for count in bc_counts]
     plt.figure()
     plt.title('CONVERGENCE SCORE FOR DIFFERENT FREQUENCIES')
     plt.bar(range(len(freq_voltages)), bc_percentages)
     plt.show()
开发者ID:drpetecarr,项目名称:sweat-plot,代码行数:26,代码来源:main_gui.py


示例7: screeplot

    def screeplot(self, type="barplot", **kwargs):
        """
        Produce the scree plot
        :param type: type of plot. "barplot" and "lines" currently supported
        :param show: if False, the plot is not shown. matplotlib show method is blocking.
        :return: None
        """
        # check for matplotlib. exit if absent.
        try:
            imp.find_module('matplotlib')
            import matplotlib
            if 'server' in kwargs.keys() and kwargs['server']: matplotlib.use('Agg', warn=False)
            import matplotlib.pyplot as plt
        except ImportError:
            print "matplotlib is required for this function!"
            return

        variances = [s**2 for s in self._model_json['output']['importance'].cell_values[0][1:]]
        plt.xlabel('Components')
        plt.ylabel('Variances')
        plt.title('Scree Plot')
        plt.xticks(range(1,len(variances)+1))
        if type == "barplot": plt.bar(range(1,len(variances)+1), variances)
        elif type == "lines": plt.plot(range(1,len(variances)+1), variances, 'b--')
        if not ('server' in kwargs.keys() and kwargs['server']): plt.show()
开发者ID:madmax983,项目名称:h2o-3,代码行数:25,代码来源:dim_reduction.py


示例8: graph_startpos

def graph_startpos(startpos, gene_name):
    """
    Make a histogram of normally distributed random numbers and plot the
    analytic PDF over it
    """

    d = defaultdict(int)
    x = arange(-1, 4)
    print x
    for i in x:
        d[i] = 0

    for pos in startpos:
        d[pos+1] += 1
        

    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.bar(x, d.values())
    print d.values()
    plt.xticks( x + 0.5 ,  (" ", 0, 1, 2, " ") )

    ax.set_xlabel('Reading Frame')
    ax.set_ylabel('# Reads')
    fig.suptitle('Distribution of open reading frames', fontsize=14, fontweight='bold')
    if (gene_name != None):
        ax.set_title("Restricted to gene {0}".format(gene_name), fontsize=12)


    plt.show()
开发者ID:cswarth,项目名称:Morris-Lab,代码行数:30,代码来源:plot_orf_dist.py


示例9: plotPredictedOriginsTotals

def plotPredictedOriginsTotals(oemfileWT,oemfileMUT):

    # Get the total number of predicted origins for WT compared against confirmed, likely, dubious origins
    totalPOcomparedWT = oc.getnumComparedOriginsWTMUT(oemfileWT,2500)

    # Get the total number of predicted origins for MUT against confirmed, likely, dubious origins
    totalPOcomparedMUT = oc.getnumComparedOriginsWTMUT(oemfileMUT,2500)

    originsConfirmed = [totalPOcomparedWT['C'],totalPOcomparedMUT['C']]

    originsLikely = [totalPOcomparedWT['L'],totalPOcomparedMUT['L']]

    originsDubious = [totalPOcomparedWT['D'],totalPOcomparedMUT['D']]

    originsNone = [totalPOcomparedWT['N'],totalPOcomparedMUT['N']]

    ind = np.arange(2)    # the x locations for the groups
    width = 0.35       # the width of the bars: can also be len(x) sequence

    plt1 = plt.bar(ind, originsConfirmed,   width, color='g')
    plt2 = plt.bar(ind, originsLikely, width, color='y',bottom=originsConfirmed)
    plt3 = plt.bar(ind, originsDubious, width, color='r',bottom=[originsConfirmed[j]+originsLikely[j] for j in range(len(originsConfirmed))])
    plt4 = plt.bar(ind, originsNone, width, color='grey',bottom=[originsConfirmed[j]+originsLikely[j]+originsDubious[j] for j in range(len(originsConfirmed))])
    plt.xticks(ind+width/2., ('WT', 'KO'))
    plt.legend((plt1,plt2,plt3,plt4),('Confirmed','Likely','Dubious','None'),loc='upper center')
    plt.ylabel('Number of Origins')

    plt.show()
开发者ID:JayKu4418,项目名称:ForkConvergenceComparison,代码行数:28,代码来源:importantfunctions.py


示例10: draw_bar_plot

    def draw_bar_plot(self, dictlist, title, fid_x, fid_y1, fid_y2, fid_y3, y_min, y_max, legend1, legend2, legend3, outputfile, x_interval=1):
        ind = np.arange(len(dictlist))
        x_ray = self.get_x_from_dictlist(dictlist, fid_x, x_interval)
        y_1 = self.get_int_list_from_dictlist(dictlist, fid_y1)
        y_2 = self.get_int_list_from_dictlist(dictlist, fid_y2)
        y_3 = self.get_int_list_from_dictlist(dictlist, fid_y3)

        plt.cla()
        width = 0.35

        y_3_bottom = []
        for i in range(len(y_1)):
            y_3_bottom.append(y_1[i] + y_2[i])

        p1 = plt.bar(ind, y_1, width, color='r')
        p2 = plt.bar(ind, y_2, width, color='y', bottom=y_1)
        p3 = plt.bar(ind, y_3, width, color='g', bottom=y_3_bottom)

        self.autolabel(p1)
        self.autolabel(p2)
        self.autolabel(p3)

        plt.title(title + '\n')
        plt.xticks(ind+width/2., x_ray )
        plt.yticks(np.arange(0,y_max,20))
        plt.legend( (p1[0], p2[0], p3[0]), (legend1, legend2, legend3) )

        plt.grid(True)
        plt.savefig(outputfile)
开发者ID:siecj,项目名称:CAP,代码行数:29,代码来源:chartgenerator.py


示例11: draw_bar

def draw_bar(data):
    alg1 = []
    alg2 = []
    alg3 = []
    for item in data:
        if item['Alg3_Time'] != -1:
            alg1.append(item['Alg1_Time'])
            alg2.append(item['Alg2_Time'])
            alg3.append(item['Alg3_Time'])
    alg1 = np.array(alg1)
    alg2 = np.array(alg2)
    alg3 = np.array(alg3)
    add_index = range(len(k_index))
    p1 = plt.bar(add_index, alg1, width, color='r',align="center",)
    p2 = plt.bar(add_index, alg2, width, color='y',
                 bottom=alg1,align="center",)
    p3 = plt.bar(add_index, alg3, width, color='b',
                 bottom=alg1+alg2,align="center",)

    plt.ylabel('running time (seconds)')
    plt.xlabel('k')
    plt.title('Breakdown of computation time on NetHEPT')
    #plt.xticks((0,1,2),(u'ÄÐ',u'Å®','as'))
    plt.xticks(add_index,k_index)

    plt.legend((p1[0],p2[0],p3[0]), ('alg1', 'alg2','alg3'),loc=2)
    plt.savefig('Breakdown_computation_time')
    plt.close()
开发者ID:Lisahtm,项目名称:TIM,代码行数:28,代码来源:draw.py


示例12: plot_graph_distribution

def plot_graph_distribution(distribution, 
                            filename = "filename", 
                            title = "title", 
                            xlabel = "xlabel", 
                            ylabel = "ylabel") :
    plotx = []
    ploty = []

    for k in distribution :
        y = distribution[k]
        if k == 0 or y == 0 : continue 
#        plotx.append(math.log(k, 2))
#        ploty.append(math.log(y, 2))
        plotx.append(k)
        ploty.append(y)

    rects1 = plt.bar(index, means_men, bar_width,
                     alpha=opacity,
                     color='b',
                     yerr=std_men,
                     error_kw=error_config,
                     label='Men')

    plt.bar(plotx,ploty, 'ro')
    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.savefig(filename + '.png') 
开发者ID:einsteiner123,项目名称:programs,代码行数:28,代码来源:run.py


示例13: test_bbox_inches_tight

def test_bbox_inches_tight():
    #: Test that a figure saved using bbox_inches='tight' is clipped right
    rcParams.update(rcParamsDefault)

    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')
开发者ID:Alexandre-Ar,项目名称:matplotlib,代码行数:30,代码来源:test_bbox_tight.py


示例14: bar_plot

def bar_plot(hist_mod, tool, paths, save_to=None, figsize=(10, 10), fontsize=6):
    """
    Plots bar plot for selected tracks:

    :param figsize: Plot figure size
    :param save_to: Object for plots saving
    :param fontsize: Size of xlabels on plot
    """
    ind = np.arange(len(paths))

    result = []
    for path in paths:
        result.append((donor(path), Bed(path).count()))

    result = sorted(result, key=donor_order_id)
    result_columns = list(zip(*result))

    plt.figure(figsize=figsize)
    width = 0.35
    plt.bar(ind, result_columns[1], width, color='black')
    plt.ylabel('Peaks count', fontsize=fontsize)
    plt.xticks(ind, result_columns[0], rotation=90, fontsize=fontsize)
    plt.title(hist_mod + " " + tool, fontsize=fontsize)
    plt.tight_layout()
    save_plot(save_to)
开发者ID:olegs,项目名称:washu,代码行数:25,代码来源:peak_metrics.py


示例15: PlotGraph

def PlotGraph(wordcounts):
    
    #v=list(D.values())    
    print("Starting to plot a graph: ")
    plt.bar(range(len(wordcounts)), wordcounts.values(), align='center')
    plt.xticks(range(len(wordcounts)), list(wordcounts.keys()))
    plt.show()
开发者ID:ibininja,项目名称:Trending-Words-Retriever,代码行数:7,代码来源:plotgraph.py


示例16: plot_err_comp

def plot_err_comp():


    results = Control_results;

    fig, ax = plt.subplots()


    #results
    rects_train = plt.bar(ind,results['train_errs'], width,
                    color = 'b',
                    alpha = opacity,
                    yerr =results['train_errs_std'],
                    label = 'train');
    rects_test = plt.bar(ind+width,results['test_errs'], width,
                    color = 'r',
                    alpha = opacity,
                    yerr =results['test_errs_std'],
                    label = 'test');

    plt.xlabel('Datasets');
    plt.ylabel('Error(MSE)');
    plt.title('Performance (Error)')
    plt.xticks(ind+width, Datasets);
    plt.legend();

    #plot and save
    plt.tight_layout();
    plt.savefig('errs_comparison'+'.png');
    plt.show();
开发者ID:adamuas,项目名称:coevondm,代码行数:30,代码来源:analysis.py


示例17: normDistribution

	def normDistribution(self, list, bins):
		abs = map(np.linalg.norm, list)
		hist, bins = np.histogram(abs, bins = bins)
		width = 0.7 * (bins[1] - bins[0])
		center = (bins[:-1] + bins[1:]) / 2
		plt.bar(center, hist, align='center', width=width)
		plt.show()
开发者ID:MattWise,项目名称:1a-Analysis,代码行数:7,代码来源:Correctness.py


示例18: makePlot

def makePlot(
                k,
                counts,
                yaxis=[],
                width=0.8,
                figsize=[14.0,8.0],
                title="",
                ylabel='tmpylabel',
                xlabel='tmpxlabel',
                labels=[],
                show=False,
                grid=True,
                xticks=[],
                yticks=[],
                steps=5,
                save=False
            ):
    '''
    '''
    if not list(yaxis):
        yaxis = np.arange(len(counts))
    if not labels:
        labels = yaxis
    index = np.arange(len(yaxis))

    fig, ax = plt.subplots()
    fig.set_size_inches(figsize[0],figsize[1])
    plt.bar(index, counts, width)

    plt.title(title)
    if not xticks:
        print ('Making xticks')
        ticks = makeTicks(yMax=len(yaxis),steps=steps)
        xticks.append(ticks+width/2.)
        xticks.append(labels)
        print ('Done making xticks')

    if yticks:
        print ('Making yticks')
        # plt.yticks([1,2000],[0,100])
        plt.yticks(yticks[0],yticks[1])
        # ax.set_yticks(np.arange(0,100,10))
        print ('Done making yticks')

    plt.xticks(xticks[0]+width/2., xticks[1])
    plt.ylabel(ylabel)
    plt.xlabel(xlabel)
    # ax.set_xticks(range(0,len(counts)+2))

    fig.autofmt_xdate()
    # ax.set_xticklabels(ks)

    plt.axis([0, len(yaxis), 0, max(counts) + (max(counts)/100)])
    plt.grid(grid)
    location = ROOT_FOLDER + "/../muchBazar/src/image/" + k + "distribution.png"
    if save:
        plt.savefig(location)
        print ('Distribution written to: %s' % location)
    if show:
        plt.show()
开发者ID:mcmhav,项目名称:suchBazar,代码行数:60,代码来源:helpers.py


示例19: tagPicture

def tagPicture(mp):

    val = []
    label = []
    lst0 = mp.keys()
    #print lst0
    lst1 = mp.values()
    if len(lst1) > 10:
        num = 10
    else:
	num = len(lst1)
 
    while (num != 0):
        i = lst1.index(max(lst1))
	label.append(lst0[i])
	#print type(lst1[i])
	val.append(int(lst1[i]))
        lst0.pop(i)
        lst1.pop(i)
        num -= 1
		
    #print label
    pos = np.arange(len(val)) +.5
    plt.figure(1)
    plt.bar(pos,val,color='c',align='center')
    plt.xticks(pos,label)
    plt.ylabel(u'人数')
    string = u"热门标签"  
    plt.title(string)
    plt.show()
开发者ID:shch,项目名称:weibo,代码行数:30,代码来源:photo.py


示例20: main

def main( args ):

  hash = get_genes_with_features(args['file'])
  for key, featurearray in hash.iteritems():
    cluster, branch = key.split()
    length = int(featurearray[0][0])
    import matplotlib.pyplot as P
    x = [e+1 for e in range(length+1)]
    y1 = [0] * (length+1)
    y2 = [0] * (length+1)
    for feature in featurearray:
      length, pos, aa, prob = feature[0:4]
      if prob > 0.95: y1[pos] = prob
      else: y2[pos] = prob
    
    P.bar(x, y1, color='#000000', edgecolor='#000000')
    P.bar(x, y2, color='#bbbbbb', edgecolor='#bbbbbb')
    P.ylim(ymin=0, ymax=1)
    P.xlim(xmin=0, xmax=length)
    P.xlabel("position in the ungapped alignment [aa]")
    P.ylabel(r'$P (\omega > 1)$')
    P.title(cluster + " (branch " + branch + ")")

    P.axhline(y=.95, xmin=0, xmax=length, linestyle=":", color="k")
    P.savefig(cluster + "." + branch + ".png", format="png")
    P.close()
开发者ID:lierhan,项目名称:bioinformatics,代码行数:26,代码来源:plot-codeml-model-A-digest.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pyplot.barbs函数代码示例发布时间:2022-05-27
下一篇:
Python pyplot.axvspan函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap