本文整理汇总了Python中matplotlib.pyplot.tight_layout函数的典型用法代码示例。如果您正苦于以下问题:Python tight_layout函数的具体用法?Python tight_layout怎么用?Python tight_layout使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了tight_layout函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: chartProperties
def chartProperties(counter,path):
seen_properties = sorted(counter, key=lambda x: x[1],reverse=True)
seen_values_pct = map(itemgetter(1), tupleCounts2Percents(seen_properties))
seen_values_pct = ['{:.1%}'.format(item)for item in seen_values_pct]
plt.figure()
numberchart = plt.bar(range(len(seen_properties)), map(itemgetter(1), seen_properties), width=0.9,alpha=0.6)
plt.xticks(range(len(seen_properties)), map(itemgetter(0), seen_properties),rotation=90,ha='left')
plt.ylabel('Occurrences')
plot_margin = 1.15
x0, x1, y0, y1 = plt.axis()
plt.axis((x0,
x1,
y0,
y1*plot_margin))
plt.tick_params(axis='both', which='major', labelsize=8)
plt.tick_params(axis='both', which='minor', labelsize=8)
plt.tight_layout()
autolabel(numberchart,seen_values_pct)
plt.savefig(path)
plt.clf()
开发者ID:dhruvghulati,项目名称:ClaimDetection,代码行数:28,代码来源:charting.py
示例2: influence_plot
def influence_plot(X, y_true, y_pred, **kwargs):
"""Produces an influence plot.
Parameters
----------
X : array
Design matrix.
y_true : array_like
Observed labels, either 0 or 1.
y_pred : array_like
Predicted probabilities, floats on [0, 1].
Notes
-----
.. plot:: pyplots/influence_plot.py
"""
r = pearson_residuals(y_true, y_pred)
leverages = pregibon_leverages(X, y_pred)
delta_X2 = case_deltas(r, leverages)
dbetas = pregibon_dbetas(r, leverages)
plt.scatter(y_pred, delta_X2, s=dbetas * 800, **kwargs)
__, __, y1, y2 = plt.axis()
plt.axis((0, 1, y1, y2))
plt.xlabel('Predicted Probability')
plt.ylabel(r'$\Delta \chi^2$')
plt.tight_layout()
开发者ID:grivescorbett,项目名称:verhulst,代码行数:31,代码来源:plots.py
示例3: vis_detections
def vis_detections (im, class_name, dets, thresh=0.5):
"""Draw detected bounding boxes."""
inds = np.where(dets[:, -1] >= thresh)[0]
if len(inds) == 0:
return
im = im[:, :, (2, 1, 0)]
fig, ax = plt.subplots(figsize=(12, 12))
ax.imshow(im, aspect='equal')
for i in inds:
bbox = dets[i, :4]
score = dets[i, -1]
ax.add_patch(
plt.Rectangle((bbox[0], bbox[1]),
bbox[2] - bbox[0],
bbox[3] - bbox[1], fill=False,
edgecolor='red', linewidth=3.5)
)
ax.text(bbox[0], bbox[1] - 2,
'{:s} {:.3f}'.format(class_name, score),
bbox=dict(facecolor='blue', alpha=0.5),
fontsize=14, color='white')
ax.set_title(('{} detections with '
'p({} | box) >= {:.1f}').format(class_name, class_name,
thresh),
fontsize=14)
plt.axis('off')
plt.tight_layout()
plt.draw()
开发者ID:brentsony,项目名称:py-faster-rcnn,代码行数:31,代码来源:demo.py
示例4: plotall
def plotall(self):
real = self.z_data_raw.real
imag = self.z_data_raw.imag
real2 = self.z_data_sim.real
imag2 = self.z_data_sim.imag
fig = plt.figure(figsize=(15,5))
fig.canvas.set_window_title("Resonator fit")
plt.subplot(131)
plt.plot(real,imag,label='rawdata')
plt.plot(real2,imag2,label='fit')
plt.xlabel('Re(S21)')
plt.ylabel('Im(S21)')
plt.legend()
plt.subplot(132)
plt.plot(self.f_data*1e-9,np.absolute(self.z_data_raw),label='rawdata')
plt.plot(self.f_data*1e-9,np.absolute(self.z_data_sim),label='fit')
plt.xlabel('f (GHz)')
plt.ylabel('Amplitude')
plt.legend()
plt.subplot(133)
plt.plot(self.f_data*1e-9,np.unwrap(np.angle(self.z_data_raw)),label='rawdata')
plt.plot(self.f_data*1e-9,np.unwrap(np.angle(self.z_data_sim)),label='fit')
plt.xlabel('f (GHz)')
plt.ylabel('Phase')
plt.legend()
# plt.gcf().set_size_inches(15,5)
plt.tight_layout()
plt.show()
开发者ID:vdrhtc,项目名称:resonator_tools,代码行数:28,代码来源:utilities.py
示例5: plot_dpi_dpr_distribution
def plot_dpi_dpr_distribution(args, dpis, dprs, diagnoses):
print log.INFO, 'Plotting estimate distributions...'
diagnoses = np.array(diagnoses)
diagnoses[(0.25 <= diagnoses) & (diagnoses <= 0.75)] = 0.5
# Setup plot
fig, ax = plt.subplots()
pt.setup_axes(plt, ax)
biomarkers_str = args.method if args.biomarkers is None else ', '.join(args.biomarkers)
ax.set_title('DP estimation using {0} at {1}'.format(biomarkers_str, ', '.join(args.visits)))
ax.set_xlabel('DP')
ax.set_ylabel('DPR')
plt.scatter(dpis, dprs, c=diagnoses, edgecolor='none', s=25.0,
vmin=0.0, vmax=1.0, cmap=pt.progression_cmap,
alpha=0.5)
# Plot legend
# noinspection PyUnresolvedReferences
rects = [mpl.patches.Rectangle((0, 0), 1, 1, fc=pt.color_cn + (0.5,), linewidth=0),
mpl.patches.Rectangle((0, 0), 1, 1, fc=pt.color_mci + (0.5,), linewidth=0),
mpl.patches.Rectangle((0, 0), 1, 1, fc=pt.color_ad + (0.5,), linewidth=0)]
labels = ['CN', 'MCI', 'AD']
legend = ax.legend(rects, labels, fontsize=10, ncol=len(rects), loc='upper center', framealpha=0.9)
legend.get_frame().set_edgecolor((0.6, 0.6, 0.6))
# Draw or save the plot
plt.tight_layout()
if args.plot_file is not None:
plt.savefig(args.plot_file, transparent=True)
else:
plt.show()
plt.close(fig)
开发者ID:aschmiri,项目名称:DiseaseProgressionModel,代码行数:34,代码来源:estimate_progressions.py
示例6: plothist
def plothist():
n_groups = 3
means_men = (42.3113658071, 39.7803247373, 67.335243553)
std_men = (1, 2, 3)
fig, ax = plt.subplots()
index = np.array([0.5,1.5,2.5])
bar_width = 0.4
opacity = 0.4
error_config = {'ecolor': '0'}
rects1 = plt.bar(index, means_men, bar_width,
alpha=opacity,
color='b',
error_kw=error_config)
plt.xlabel('Approach')
plt.ylabel('Accuracy')
plt.axis((0,3.4,0,100))
plt.title('Evaluation')
plt.xticks(index + bar_width/2, ('Bing Liu', 'AFINN', 'SentiWordNet'))
plt.legend()
plt.tight_layout()
# plt.show()
plt.savefig('foo.png')
开发者ID:abhinavchanda,项目名称:mood_india,代码行数:30,代码来源:tester.py
示例7: peek
def peek(self, figsize=(15, 5)):
"""Quick-look summary plot."""
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=figsize)
self.plot_bias(ax=axes[0])
self.plot_matrix(ax=axes[1])
plt.tight_layout()
开发者ID:cdeil,项目名称:gammapy,代码行数:7,代码来源:energy_dispersion.py
示例8: plot_errsh
def plot_errsh():
results = Control_results;
fig, ax = plt.subplots()
#results
rects_train = plt.barh(ind,results['train_errs'], width,
color = 'b',
alpha = opacity,
xerr =results['train_errs_std']/np.sqrt(10),
label = '$train$');
rects_test = plt.barh(ind+width,results['test_errs'], width,
color = 'r',
alpha = opacity,
xerr =results['test_errs_std']/np.sqrt(10),
label = 'test');
plt.ylabel('Performance (Error)');
plt.title('Error (MSE)')
plt.yticks(ind+width, Datasets);
plt.legend();
#plot and save
plt.tight_layout();
plt.savefig('errs'+'.png');
plt.show();
开发者ID:adamuas,项目名称:coevondm,代码行数:30,代码来源:analysis.py
示例9: dend
def dend(X, notitles=False, metric="euclidean"):
"""Takes BoWs array creates linkage and dendrogram.
Args
----
X: ndarray
BoWs array
metric: String
Distance metric to use (default: "euclidean")
Returns
-------
Z: ndarray
Linkage array
dend: dict
dendrogram as a leaf and branch tree.
"""
Z = linkage(X, metric=metric)
plt.clf()
den = dendrogram(Z, labels=abbrev, orientation="left")
plt.title("Dendrogram of Antiquity Texts")
plt.xlabel("Distance between items")
plt.tight_layout()
if notitles:
name = "Dendrogram_notitles_{}.pdf".format(metric)
else:
name = "Dendrogram_{}.pdf".format(metric)
plt.savefig(name)
return Z, den
开发者ID:oew1v07,项目名称:hierarchical,代码行数:32,代码来源:analysis.py
示例10: 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
示例11: plot_errs
def plot_errs():
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']/np.sqrt(10),
## label = 'train');
rects_test = plt.boxplot(results['test_errs'],
labels =Datasets);
plt.ylabel('$Error(MSE)$');
plt.title('$Performance (Error) - With\ Injections$');
plt.xticks(ind+width, Datasets);
## plt.legend();
#plot and save
plt.tight_layout();
plt.savefig('errs_with_inject'+'.png');
plt.show();
开发者ID:adamuas,项目名称:coevondm,代码行数:27,代码来源:analysis.py
示例12: plot_main_seeds
def plot_main_seeds(self, qname, radio=False, checkbox=False,
numerical=False, array=False):
""" Plot the responses separately for each seed group in main_seeds. """
assert sum([radio, checkbox, numerical, array]) == 1
for seed in self.main_seeds:
responses_seed = self.filter_rows_by_seed(seed, self.responses)
responses_seed_question = self.filter_columns_by_name(qname, responses_seed)
plt.subplot(int("22" + str(self.main_seeds.index(seed))))
plt.title("Seed " + seed)
if radio:
self.plot_convergence_radio(qname, responses_seed_question)
elif checkbox:
self.plot_convergence_checkbox(responses_seed_question)
elif numerical:
self.plot_convergence_numerical(responses_seed_question)
elif array:
self.plot_array_boxes(qname, responses_seed_question)
qtext = self.get_qtext_from_qname(qname)
plt.suptitle(qtext)
plt.tight_layout()
plt.show()
开发者ID:acerato,项目名称:survey-scripts,代码行数:26,代码来源:Limeplot.py
示例13: 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
示例14: length_bar_plots
def length_bar_plots(tracks_paths, min_power, max_power, threads_num, save_to=None):
"""
Plots bar plot for each track - peaks count via peaks lengths:
:param tracks_paths: List of absolute track paths
:param min_power: used for left border of bar plot as a power for 10
:param max_power: used for right border of bar plot as a power for 10
:param threads_num: Threads number for parallel execution
:param save_to: Object for plots saving
"""
pool = multiprocessing.Pool(processes=threads_num)
bins = np.logspace(min_power, max_power, 80)
ordered_paths, ordered_lengths, track_max_bar_height = zip(*pool.map(functools.partial(
_calculate_lengths, bins=bins), tracks_paths))
max_bar_height = max(track_max_bar_height)
lengths = dict(zip(ordered_paths, ordered_lengths))
plt.figure()
for i, track_path in enumerate(tracks_paths):
ax = plt.subplot(330 + i % 9 + 1)
ax.hist(lengths[track_path], bins, histtype='bar')
ax.set_xscale('log')
ax.set_xlabel('Peaks length')
ax.set_ylabel('Peaks count')
ax.set_ylim([0, max_bar_height])
ax.set_title(donor(track_path) if is_od_or_yd(track_path) else Path(track_path).name)
if i % 9 == 8:
plt.tight_layout()
save_plot(save_to)
plt.figure()
plt.tight_layout()
save_plot(save_to)
开发者ID:olegs,项目名称:washu,代码行数:33,代码来源:peak_metrics.py
示例15: example
def example(show=True, save=False):
# Settings:
t0 = 0.
dt = .0001
dv = .0001
tf = .1
verbose = True
update_method = 'approx'
approx_order = 1
tol = 1e-14
# Run simulation:
simulation = get_simulation(dv=dv, verbose=verbose, update_method=update_method, approx_order=approx_order, tol=tol)
simulation.run(dt=dt, tf=tf, t0=t0)
# Visualize:
i1 = simulation.population_list[1]
plt.figure(figsize=(3,3))
plt.plot(i1.t_record, i1.firing_rate_record)
plt.xlim([0,tf])
plt.ylim(ymin=0)
plt.xlabel('Time (s)')
plt.ylabel('Firing Rate (Hz)')
plt.tight_layout()
if save == True: plt.savefig('./excitatory_inhibitory.png')
if show == True: plt.show()
return i1.t_record, i1.firing_rate_record
开发者ID:AllenInstitute,项目名称:dipde,代码行数:29,代码来源:excitatory_inhibitory.py
示例16: plot_raw_data
def plot_raw_data(ratings):
"""plot the statistics result on raw rating data."""
# do statistics.
num_items_per_user = np.array((ratings != 0).sum(axis=0)).flatten()
num_users_per_item = np.array((ratings != 0).sum(axis=1).T).flatten()
sorted_num_movies_per_user = np.sort(num_items_per_user)[::-1]
sorted_num_users_per_movie = np.sort(num_users_per_item)[::-1]
# plot
fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1)
ax1.plot(sorted_num_movies_per_user, color='blue')
ax1.set_xlabel("users")
ax1.set_ylabel("number of ratings (sorted)")
ax1.grid()
ax2 = fig.add_subplot(1, 2, 2)
ax2.plot(sorted_num_users_per_movie)
ax2.set_xlabel("items")
ax2.set_ylabel("number of ratings (sorted)")
ax2.set_xticks(np.arange(0, 2000, 300))
ax2.grid()
plt.tight_layout()
plt.savefig("stat_ratings")
plt.show()
# plt.close()
return num_items_per_user, num_users_per_item
开发者ID:epfml,项目名称:ML_course,代码行数:28,代码来源:plots.py
示例17: plot_flux
def plot_flux(f, q_left, q_right, plot_zero=True):
qvals = np.linspace(q_right, q_left, 200)
fvals = f(qvals)
dfdq = np.diff(fvals) / (qvals[1]-qvals[0]) # approximate df/dq
qmid = 0.5*(qvals[:-1] + qvals[1:]) # midpoints for plotting dfdq
#plt.figure(figsize=(12,4))
plt.subplot(131)
plt.plot(qvals,fvals)
plt.xlabel('q')
plt.ylabel('f(q)')
plt.title('flux function f(q)')
plt.subplot(132)
plt.plot(qmid, dfdq)
plt.xlabel('q')
plt.ylabel('df/dq')
plt.title('characteristic speed df/dq')
plt.subplot(133)
plt.plot(dfdq, qmid)
plt.xlabel('df/dq')
plt.ylabel('q')
plt.title('q vs. df/dq')
if plot_zero:
plt.plot([0,0],[qmid.min(), qmid.max()],'k--')
plt.subplots_adjust(left=0.)
plt.tight_layout()
开发者ID:maojrs,项目名称:riemann_book,代码行数:29,代码来源:nonconvex_demos.py
示例18: dist_small_multiples
def dist_small_multiples(df, figsize=(20, 20)):
"""
Small multiples plots of the distribution of a dataframe's variables.
"""
import math
sns.set_style("white")
num_plots = len(df.columns)
n = int(math.ceil(math.sqrt(num_plots)))
fig = plt.figure(figsize=figsize)
axes = [plt.subplot(n, n, i) for i in range(1, num_plots + 1)]
i = 0
for k, v in df.iteritems():
ax = axes[i]
sns.kdeplot(v, shade=True, ax=ax, legend=False)
sns.rugplot(v, ax=ax, c=sns.color_palette("husl", 3)[0])
[label.set_visible(False) for label in ax.get_yticklabels()]
ax.xaxis.set_ticks([v.min(), v.max()])
ax.set_title(k)
i += 1
sns.despine(left=True, trim=True, fig=fig)
plt.tight_layout()
return fig, axes
开发者ID:Gbemileke,项目名称:pyDEA,代码行数:26,代码来源:plot.py
示例19: plot_confusion_matrix
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
开发者ID:KenAhon,项目名称:own_data_cnn_implementation_keras,代码行数:32,代码来源:updated_custom_data_cnn.py
示例20: LEpdf
def LEpdf(xydata):
""" Plot pdf
NEEDS WORK
"""
## Read eta (yy), xHO (x1) points from file
yy,x1 = np.loadtxt(xydata,delimiter=" ",skiprows=1)[:,1:3].T
del xydata
## Construct a (normed) histogram of the data
nbins = [100,100]
H,xedges,yedges = np.histogram2d(x1,yy,bins=nbins,normed=True)
xpos = xedges[1:]-xedges[0]; ypos = yedges[1:]-yedges[0]
## Plot pdf
H = gaussian_filter(H, 3) ## Convolve with Gaussian
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3)
ax1.imshow(H, interpolation='nearest', origin='low')#,extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
ax1.set_xlabel("$x_{HO}$");ax1.set_ylabel("$\eta$")
ax2.contour(xpos,ypos,H,10)
ax2.set_xlabel("$x_{HO}$");ax2.set_ylabel("$\eta$")
ax3.hist2d(x1,yy, bins=100, normed=True)
ax3.set_xlabel("$x$");ax3.set_ylabel("$\eta$")
plt.tight_layout()
plt.show()
return
开发者ID:Allium,项目名称:ColouredNoise,代码行数:27,代码来源:LE_Plot.py
注:本文中的matplotlib.pyplot.tight_layout函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论