本文整理汇总了Python中matplotlib.pyplot.bar函数的典型用法代码示例。如果您正苦于以下问题:Python bar函数的具体用法?Python bar怎么用?Python bar使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了bar函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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")
示例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()
示例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)
示例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)
示例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)
示例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()
示例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()
示例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()
示例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()
示例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)
示例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()
示例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')
示例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')
示例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)
示例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()