本文整理汇总了Python中pylab.boxplot函数的典型用法代码示例。如果您正苦于以下问题:Python boxplot函数的具体用法?Python boxplot怎么用?Python boxplot使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了boxplot函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: prob_dispersion
def prob_dispersion(target, result, prob, nclasses=5, save_as=''):
classprob = [[] for i in 2 * range(nclasses)]
for i in xrange(len(result)):
p = prob[i][result[i]]
if result[i] == target[i]:
classprob[2*result[i]].append(p)
else:
classprob[2*result[i] + 1].append(p)
xlabels = [[str(i+1) + "-Good", str(i+1) + "-Bad"] for i in range(nclasses)]
xlabels = reduce(list.__add__, xlabels, [])
# Plotting the result
fig = plt.figure()
fig.suptitle('Probability distribution' , fontsize=20)
plot = fig.add_subplot(111)
pylab.boxplot(classprob)
pylab.xticks(range(1, 2 * nclasses + 1), xlabels)
plot.set_xlabel('Predicted' , fontsize = 16)
plot.set_ylabel('Probabilities' , fontsize = 16)
plot.tick_params(axis='both', which='major', labelsize=14)
plot.tick_params(axis='both', which='minor', labelsize=8)
# Save options
if save_as =='':
plt.show()
else :
fig.savefig(save_as)
示例2: chart
def chart(SW, a, b, label, folder, FILE):
pylab.ioff()
fig_width_pt = 350 # Get this from LaTeX using \showthe\columnwidth
inches_per_pt = 1.0/72.27 # Convert pt to inch
golden_mean = ((5**0.5)-1.0)/2.0 # Aesthetic ratio
fig_width = fig_width_pt*inches_per_pt # width in inches
fig_height = fig_width*golden_mean # height in inches
fig_size = [fig_width,fig_height]
params = { 'backend': 'ps',
'axes.labelsize': 10,
'text.fontsize': 10,
'legend.fontsize': 10,
'xtick.labelsize': 8,
'ytick.labelsize': 8,
'text.usetex': True,
'figure.figsize': fig_size }
pylab.rcParams.update(params)
home = '/home/nealbob'
img_ext = '.pdf'
pylab.figure()
pylab.boxplot([SW['SWA'], SW['OA'], SW['NS']], whis=5)
pylab.axhline(y=1.0, color='0.5', linewidth=0.5, alpha=0.75, linestyle=':')
pylab.ylim(a, b)
pylab.ylabel(label)
pylab.tick_params(axis='x', which = 'both', labelbottom='off')
pylab.figtext(0.225, 0.06, 'SWA', fontsize = 10)
pylab.figtext(0.495, 0.06, 'OA', fontsize = 10)
pylab.figtext(0.76, 0.06, 'NS', fontsize = 10)
pylab.savefig(home + folder + FILE + img_ext)
pylab.show()
示例3: makeboxplot
def makeboxplot(filteredclusts, dblibrary, figname, pool=False):
'''takes a filtered dict of clusts worth keeping and creates a boxplot of either by lane (default) or pool'''
indiv_cluster_count = defaultdict(int)
for clust, inddict in filteredclusts.items():
for ind, reads in inddict.items():
if ind in indiv_cluster_count.keys():
indiv_cluster_count[ind]+=1
else:
indiv_cluster_count[ind]+=1
t = gdata_tools.get_table_as_dict(dblibrary)
db_ind_countd = Util.countdict([d['sampleid'] for d in t if d['sampleid'] in indiv_cluster_count.keys()[3]]) #creates a table of individual dicts from google spreadsheet
indiv_by_group = defaultdict(list)
for d in t:
if 'pool' in d:
indkey = (d.get('flowcell',None),d.get('lane',None),d.get('index',None),d.get('sampleid',None))
if indkey in indiv_cluster_count:
if pool == True:
indiv_by_group[(d['flowcell'],d['lane'],d.get('index',None),d['pool'])].append(indiv_cluster_count[indkey])
else:
indiv_by_group[(d['flowcell'],d['lane'],d.get('index',None))].append(indiv_cluster_count[indkey])
boxes = []
labels = []
for group,indcounts in indiv_by_group.items():
boxes.append(indcounts)
labels.append(group)
boxplt = pylab.figure(1)
pylab.boxplot(boxes)
pylab.xticks(arange(1,(len(labels)+1)),labels,fontsize='small') #legend with best location (0) if pools
boxplt.savefig(figname)
示例4: quartile_plot
def quartile_plot(
fits,
group_index_start, group_index_end,
model_param_index,
ylim=None,
log=True,
xlabel=None,
ylabel=None,
labels=None):
model_param_values = [
fit_params(fits, group_index, model_param_index)
for group_index in xrange(
group_index_start, group_index_end)
]
fig = plt.figure(figsize=(len(model_param_values), 7))
if log is True:
plt.yscale('log')
if ylim is not None:
plt.ylim(ylim)
if xlabel is not None:
plt.xlabel(xlabel)
if ylabel is not None:
plt.ylabel(ylabel)
plt.boxplot(
model_param_values,
labels=labels,
showmeans=True)
plt.grid()
plt.show()
示例5: chart
def chart(idx, a, b, label, FILE):
pylab.ioff()
fig_width_pt = 350 # Get this from LaTeX using \showthe\columnwidth
inches_per_pt = 1.0/72.27 # Convert pt to inch
golden_mean = ((5**0.5)-1.0)/2.0 # Aesthetic ratio
fig_width = fig_width_pt*inches_per_pt # width in inches
fig_height = fig_width*golden_mean # height in inches
fig_size = [fig_width*0.42,fig_height]
params = { 'backend': 'ps',
'axes.labelsize': 10,
'text.fontsize': 10,
'legend.fontsize': 10,
'xtick.labelsize': 8,
'ytick.labelsize': 8,
'text.usetex': True,
'figure.figsize': fig_size }
pylab.rcParams.update(params)
home = '/home/nealbob'
folder = '/Dropbox/Thesis/IMG/chapter3/'
img_ext = '.pdf'
pylab.figure()
pylab.boxplot(idx, whis=100)
pylab.ylim(a, b)
#pylab.ylabel(label)
pylab.tick_params(axis='x', which = 'both', labelbottom='off')
pylab.savefig(home + folder + FILE + img_ext)
pylab.show()
示例6: whiskers
def whiskers(i1, i2, lab1="", lab2=""):
width = 0.35
l1 = pb.boxplot([d[:, i1] for d in data] , positions=np.arange(len(data))-1.03*width/2., widths=width)
l2 = pb.boxplot([d[:, i2] for d in data] , positions=np.arange(len(data))+1.03*width/2., widths=width)
pb.xticks(np.arange(len(data)),[fn.split('raw')[0].replace('_',' ') for fn in fnames], rotation=45)
pb.xlim(-1.2*width, len(data)-1+1.2*width)
for key, lines in l1.iteritems():
pb.setp(lines, lw=1)
if key == "boxes":
pb.setp(lines, color='b', lw=1.4)
if key == 'whiskers':
pb.setp(lines, color='b')
if key == 'fliers':
pb.setp(lines, color='b')
if key == 'medians':
pb.setp(lines, color='k', lw=1.4)
for key, lines in l2.iteritems():
pb.setp(lines, lw=1.2)
if key == "boxes":
pb.setp(lines, color='g', lw=1.4)
if key == 'whiskers':
pb.setp(lines, color='g')
if key == 'fliers':
pb.setp(lines, color='g')
if key == 'medians':
pb.setp(lines, color='k', lw=1.4)
示例7: plot
def plot():
swarmsize_marks = [20, 50, 100, 200]
times = {}
for mark in swarmsize_marks:
times[mark] = []
for time_filename, size_filename, label, style in lines_to_plot:
time_file = open('parser_results/' + time_filename)
size_file = open('parser_results/' + size_filename)
for line in time_file:
time = float(line.split()[0])
size = int(size_file.next().split()[0])
for mark in swarmsize_marks:
if size <= mark:
times[mark].append(time)
break
xs = []
labels = []
for mark in swarmsize_marks:
xs.append(times[mark])
labels.append('<=%d' % mark)
pylab.boxplot(xs)
pylab.setp(pylab.gca(), 'xticklabels', labels)
pylab.savefig(output_filename)
# pylab.close()
print 'Output saved to:', output_filename
示例8: do_proc
def do_proc(resdir, timedir):
"""
EXPS on IPC6_SEQ_ELEVATORS_12 & IPC6_TEMPO_OPENSTACKS_17
steadyState=50
1) popsize=48 & runmax=1 & maxseconds=0
2) RESTART case: popsize=96 & runmax=0 & maxseconds=1799
foreach nthreads: 1, 24, 48
repeat 11 times
"""
if not options.cores: return
for field, popsize, runmax, maxseconds in [
("PROC", 48, 1, 0),
#("RESTART_PROC", 96, 0, 1799)
]:
for name, domain, instance in SAMPLES:
local_logger = logging.getLogger("GECCO2011.PROC.%s" % name)
plotdata = []
for num in range(1, options.nruns+1):
subdata = []
for nthreads in [1, 24, 48]:
field_name = "%s_%s_%d" % (field, "DYNAMIC" if options.dynamic else "STATIC", nthreads)
time_filename = PATTERN_TIME_FILENAME % {"TIMEDIR": timedir, "NAME": name, "FIELD": field_name, "NUM": num}
res_filename = PATTERN_RES_FILENAME % {"RESDIR": resdir, "NAME": name, "FIELD": field_name, "NUM": num}
plan_filename = PATTERN_PLAN_FILENAME % {"RESDIR": resdir, "NAME": name, "FIELD": field_name, "NUM": num}
cmd = PATTERN_CMD % {"DOMAIN": domain,
"INSTANCE": instance,
"LOOP": 1,
"DYNAMIC": 1 if options.dynamic else 0,
"THREADS": nthreads,
"RUNMAX": runmax,
"POPSIZE": popsize,
"OFFSPRINGS": popsize*7,
"MAXSECONDS": maxseconds,
"GENSTEADY": 50,
"TIME_FILENAME": time_filename,
"RES_FILENAME": res_filename,
"PLAN_FILENAME": plan_filename,
}
local_logger.debug(cmd)
if options.execute:
os.system( cmd )
if options.plot:
try:
f = open(time_filename).readlines()
t1 = float(f[1].split()[-1])
tp = f[4].split()[-1].split(':')
tp = float(int(tp[0]) * 60 + float(tp[1]))
subdata.append([t1, tp, t1 / tp])
except IOError:
pass
if options.plot:
if len(subdata):
plotdata.append(subdata)
if options.plot:
local_logger.info(plotdata)
pylab.boxplot( plotdata )
示例9: graphDepthComparison
def graphDepthComparison(benchType):
clf()
data = filter(table,
timestamp=range(1336921433, 1336922429+1),
benchType=benchType)
writeUnits = 160
xData = project(data, 'depth')
yData = project(data, 'latency')
print len(xData)
print len(yData)
# Each sample represents 5 trials.
yData = map(lambda x:x/5, yData)
(xData, yData) = condense(xData, yData)
pylab.boxplot(yData)
fmt = ticker.FixedFormatter(map(str, xData))
ax = gca()
ax.get_xaxis().set_major_formatter(fmt)
ax.set_ylabel("Sequential 4K block write latency (s)")
ax.set_xlabel("Depth (number of parent directories)")
ax.get_yaxis().grid(color='gray', linestyle='dashed')
ax.get_yaxis().set_major_locator(ticker.MaxNLocator(10))
title('Backend: DynamoDB; Provisioning Units = %d' % writeUnits)
pylab.ylim([0,0.1])
pylab.show()
示例10: graphPageSizeComparison
def graphPageSizeComparison(benchType, backend, writeUnits):
clf()
data = filter(table,
benchType=benchType,
backend=backend,
writeUnits=writeUnits)
xData = project(data, 'pageSize')
yData = project(data, 'latency')
# Each sample represents 10 trials.
yData = map(lambda x:x/10, yData)
(xData, yData) = condense(xData, yData)
pylab.boxplot(yData)
fmt = ticker.FixedFormatter(map(str, xData))
ax = gca()
ax.get_xaxis().set_major_formatter(fmt)
ax.set_ylabel("Sequential 4K block write latency (s)")
ax.set_xlabel("Page size (B)")
ax.get_yaxis().grid(color='gray', linestyle='dashed')
ax.get_yaxis().set_major_locator(ticker.MaxNLocator(15))
if backend == 's3':
title('Backend: S3')
else:
title('Backend: DynamoDB; Provisioning Units = %d' % writeUnits)
pylab.show()
示例11: plot_res_paper
def plot_res_paper(df):
"""
:param df: contain field classifier_name, accuarcy, and fold
:return:
"""
ticks = []
i = 0
data_to_plot = []
for g, v in df.groupby(df.classifier_name):
data_to_plot.append(v['accuracy'].values)
ticks.append(g)
print v
pylab.boxplot(data_to_plot)
pylab.xticks(range(1, 1+ len(data_to_plot)), ticks)
pylab.gca().invert_xaxis()
pylab.ylabel('Classification accuracy')
pylab.xlabel('Fold (cross validation fold for test)')
pylab.gca().yaxis.set_ticks(np.arange(0, 1, 0.1))
pylab.ylim((0,1))
pylab.legend()
pylab.show()
return
示例12: genderBoxplots
def genderBoxplots(self, women, men, labels, path):
data = [women.edition_count.values, men.edition_count.values]
plt.figure()
plt.boxplot(data)
# mark the mean
means = [np.mean(x) for x in data]
print(means)
plt.scatter(range(1, len(data) + 1), means, color="red", marker=">", s=20)
plt.ylabel("num editions")
plt.xticks(range(1, len(data) + 1), labels)
plt.savefig(
path + "/numeditions_gender_box_withOutlier" + self.pre + "-" + self.post + ".png", bbox_inches="tight"
)
plt.figure()
plt.boxplot(data, sym="")
# mark the mean
means = [np.mean(x) for x in data]
print(means)
plt.scatter(range(1, len(data) + 1), means, color="red", marker=">", s=20)
plt.ylabel("num editions")
plt.xticks(range(1, len(data) + 1), labels)
plt.savefig(path + "/numeditions_gender_box" + self.pre + "-" + self.post + ".png", bbox_inches="tight")
示例13: finalgen
def finalgen(names):
names = eval(names)
totaleff = []
for name in names:
resultsfolder = "results/"+name+"/"
final = resultsfolder + "gen049.dat"
population = []
name = final.rstrip('.dat')
efflist = []
resultsfile = open(final, 'r')
for line in resultsfile:
population.append(eval(line))
for indiv in population:
# if "fullrandom" in name:
# print "found", name
# lift = indiv['fitness'][0] - 0.5
# else:
lift = indiv['fitness'][0]
drag = 5.0 - indiv['fitness'][1]
efficiency = lift/drag
efflist.append(efficiency)
aveeff = ave(efflist)
stdeff = std(efflist,aveeff)
print "efficieny average", aveeff, "+-", stdeff
totaleff.append(efflist)
pylab.boxplot(totaleff)
pylab.show()
bwblift, bwbdrag = LIFT, 5 - DRAG
print "bwbefficiency", bwblift/bwbdrag
示例14: analyze
def analyze(real, samples, skip=0, thr=0.9):
real = pickle.load(open(real, 'rb'))
samples = pickle.load(open(samples, 'rb'))
thr=float(thr)
def flatten(measurements):
shared, exclusive = [], []
for es, ss in measurements:
exclusive.extend(es[skip:])
shared.extend(ss[skip:])
return exclusive, shared
true_values = OrderedDict()
for vm, measurements in real.results.items():
shared, exclusive = flatten(measurements)
true_values[vm] = mean(shared)/mean(exclusive)
print(true_values)
means = OrderedDict()
nums = []
avgms, avgdevs = [], []
#for vm, measurements in sorted(samples.results.items()):
for vm, measurements in sorted(samples.results.items()):
print("calculating", vm)
shared, exclusive = flatten(measurements)
def myfilter(l): return [e for e in l if e != 0]
shared = myfilter(shared)
exclusive = myfilter(exclusive)
ns = []
true = true_values[vm]
for _ in range(1000):
sh_samples, exc_samples = [], []
n = 0
while True:
n += 1
sh_samples.append(choice(shared))
exc_samples.append(choice(exclusive))
cur = mean(sh_samples)/mean(exc_samples)
prec = 1 - abs(1-cur/true)
if prec > thr:
ns.append(n)
break
if n > 20:
print(vm, "max precision:", prec)
break
if not ns:
print("no data points for", vm)
continue
nums.append(ns)
#m = mean(ns)
#d = pstdev(ns)
#rd = d/m*100
#avgdevs.append(rd)
#avgms.append(m)
#print("{vm}: {m:.1f} {rd:.1f}%".format(vm=vm, m=m,d=d,rd=rd))
#means[vm]=mean(nums)
ticks = real.mapping
p.xticks(range(len(ticks)), ticks)
p.boxplot(nums)
示例15: main
def main():
# exon, intron, unknown
specific = [[], [], []]
nonspecific = [[], [], []]
foldspecific = [[], [], []]
foldnonspecific = [[], [], []]
for prefix in sys.argv[1:]:
tempexonic, tempspecific, tempnonspecific, tempfoldspecific, tempfoldnonspecific, templength = getData(
prefix + ".exonic.overlap.out.annotation.txt", ["exon"]
)
exonic = tempexonic[0]
exoniclength = templength[0]
specific[0].append(tempspecific[0])
nonspecific[0].append(tempnonspecific[0])
foldspecific[0].append(tempfoldspecific[0])
foldnonspecific[0].append(tempfoldnonspecific[0])
tempData, tempspecific, tempnonspecific, tempfoldspecific, tempfoldnonspecific, templength = getData(
prefix + ".novel.overlap.out.annotation.txt", ["intron", "unknown"]
)
intronic = tempData[0]
unknown = tempData[1]
introniclength = templength[0]
unknownlength = templength[1]
specific[1].append(tempspecific[0])
specific[2].append(tempspecific[1])
nonspecific[1].append(tempnonspecific[0])
nonspecific[2].append(tempnonspecific[1])
foldspecific[1].append(tempfoldspecific[0])
foldspecific[2].append(tempfoldspecific[1])
foldnonspecific[1].append(tempfoldnonspecific[0])
foldnonspecific[2].append(tempfoldnonspecific[1])
plotData = [exonic, intronic, unknown]
print prefix
print "exonic: ", len(exonic)
print "intronic: ", len(intronic)
print "unknown: ", len(unknown)
fig = pl.figure()
pl.boxplot(plotData)
pl.ylim([2, 15])
pl.ylabel("Log Expression Level")
pl.xticks([1, 2, 3], ["Exonic", "Intronic", "Unknown"])
pl.title(prefix.replace("_fsorted", "").replace("_", " "))
fig.savefig(prefix + ".expression.png", dpi=fig.dpi)
fig = pl.figure()
pl.boxplot([exoniclength, introniclength, unknownlength])
pl.ylim([60, 2500])
pl.ylabel("Transcript Length")
pl.xticks([1, 2, 3], ["Exonic", "Intronic", "Unknown"])
pl.title(prefix.replace("_fsorted", "").replace("_", " "))
fig.savefig(prefix + ".length.png", dpi=fig.dpi)
# pl.show()
abbr = []
for i in sys.argv[1:]:
tokens = i.split("_")
abbr.append(tokens[0][0].upper() + tokens[1][0:2].title())
plotSpec(specific, nonspecific, abbr, ["exonic", "intronic", "unknown"], "abs")
plotSpec(foldspecific, foldnonspecific, abbr, ["exonic", "intronic", "unknown"], "fold")