本文整理汇总了Python中matplotlib.pyplot.title函数的典型用法代码示例。如果您正苦于以下问题:Python title函数的具体用法?Python title怎么用?Python title使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了title函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: make_bar
def make_bar(
x,
y,
f_name,
title=None,
legend=None,
x_label=None,
y_label=None,
x_ticks=None,
y_ticks=None,
):
fig = plt.figure()
if title is not None:
plt.title(title, fontsize=16)
if x_label is not None:
plt.ylabel(x_label)
if y_label is not None:
plt.xlabel(y_label)
if x_ticks is not None:
plt.xticks(x, x_ticks)
if y_ticks is not None:
plt.yticks(y_ticks)
plt.bar(x, y, align="center")
if legend is not None:
plt.legend(legend)
plt.savefig(f_name)
plt.close(fig)
开发者ID:DongjunLee,项目名称:stalker-bot,代码行数:31,代码来源:plot.py
示例2: showOverlap
def showOverlap(mode, modes, *args, **kwargs):
"""Show overlap :func:`~matplotlib.pyplot.bar`.
:arg mode: a single mode/vector
:type mode: :class:`.Mode`, :class:`.Vector`
:arg modes: multiple modes
:type modes: :class:`.ModeSet`, :class:`.ANM`, :class:`.GNM`, :class:`.PCA`
"""
import matplotlib.pyplot as plt
if not isinstance(mode, (Mode, Vector)):
raise TypeError('mode must be Mode or Vector, not {0}'
.format(type(mode)))
if not isinstance(modes, (NMA, ModeSet)):
raise TypeError('modes must be NMA or ModeSet, not {0}'
.format(type(modes)))
overlap = abs(calcOverlap(mode, modes))
if isinstance(modes, NMA):
arange = np.arange(0.5, len(modes)+0.5)
else:
arange = modes.getIndices() + 0.5
show = plt.bar(arange, overlap, *args, **kwargs)
plt.title('Overlap with {0}'.format(str(mode)))
plt.xlabel('{0} mode index'.format(modes))
plt.ylabel('Overlap')
if SETTINGS['auto_show']:
showFigure()
return show
开发者ID:karolamik13,项目名称:ProDy,代码行数:28,代码来源:plotting.py
示例3: showNormDistFunct
def showNormDistFunct(model, coords, *args, **kwargs):
"""Show normalized distance fluctuation matrix using
:func:`~matplotlib.pyplot.imshow`. By default, *origin=lower*
keyword arguments are passed to this function,
but user can overwrite these parameters."""
import math
import matplotlib
import matplotlib.pyplot as plt
normdistfunct = model.getNormDistFluct(coords)
if not 'origin' in kwargs:
kwargs['origin'] = 'lower'
matplotlib.rcParams['font.size'] = '14'
fig = plt.figure(num=None, figsize=(10,8), dpi=100, facecolor='w')
show = plt.imshow(normdistfunct, *args, **kwargs), plt.colorbar()
plt.clim(math.floor(np.min(normdistfunct[np.nonzero(normdistfunct)])), \
round(np.amax(normdistfunct),1))
plt.title('Normalized Distance Fluctution Matrix')
plt.xlabel('Indices', fontsize='16')
plt.ylabel('Indices', fontsize='16')
if SETTINGS['auto_show']:
showFigure()
return show
开发者ID:karolamik13,项目名称:ProDy,代码行数:25,代码来源:plotting.py
示例4: plotResults
def plotResults(datasetName, sampleSizes, foldsSet, cvScalings, sampleMethods, fileNameSuffix):
"""
Plots the errors for a particular dataset on a bar graph.
"""
for k in range(len(sampleMethods)):
outfileName = outputDir + datasetName + sampleMethods[k] + fileNameSuffix + ".npz"
data = numpy.load(outfileName)
errors = data["arr_0"]
meanMeasures = numpy.mean(errors, 0)
for i in range(sampleSizes.shape[0]):
plt.figure(k*len(sampleMethods) + i)
plt.title("n="+str(sampleSizes[i]) + " " + sampleMethods[k])
for j in range(errors.shape[3]):
plt.plot(foldsSet, meanMeasures[i, :, j])
plt.xlabel("Folds")
plt.ylabel('Error')
labels = ["VFCV", "PenVF+"]
labels.extend(["VFP s=" + str(x) for x in cvScalings])
plt.legend(tuple(labels))
plt.show()
开发者ID:pierrebo,项目名称:wallhack,代码行数:25,代码来源:ProcessResults.py
示例5: show_plot
def show_plot(X, y, n_neighbors=10, h=0.2):
# Create color maps
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF','#FFAAAA', '#AAFFAA', '#AAAAFF','#FFAAAA', '#AAFFAA', '#AAAAFF','#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF','#FF0000','#FF0000','#FF0000','#FF0000','#FF0000','#FF0000','#FF0000',])
for weights in ['uniform', 'distance']:
# we create an instance of Neighbours Classifier and fit the data.
clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
clf.fit(X, y)
clf.n_neighbors = n_neighbors
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, x_max]x[y_min, y_max].
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("3-Class classification (k = %i, weights = '%s')"
% (n_neighbors, weights))
plt.show()
开发者ID:DistrictDataLabs,项目名称:yellowbrick,代码行数:32,代码来源:testing.py
示例6: plot_scenario
def plot_scenario(strategies, names, scenario_id=1):
probabilities = get_scenario(scenario_id)
plt.figure(figsize=(6, 4.5))
ax = plt.subplot(111)
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
plt.yticks(fontsize=14)
plt.xticks(fontsize=14)
plt.xlim((0, 1300))
# Remove the tick marks; they are unnecessary with the tick lines we just plotted.
plt.tick_params(axis="both", which="both", bottom="on", top="off",
labelbottom="on", left="off", right="off", labelleft="on")
for rank, (strategy, name) in enumerate(zip(strategies, names)):
plot_strategy(probabilities, strategy, name, rank)
plt.title("Bandits: " + str(probabilities), fontweight='bold')
plt.xlabel('Number of Trials', fontsize=14)
plt.ylabel('Cumulative Regret', fontsize=14)
plt.legend(names)
plt.show()
开发者ID:finartist,项目名称:CG1,代码行数:30,代码来源:plotbandits.py
示例7: default_run
def default_run(self):
"""
Plots the results, saves the figure, and finally displays it from simulating codewords with Sum-prod and Max-prod
algorithms across variance levels. This combines the results in one plot.
:return:
"""
if not os.path.exists("./graphs"):
os.makedirs("./graphs")
self.save_time = str(int(time.time()))
self.simulate(Decoder.SUM_PROD)
self.compute_error()
plt.plot([math.log10(x) for x in self.variance_levels], [math.log10(y) for y in self.bit_error_probability],
"ro-", label="Sum-Prod")
self.simulate(Decoder.MAX_PROD)
self.compute_error()
plt.plot([math.log10(x) for x in self.variance_levels], [math.log10(y) for y in self.bit_error_probability],
"g^--", label="Max-Prod")
plt.legend(loc=2)
plt.title("Hamming Decoder Factor Graph Simulation Results\n" +
r"$\log_{10}(\sigma^2)$ vs. $\log_{10}(P_e)$" + " for Max-Prod & Sum-Prod Algorithms\n" +
"Sample Size n = %(codewords)s Codewords \n Variance Levels = %(levels)s"
% {"codewords": str(self.iterations), "levels": str(self.variance_levels)})
plt.xlabel("$\log_{10}(\sigma^2)$")
plt.ylabel(r"$\log_{10}(P_e)$")
plt.savefig("graphs/%(time)s-max-prod-sum-prod-%(num_codewords)s-codewords-variance-bit_error_probability.png" %
{"time": self.save_time,
"num_codewords": str(self.iterations)}, bbox_inches="tight")
plt.show()
开发者ID:finnergizer,项目名称:hamming-decoder-factor-graph,代码行数:28,代码来源:simulator.py
示例8: visualize
def visualize(segmentation, expression, visualize=None, store=None, title=None, legend=False):
notes = []
onsets = []
values = []
param = ['Dynamics', 'Articulation', 'Tempo']
converter = NoteList()
converter.bpm = 100
if not visualize:
visualize = selectSubset(param)
for segment, expr in zip(segmentation, expression):
for note in segment:
onsets.append(converter.ticks_to_milliseconds(note.on)/1000.0)
values.append([expr[i] for i in visualize])
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12, 4))
for i in visualize:
plt.plot(onsets, [v[i] for v in values], label=param[i])
plt.ylabel('Deviation')
plt.xlabel('Score time (seconds)')
if legend:
plt.legend(bbox_to_anchor=(0., 1), loc=2, borderaxespad=0.)
if title:
plt.title(title)
#dplot = fig.add_subplot(111)
#sodplot = fig.add_subplot(111)
#dplot.plot([i for i in range(len(deltas[0]))], deltas[0])
#sodplot.plot([i for i in range(len(sodeltas[0]))], sodeltas[0])
if store:
fig.savefig('plots/{0}.png'.format(store))
else:
plt.show()
开发者ID:bjvanderweij,项目名称:expressivity,代码行数:32,代码来源:performancerenderer.py
示例9: display
def display(spectrum):
template = np.ones(len(spectrum))
#Get the plot ready and label the axes
pyp.plot(spectrum)
max_range = int(math.ceil(np.amax(spectrum) / standard_deviation))
for i in range(0, max_range):
pyp.plot(template * (mean + i * standard_deviation))
pyp.xlabel('Units?')
pyp.ylabel('Amps Squared')
pyp.title('Mean Normalized Power Spectrum')
if 'V' in Options:
pyp.show()
if 'v' in Options:
tokens = sys.argv[-1].split('.')
filename = tokens[0] + ".png"
input = ''
if os.path.isfile(filename):
input = input("Error: Plot file already exists! Overwrite? (y/n)\n")
while input != 'y' and input != 'n':
input = input("Please enter either \'y\' or \'n\'.\n")
if input == 'y':
pyp.savefig(filename)
else:
print("Plot not written.")
else:
pyp.savefig(filename)
开发者ID:seadsystem,项目名称:Backend,代码行数:27,代码来源:Analysis3.py
示例10: predicted_probabilities
def predicted_probabilities(y_true, y_pred, n_groups=30):
"""Plots the distribution of predicted probabilities.
Parameters
----------
y_true : array_like
Observed labels, either 0 or 1.
y_pred : array_like
Predicted probabilities, floats on [0, 1].
n_groups : int, optional
The number of groups to create. The default value is 30.
Notes
-----
.. plot:: pyplots/predicted_probabilities.py
"""
plt.hist(y_pred, n_groups)
plt.xlim([0, 1])
plt.xlabel('Predicted Probability')
plt.ylabel('Count')
title = 'Distribution of Predicted Probabilities (n = {})'
plt.title(title.format(len(y_pred)))
plt.tight_layout()
开发者ID:grivescorbett,项目名称:verhulst,代码行数:25,代码来源:plots.py
示例11: roc_plot
def roc_plot(y_true, y_pred):
"""Plots a receiver operating characteristic.
Parameters
----------
y_true : array_like
Observed labels, either 0 or 1.
y_pred : array_like
Predicted probabilities, floats on [0, 1].
Notes
-----
.. plot:: pyplots/roc_plot.py
References
----------
.. [1] Pedregosa, F. et al. "Scikit-learn: Machine Learning in Python."
*Journal of Machine Learning Research* 12 (2011): 2825–2830.
.. [2] scikit-learn developers. "Receiver operating characteristic (ROC)."
Last modified August 2013.
http://scikit-learn.org/stable/auto_examples/plot_roc.html.
"""
fpr, tpr, __ = roc_curve(y_true, y_pred)
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, label='ROC curve (area = {:0.2f})'.format(roc_auc))
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic')
plt.legend(loc='lower right')
开发者ID:grivescorbett,项目名称:verhulst,代码行数:33,代码来源:plots.py
示例12: ecdf_by_observed_label
def ecdf_by_observed_label(y_true, y_pred):
"""Plots the empirical cumulative density functions by observed label.
Parameters
----------
y_true : array_like
Observed labels, either 0 or 1.
y_pred : array_like
Predicted probabilities, floats on [0, 1].
Notes
-----
.. plot:: pyplots/ecdf_by_observed_label.py
"""
x = np.linspace(0, 1)
ecdf = ECDF(y_pred[y_true == 0])
y_0 = ecdf(x)
ecdf = ECDF(y_pred[y_true == 1])
y_1 = ecdf(x)
plt.step(x, y_0, label='Observed label 0')
plt.step(x, y_1, label='Observed label 1')
plt.xlabel('Predicted Probability')
plt.ylabel('Proportion')
plt.title('Empirical Cumulative Density Functions by Observed Label')
plt.legend(loc='lower right')
开发者ID:grivescorbett,项目名称:verhulst,代码行数:28,代码来源:plots.py
示例13: _plot
def _plot(self,names,title,style,when=0,showLegend=True):
if isinstance(names,str):
names = [names]
assert isinstance(names,list)
legend = []
for name in names:
assert isinstance(name,str)
legend.append(name)
# if it's a differential state
if name in self.xNames:
index = self.xNames.index(name)
ys = np.squeeze(self._log['x'])[:,index]
ts = np.arange(len(ys))*self.Ts
plt.plot(ts,ys,style)
if name in self.outputNames:
index = self.outputNames.index(name)
ys = np.squeeze(self._log['outputs'][name])
ts = np.arange(len(ys))*self.Ts
plt.plot(ts,ys,style)
if title is not None:
assert isinstance(title,str), "title must be a string"
plt.title(title)
plt.xlabel('time [s]')
if showLegend is True:
plt.legend(legend)
plt.grid()
开发者ID:jgillis,项目名称:rawesome,代码行数:30,代码来源:mpc_mhe_utils.py
示例14: make_line
def make_line(
x,
y,
f_name,
title=None,
legend=None,
x_label=None,
y_label=None,
x_ticks=None,
y_ticks=None,
):
fig = plt.figure()
if title is not None:
plt.title(title, fontsize=16)
if x_label is not None:
plt.ylabel(x_label)
if y_label is not None:
plt.xlabel(y_label)
if x_ticks is not None:
plt.xticks(x, x_ticks)
if y_ticks is not None:
plt.yticks(y_ticks)
if isinstance(y[0], list):
for data in y:
plt.plot(x, data)
else:
plt.plot(x, y)
if legend is not None:
plt.legend(legend)
plt.savefig(f_name)
plt.close(fig)
开发者ID:DongjunLee,项目名称:stalker-bot,代码行数:35,代码来源:plot.py
示例15: plot_precision_recall_n
def plot_precision_recall_n(y_true, y_scores, model_name):
'''
Takes the model, plots precision and recall curves
'''
precision_curve, recall_curve, pr_thresholds = precision_recall_curve(y_true, y_scores)
precision_curve = precision_curve[:-1]
recall_curve = recall_curve[:-1]
pct_above_per_thresh = []
number_scored = len(y_scores)
for value in pr_thresholds:
num_above_thresh = len(y_scores[y_scores >= value])
pct_above_thresh = num_above_thresh / float(number_scored)
pct_above_per_thresh.append(pct_above_thresh)
pct_above_per_thresh = np.array(pct_above_per_thresh)
plt.clf()
fig, ax1 = plt.subplots()
ax1.plot(pct_above_per_thresh, precision_curve, 'b')
ax1.set_xlabel('percent of population')
ax1.set_ylabel('precision', color='b')
ax2 = ax1.twinx()
ax2.plot(pct_above_per_thresh, recall_curve, 'r')
ax2.set_ylabel('recall', color='r')
name = model_name
plt.title(name)
plt.savefig("Eval/{}.png".format(name))
开发者ID:csking1,项目名称:world-bank-project,代码行数:28,代码来源:pipeline.py
示例16: plotISVar
def plotISVar():
plt.figure()
plt.title('Variance minimization problem (call).\nVertical lines mark the minima.')
for K in [0.6, 0.8, 1.0, 1.2]:
theta = np.linspace(-0.6, 2)
var = [BS.exactCallVar(K*s0, theta) for theta in theta]
minth = theta[np.argmin(var)]
line, = plt.plot(theta, var, label=str(K))
plt.axvline(minth, color=line.get_color())
plt.xlabel(r'$\theta$')
plt.ylabel('call variance')
plt.legend(title=r'$K/s_0$', loc='upper left')
plt.autoscale(tight=True)
plt.figure()
plt.title('Variance minimization problem (put).\nVertical lines mark the minima.')
for K in [0.8, 1.0, 1.2, 1.4]:
theta = np.linspace(-2, 0.5)
var = [BS.exactPutVar(K*s0, theta) for theta in theta]
minth = theta[np.argmin(var)]
line, = plt.plot(theta, var, label=str(K))
plt.axvline(minth, color=line.get_color())
plt.xlabel(r'$\theta$')
plt.ylabel('put variance')
plt.legend(title=r'$K/s_0$', loc='upper left')
plt.autoscale(tight=True)
开发者ID:alexschlueter,项目名称:ba,代码行数:28,代码来源:callput_plots.py
示例17: build_hist
def build_hist(self, coverage, show=False, save=False, save_fn="max_hist_plot"):
"""
Build a histogram to determine what the maxes look & visualize match_count
Might be used to determine a resonable threshold
@param coverage: the average coverage for an single nt
@param show: Show visualization with match maxes
@param save_fn: Save to disk with this file name or else it will be the default
@return: the histogram array
"""
#import matplotlib
#matplotlib.use("Agg")
import matplotlib.pyplot as plt
maxes = self.match_count.max(1) # get maxes along 1st dim
h = plt.hist(maxes, bins=self.match_count.shape[0]) # figure out where the majority
plt.ylabel("Frequency")
plt.xlabel("Count per index")
plt.title("Frequency count histogram")
if show: plt.show()
if save: plt.savefig(save_fn, dpi=160, frameon=False)
return h[0]
开发者ID:disa-mhembere,项目名称:Guided-Assembler,代码行数:27,代码来源:reference.py
示例18: zplane
def zplane(self, title="", fontsize=18):
""" Display filter in the complex plane
Parameters
----------
"""
rb = self.z
ra = self.p
t = np.arange(0, 2 * np.pi + 0.1, 0.1)
plt.plot(np.cos(t), np.sin(t), "k")
plt.plot(np.real(ra), np.imag(ra), "x", color="r")
plt.plot(np.real(rb), np.imag(rb), "o", color="b")
M1 = -10000
M2 = -10000
if len(ra) > 0:
M1 = np.max([np.abs(np.real(ra)), np.abs(np.imag(ra))])
if len(rb) > 0:
M2 = np.max([np.abs(np.real(rb)), np.abs(np.imag(rb))])
M = 1.6 * max(1.2, M1, M2)
plt.axis([-M, M, -0.7 * M, 0.7 * M])
plt.title(title, fontsize=fontsize)
plt.show()
开发者ID:tattoxcm,项目名称:pylayers,代码行数:25,代码来源:DF.py
示例19: run_test
def run_test(fld, seeds, plot2d=True, plot3d=True, add_title="",
view_kwargs=None, show=False, scatter_mpl=False, mesh_mvi=True):
interpolated_fld = viscid.interp_trilin(fld, seeds)
seed_name = seeds.__class__.__name__
if add_title:
seed_name += " " + add_title
try:
if not plot2d:
raise ImportError
from viscid.plot import vpyplot as vlt
from matplotlib import pyplot as plt
plt.clf()
# plt.plot(seeds.get_points()[2, :], fld)
mpl_plot_kwargs = dict()
if interpolated_fld.is_spherical():
mpl_plot_kwargs['hemisphere'] = 'north'
vlt.plot(interpolated_fld, **mpl_plot_kwargs)
plt.title(seed_name)
plt.savefig(next_plot_fname(__file__, series='2d'))
if show:
plt.show()
if scatter_mpl:
plt.clf()
vlt.plot2d_line(seeds.get_points(), fld, symdir='z', marker='o')
plt.savefig(next_plot_fname(__file__, series='2d'))
if show:
plt.show()
except ImportError:
pass
try:
if not plot3d:
raise ImportError
from viscid.plot import vlab
_ = get_mvi_fig(offscreen=not show)
try:
if mesh_mvi:
mesh = vlab.mesh_from_seeds(seeds, scalars=interpolated_fld)
mesh.actor.property.backface_culling = True
except RuntimeError:
pass
pts = seeds.get_points()
p = vlab.points3d(pts[0], pts[1], pts[2], interpolated_fld.flat_data,
scale_mode='none', scale_factor=0.02)
vlab.axes(p)
vlab.title(seed_name)
if view_kwargs:
vlab.view(**view_kwargs)
vlab.savefig(next_plot_fname(__file__, series='3d'))
if show:
vlab.show(stop=True)
except ImportError:
pass
开发者ID:KristoforMaynard,项目名称:Viscid,代码行数:60,代码来源:test_seed.py
示例20: plot_mpl_fig
def plot_mpl_fig():
rootdir = '/Users/catherinefielder/Documents/Research_Halos/HaloDetail'
cs = []
pops = []
for subdir, dirs, files in os.walk(rootdir):
head,tail = os.path.split(subdir)
haloname = tail
for file in files:
if file.endswith('_columnsadded'):
values = ascii.read(os.path.join(subdir, file), format = 'commented_header') #Get full path and access file
host_c = values[1]['host_c']
cs = np.append(cs, host_c)
pop = len(values['mvir(10)'])
pops = np.append(pops, pop)
print pop
plt.loglog(host_c, pop, alpha=0.8,label = haloname)
print "%s done. On to the next." %haloname
#plt.xscale('log')
#plt.yscale('log')
plt.xlabel('Host Concentration')
plt.ylabel('Nsat')
plt.title('Abundance vs. Host Concentration', ha='center')
#plt.legend(loc='best')
spearman = scipy.stats.spearmanr(cs, pops)
print spearman
开发者ID:cfielder,项目名称:DM_haloprops,代码行数:25,代码来源:abundance_vs_concentration.py
注:本文中的matplotlib.pyplot.title函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论