本文整理汇总了Python中matplotlib.pyplot.margins函数的典型用法代码示例。如果您正苦于以下问题:Python margins函数的具体用法?Python margins怎么用?Python margins使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了margins函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_teh
def plot_teh(damage,title,subplot):
plt.subplot(subplot)
h5 = read_csv(5,damage)
h4 = read_csv(4,damage)
h3 = read_csv(3,damage)
h2 = read_csv(2,damage)
h1 = read_csv(1,damage)
xlist = [z for z in range(len(h5))]
ph5 = plt.plot(xlist,h5,'-o',label='h5',marker = 'v',markersize=8,color='blue')
ph4 = plt.plot(xlist,h4,'-o',label='h4',marker = 'o',markersize=8,color='green')
ph3 = plt.plot(xlist,h3,'-o',label='h3',marker = 'D',markersize=8,color='orange')
ph2 = plt.plot(xlist,h2,'-o',label='h2',marker = '*',markersize=8,color='red')
ph1 = plt.plot(xlist,h1,'-o',label='h1',marker = 's',markersize=8,color='black')
#plt.legend(loc='upper left', handlelength=5, borderpad=1.2, labelspacing=1.2)
#plt.legend()
plt.legend(loc='upper right', fontsize = 'xx-large')
plt.tick_params(axis='both',which='major', labelsize='large')
plt.title(title,size = 'xx-large',weight='bold')
plt.xlabel('Rank',size='xx-large',weight='bold')
plt.ylabel('Transfer Entropy',size='xx-large',weight='bold')
sns.axes_style("darkgrid", {"axes.facecolor": ".9"})
plt.ylim(ymin=0.0,ymax = 1.0)
plt.xlim(xmin=0.0,xmax = len(h5))
plt.margins(0.2)
plt.tight_layout(pad=2.5)
return
示例2: exercise_2a
def exercise_2a():
X, y = make_blobs(n_samples=1000,centers=50, n_features=2, random_state=0)
# plt.scatter(X[:, 0], X[:, 1], marker='o', c=y)
# plt.show()
kf = KFold(1000, n_folds=10, shuffle=False, random_state=None)
accuracy_lst = np.zeros([49, 2], dtype=float)
accuracy_current = np.zeros(10, dtype=float)
for k in range(1,50):
iterator = 0
clf = KNeighborsClassifier(n_neighbors=k)
for train_index, test_index in kf:
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
clf.fit(X_train, y_train)
accuracy_current[iterator] = (1. - clf.score(X_test,y_test))
iterator+=1
accuracy_lst[k-1, 0] = accuracy_current.mean()
# accuracy_lst[k-1, 1] = accuracy_current.std() #confidence interval 95%
x = np.arange(1,50, dtype=int)
plt.style.use('ggplot')
plt.plot(x, accuracy_lst[:, 0], '#009999', marker='o')
# plt.errorbar(x, accuracy_lst[:, 0], accuracy_lst[:, 1], linestyle='None', marker='^')
plt.xticks(x, x)
plt.margins(0.02)
plt.xlabel('K values')
plt.ylabel('Missclasification Error')
plt.show()
示例3: gen_graph
def gen_graph(kind, xvals, yvals, xlabel, ylabel):
if len(xvals) > 10:
xvals = xvals[:10]
if len(yvals) > 10:
yvals = yvals[:10]
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ind = np.arange(len(yvals))
if kind == 'line':
ax.plot(ind, yvals[::-1])
elif kind == 'bar':
ax.bar(ind, yvals[::-1])
plt.xticks(ind + .3 / 2, xvals[::-1])
plt.xlabel(xlabel, labelpad=20)
plt.ylabel(ylabel)
plt.margins(xmargin=0.05)
plt.xticks(range(0, len(xvals)))
plt.subplots_adjust(bottom=0.3, right=0.9)
ax.set_xticklabels(xvals[::-1], rotation=45)
io = StringIO()
fig.savefig(io, format='png')
graph = io.getvalue().encode('base64')
return graph
示例4: calculate_write_data_rate
def calculate_write_data_rate(loop_time):
f = open('create_rand_data.txt', 'a+');
block_size_list = [];
i = 128;
while i < (3*1024*1024):
block_size_list.append(i);
i = i*2;
fastest_block_index_count = len(block_size_list)*[0];
for j in range(loop_time):
#block_size_list = [100, 1000, 4000, 10000, 20000, 40000, 60000, 80000, 100000, 150000, 200000, 500000, 1000000, 2000000, 3000000]
data_rates = []
max_rate = 0;
max_block_index = 0;
file_size = 30*1024*1024; #30mb
for i in range(len(block_size_list)):
fname = "test" + str(i+1) + ".txt";
out = subprocess.check_output(["./create_random_file", fname, str(file_size), str(block_size_list[i])]);
data = out.split(":");
time_used = int(data[1].strip()[:-1]);
data_rate = (file_size / time_used);
data_rates.append(data_rate);
if data_rate > max_rate:
max_rate = data_rate;
max_block_index = i;
#print('writing' + str(i+1));
f.write('Block size:\n');
f.write(str(block_size_list)+'\n');
f.write('Data rate:\n');
f.write(str(data_rates)+'\n');
max_block_size = block_size_list[max_block_index];
single_info = "max rate: "+str(max_rate)+", "+"optimal_block_size: "+str(max_block_size)+"\n\n";
f.write(single_info);
plt.figure(j+1);
plt.plot(block_size_list, data_rates, linestyle='-', marker='o', color='b',linewidth=2.0);
plt.ylabel("data rate (b/ms)");
plt.xlabel("block size (b)");
label_text = "max:" + str(max_rate) + " " + "block:" + str(max_block_size);
plt.annotate(label_text, xy=(max_block_size, max_rate), xytext=(max_block_size+20000, max_rate+20000), arrowprops=dict(facecolor='black', shrink=0.05));
plt.ylim(0,200000);
plt.xscale('log');
plt.xticks(block_size_list);
plt.axes().get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter());
plt.axes().tick_params(axis='x', labelsize=13);
plt.xticks(rotation=30);
plt.margins(x=0);
save_fig_name = 'create_plot_' + str(j+1) + '.png';
plt.savefig(save_fig_name, bbox_inches="tight");
print(str(j+1)+"th iteration ends");
fastest_block_index_count[max_block_index] += 1;
max_count_index = 0;
optimal_index = 0;
for x in range(len(block_size_list)):
if fastest_block_index_count[x] > max_count_index:
max_count_index = fastest_block_index_count[x];
optimal_index = x;
f.write('OPTIMAL BLOCK SIZE: ' + str(block_size_list[optimal_index]));
f.close();
示例5: make_plot
def make_plot(counts):
"""
Plot the counts for the positive and negative words for each timestep.
Use plt.show() so that the plot will popup.
"""
positives=[]
negatives=[]
for i in counts:
for j in i:
if j[0]=="positive":
positives.append(j[1])
else:
negatives.append(j[1])
x_ticks=range(0,12)
lineP=plt.plot(positives)
plt.setp(lineP, color='b', marker='o', label="positive")
lineN=plt.plot(negatives)
plt.setp(lineN, color='g', marker='o', label="negative")
plt.margins(0.1)
plt.ylabel("Word count")
plt.xlabel("Time step")
plt.xticks(x_ticks)
plt.legend(loc=0)
plt.show()
示例6: on_epoch_end
def on_epoch_end(self, callback_data, model, epoch):
# convert to numpy arrays
data_batch = model.data_batch.get()
noise_batch = model.noise_batch.get()
# value transform
data_batch = self._value_transform(data_batch)
noise_batch = self._value_transform(noise_batch)
# shape transform
data_canvas = self._shape_transform(data_batch)
noise_canvas = self._shape_transform(noise_batch)
# plotting options
im_args = dict(interpolation="nearest", vmin=0., vmax=1.)
if self.nchan == 1:
im_args['cmap'] = plt.get_cmap("gray")
fname = self.filename+'_data_'+'{:03d}'.format(epoch)+'.png'
Image.fromarray(np.uint8(data_canvas*255)).convert('RGB').save(fname)
fname = self.filename+'_noise_'+'{:03d}'.format(epoch)+'.png'
Image.fromarray(np.uint8(noise_canvas*255)).convert('RGB').save(fname)
# plot logged WGAN costs if logged
if model.cost.costfunc.func == 'wasserstein':
giter = callback_data['gan/gen_iter'][:]
nonzeros = np.where(giter)
giter = giter[nonzeros]
cost_dis = callback_data['gan/cost_dis'][:][nonzeros]
w_dist = medfilt(np.array(-cost_dis, dtype='float64'), kernel_size=101)
plt.figure(figsize=(400/self.dpi, 300/self.dpi), dpi=self.dpi)
plt.plot(giter, -cost_dis, 'k-', lw=0.25)
plt.plot(giter, w_dist, 'r-', lw=2.)
plt.title(self.filename, fontsize=self.font_size)
plt.xlabel("Generator Iterations", fontsize=self.font_size)
plt.ylabel("Wasserstein estimate", fontsize=self.font_size)
plt.margins(0, 0, tight=True)
plt.savefig(self.filename+'_training.png', bbox_inches='tight')
plt.close()
示例7: plot_perfect_recall_rates_for_dg_weightings_no_err_bars
def plot_perfect_recall_rates_for_dg_weightings_no_err_bars(parsed_data, additional_plot_title):
set_size_buckets = Parser.get_dictionary_list_of_convergence_and_perfect_recall_for_dg_weightings(parsed_data)
# x, y_iters, std_iters, y_ratios, std_ratios
x = range(30)
results_2 = Parser.get_avg_convergence_for_x_and_set_size(2, set_size_buckets, x)
results_3 = Parser.get_avg_convergence_for_x_and_set_size(3, set_size_buckets, x)
results_4 = Parser.get_avg_convergence_for_x_and_set_size(4, set_size_buckets, x)
results_5 = Parser.get_avg_convergence_for_x_and_set_size(5, set_size_buckets, x)
plt.rcParams.update({'font.size': 25})
plt.ylabel('Convergence ratio')
plt.xlabel('Turnover rate')
plt.title('Average convergence rate by DG-weighting, ' + additional_plot_title)
p2 = plt.plot(results_2[0], results_2[3])
p3 = plt.plot(results_3[0], results_3[3])
p4 = plt.plot(results_4[0], results_4[3])
p5 = plt.plot(results_5[0], results_5[3])
plt.legend((p2[0], p3[0], p4[0], p5[0]), ('2x5', '3x5', '4x5', '5x5'))
# bbox_to_anchor=(1, 0.9), ncol=1, fancybox=True, shadow=True)
plt.grid(True)
plt.margins(0.01)
plt.yticks(np.arange(0, 1.1, .1))
plt.show()
示例8: draw_label
def draw_label(label, img, label_names, colormap=None):
plt.subplots_adjust(left=0, right=1, top=1, bottom=0,
wspace=0, hspace=0)
plt.margins(0, 0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
if colormap is None:
colormap = label_colormap(len(label_names))
label_viz = label2rgb(label, img, n_labels=len(label_names))
plt.imshow(label_viz)
plt.axis('off')
plt_handlers = []
plt_titles = []
for label_value, label_name in enumerate(label_names):
fc = colormap[label_value]
p = plt.Rectangle((0, 0), 1, 1, fc=fc)
plt_handlers.append(p)
plt_titles.append(label_name)
plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5)
f = io.BytesIO()
plt.savefig(f, bbox_inches='tight', pad_inches=0)
plt.cla()
plt.close()
out_size = (img.shape[1], img.shape[0])
out = PIL.Image.open(f).resize(out_size, PIL.Image.BILINEAR).convert('RGB')
out = np.asarray(out)
return out
示例9: plot_faces
def plot_faces(filename, args):
dset = gusto_dataset.GustoDataset(filename)
segments = dset.get_face_segments()
for seg in segments:
plt.plot(seg[:,0], seg[:,2], '-o', c='k')
plt.axis('equal')
plt.margins(0.1)
示例10: graph_TwoLines
def graph_TwoLines(aValues, bValues, l, labels, molecule, worksheet, augmented, yLabel, graphFolder, aLabel, bLabel):
#graph_HFandCCSDT
'''graphs CCSDT and HF on same axis'''
if worksheet==worksheetCharged:
chargeFolder=chargedFolder
if worksheet==worksheetNeutral:
chargeFolder=neutralFolder
if augmented==True:
augmentedFolder=augFolder
if augmented==False:
augmentedFolder=ccFolder
plt.plot(l, aValues, color=primaryColor, lw=2, ls='-', marker='s', label=molecule + aLabel)
plt.plot(l, bValues, color=secondaryColor, lw=2, ls='-', marker='o', label=molecule + bLabel)
plt.xticks(l, labels, rotation = '30', ha='right')
plt.margins(0.015, 0.05)
plt.subplots_adjust(bottom=0.2, top=0.85)
plt.ylabel(yLabel)
plt.legend(loc='upper center', bbox_to_anchor=(.5, 1.2), numpoints = 1, shadow=True, ncol=2)
plt.grid(True)
if not os.path.exists(path + '/ALL GRAPHS' + graphFolder +chargeFolder+augmentedFolder):
os.makedirs(path + '/ALL GRAPHS' + graphFolder +chargeFolder+augmentedFolder)
plt.savefig(path + '/ALL GRAPHS' + graphFolder +chargeFolder+augmentedFolder+ molecule + '.eps')
#plt.show()
plt.close()
示例11: generate
def generate(self, title=None):
max_duration = 0
for machine_nr in self.__tasks:
machine = self.__tasks[machine_nr]
for start_time in machine:
job_nr = machine[start_time]['job_nr']
duration = machine[start_time]['duration']
color = self.__colors[job_nr % len(self.__colors)]
plt.hlines(machine_nr, start_time, start_time + duration, colors=color, lw=50)
plt.text(start_time + 0.1, machine_nr + 0.1, str(job_nr), bbox=dict(facecolor='white', alpha=1.0)) #fontdict=dict(color='white'))
if duration + start_time > max_duration:
max_duration = duration + start_time
plt.margins(1)
if self.__n_machines is 0:
plt.axis([0, max_duration, 0.8, len(self.__tasks)])
else:
plt.axis([0, max_duration, -0.8, self.__n_machines])
plt.xticks(range(0, max_duration, 1))
if title:
plt.title(title)
plt.xlabel("Time")
plt.ylabel("Machines")
if self.__n_machines is 0:
plt.yticks(range(0, len(self.__tasks), 1))
else:
plt.yticks(range(0, self.__n_machines, 1))
self.__fig.savefig(self.__out_dir + sep + title + '.png')
示例12: graph_OneLine
def graph_OneLine(values, l, labels, molecule, worksheet, augmented, yLabel, graphFolder):
#graph_HF_CORR
#line graphs HF values and corr values
#s all graphs with just one line
if worksheet==worksheetCharged:
chargeFolder=chargedFolder
if worksheet==worksheetNeutral:
chargeFolder=neutralFolder
if augmented==True:
augmentedFolder=augFolder
if augmented==False:
augmentedFolder=ccFolder
plt.plot(l, values, color=primaryColor, lw=2, ls='-', marker='s', label=molecule)
plt.xticks(l, labels, rotation = '30', ha='right')
plt.margins(0.09, 0.09)
#y_formatter = plt.ticker.ScalarFormatter(useOffset=False)
#ax.yaxis.set_major_formatter(y_formatter)
plt.subplots_adjust(bottom=0.2, top=0.85)
plt.ylabel(yLabel)
plt.legend(loc='upper center', bbox_to_anchor=(.5, 1.2), numpoints = 1, shadow=True, ncol=3)
plt.grid(True)
if not os.path.exists(path + '/ALL GRAPHS' + graphFolder +chargeFolder+augmentedFolder):
os.makedirs(path + '/ALL GRAPHS' + graphFolder +chargeFolder+augmentedFolder)
plt.savefig(path + '/ALL GRAPHS' + graphFolder +chargeFolder+augmentedFolder+ molecule + '.eps')
plt.close()
示例13: stepplot
def stepplot(x, y, labels, plot_titles):
"""Generates Correlation Graph.
With the x,y coordinates, labels, and plot titles
established, the step-plots can be generated. Output
is PDF file format"""
plt.figure() #makes new image for each plot
#plot x & y stemplot. format plot points
plt.stem(x, y, linefmt='k--', markerfmt='ro', basefmt='k-')
#set x-axis labels and set them vertical. size 10 font.
plt.xticks(x, labels, rotation='vertical', fontsize = 10)
#set titles for graph and axes
plt.title(plot_titles[0])
plt.xlabel("Biomarkers")
plt.ylabel("Correlation Values")
# slightly move axis away from plot. prevents clipping the labels
plt.margins(0.2)
# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=0.15)
plt.tight_layout() #prevents labels from being clipped
with PdfPages(plot_titles[0]+'.pdf') as pdf: #creates new file for each figure
pdf.savefig()
示例14: _make_plot
def _make_plot(cls, title, depths, names, filename):
""" Create a PNG plot of the graph data
Args:
title: title of the plot
depths: Values to be graphed
names: Names of each of the bins being graphed
filename: Full path of the file for the resulting PNG
Returns:
None
Raises:
None
"""
plt.figure()
plt.title(title)
plt.xlabel('Graph Depth')
plt.ylabel('Count')
plt.margins(0.01)
plt.subplots_adjust(bottom=0.15)
plt.hist(depths, histtype='bar', label=names, bins=10)
plt.rc('legend', **{'fontsize': 8})
plt.legend(shadow=True, fancybox=True)
plt.savefig(filename, format='png')
示例15: main
def main():
options = _parse_args()
n_g = 3
n_h = 1
b_3 = 11 - 4/3 * n_g
b_2 = 22/3 - 4/3 * n_g - 1/6 * n_h
b_1 = - 4/3 * n_g - 1/10 * n_h
a_inv_1 = 58.98
a_inv_2 = 29.60
a_inv_3 = 8.47
q = np.logspace(4, 20, 10)
m_z = 91
a_inv_1_q = a_inv_1 + b_1 / (2 * np.pi) * np.log(q / m_z)
a_inv_2_q = a_inv_2 + b_2 / (2 * np.pi) * np.log(q / m_z)
a_inv_3_q = a_inv_3 + b_3 / (2 * np.pi) * np.log(q / m_z)
pl.plot(q, a_inv_1_q, label='U(1)')
pl.plot(q, a_inv_2_q, label='SU(2)')
pl.plot(q, a_inv_3_q, label='SU(3)')
pl.xscale('log')
pl.margins(0.05)
pl.savefig('running.pdf')
np.savetxt('running-1.txt', np.column_stack([q, a_inv_1_q]))
np.savetxt('running-2.txt', np.column_stack([q, a_inv_2_q]))
np.savetxt('running-3.txt', np.column_stack([q, a_inv_3_q]))