本文整理汇总了Python中matplotlib.pyplot.plot函数的典型用法代码示例。如果您正苦于以下问题:Python plot函数的具体用法?Python plot怎么用?Python plot使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了plot函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: 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
示例2: plot_predict_is
def plot_predict_is(self,h=5,**kwargs):
""" Plots forecasts with the estimated model against data
(Simulated prediction with data)
Parameters
----------
h : int (default : 5)
How many steps to forecast
Returns
----------
- Plot of the forecast against data
"""
figsize = kwargs.get('figsize',(10,7))
plt.figure(figsize=figsize)
date_index = self.index[-h:]
predictions = self.predict_is(h)
data = self.data[-h:]
t_params = self.transform_z()
plt.plot(date_index,np.abs(data-t_params[-1]),label='Data')
plt.plot(date_index,predictions,label='Predictions',c='black')
plt.title(self.data_name)
plt.legend(loc=2)
plt.show()
开发者ID:ekote,项目名称:pyflux,代码行数:28,代码来源:egarchmreg.py
示例3: showNormedSqFlucts
def showNormedSqFlucts(modes, *args, **kwargs):
"""Show normalized square fluctuations via :func:`~matplotlib.pyplot.plot`.
"""
import matplotlib.pyplot as plt
sqf = calcSqFlucts(modes)
args = list(args)
modesarg = []
i = 0
while i < len(args):
if isinstance(args[i], (VectorBase, ModeSet, NMA)):
modesarg.append(args.pop(i))
else:
i += 1
show = [plt.plot(sqf/(sqf**2).sum()**0.5, *args,
label='{0}'.format(str(modes)), **kwargs)]
plt.xlabel('Indices')
plt.ylabel('Square fluctuations')
for modes in modesarg:
sqf = calcSqFlucts(modes)
show.append(plt.plot(sqf/(sqf**2).sum()**0.5, *args,
label='{0}'.format(str(modes)), **kwargs))
if SETTINGS['auto_show']:
showFigure()
return show
开发者ID:karolamik13,项目名称:ProDy,代码行数:25,代码来源:plotting.py
示例4: plotAlphas
def plotAlphas(datasetNames, sampleSizes, foldsSet, cvScalings, sampleMethods, fileNameSuffix):
"""
Plot the variation in the error with alpha for penalisation.
"""
for i, datasetName in enumerate(datasetNames):
#plt.figure(i)
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)
foldInd = 4
for i in range(sampleSizes.shape[0]):
plt.plot(cvScalings, meanMeasures[i, foldInd, 2:8], next(linecycler), label="m="+str(sampleSizes[i]))
plt.xlabel("Alpha")
plt.ylabel('Error')
xmin, xmax = cvScalings[0], cvScalings[-1]
plt.xlim((xmin,xmax))
plt.legend(loc="upper left")
plt.show()
开发者ID:pierrebo,项目名称:wallhack,代码行数:28,代码来源:ProcessResults.py
示例5: draw_ranges_for_parameters
def draw_ranges_for_parameters(data, title='', save_path='./pictures/'):
parameters = data.columns.values.tolist()
# remove flight name parameter
for idx, parameter in enumerate(parameters):
if parameter == 'flight_name':
del parameters[idx]
flight_names = np.unique(data['flight_name'])
print len(flight_names)
for parameter in parameters:
plt.figure()
axis = plt.gca()
# ax.set_xticks(numpy.arange(0,1,0.1))
axis.set_yticks(flight_names)
axis.tick_params(labelright=True)
axis.set_ylim([94., 130.])
plt.grid()
plt.title(title)
plt.xlabel(parameter)
plt.ylabel('flight name')
colors = iter(cm.rainbow(np.linspace(0, 1,len(flight_names))))
for flight in flight_names:
temp = data[data.flight_name == flight][parameter]
plt.plot([np.min(temp), np.max(temp)], [flight, flight], c=next(colors), linewidth=2.0)
plt.savefig(save_path+title+'_'+parameter+'.jpg')
plt.close()
开发者ID:prikhodkop,项目名称:AnalysisWorkbench,代码行数:35,代码来源:data_utils_v2.py
示例6: 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
示例7: work
def work(self, **kwargs):
self.__dict__.update(kwargs)
self.worked = True
samples = LGMM1(rng=self.rng,
size=(self.n_samples,),
**self.LGMM1_kwargs)
samples = np.sort(samples)
edges = samples[::self.samples_per_bin]
centers = .5 * edges[:-1] + .5 * edges[1:]
print edges
pdf = np.exp(LGMM1_lpdf(centers, **self.LGMM1_kwargs))
dx = edges[1:] - edges[:-1]
y = 1 / dx / len(dx)
if self.show:
plt.scatter(centers, y)
plt.plot(centers, pdf)
plt.show()
err = (pdf - y) ** 2
print np.max(err)
print np.mean(err)
print np.median(err)
if not self.show:
assert np.max(err) < .1
assert np.mean(err) < .01
assert np.median(err) < .01
开发者ID:AshBT,项目名称:hyperopt,代码行数:27,代码来源:test_tpe.py
示例8: tuning
def tuning(x, y, err=None, smooth=None, ylabel=None, pal=None):
"""
Plot a tuning curve
"""
if smooth is not None:
xs, ys = smoothfit(x, y, smooth)
plt.plot(xs, ys, linewidth=4, color="black", zorder=1)
else:
ys = asarray([0])
if pal is None:
pal = sns.color_palette("husl", n_colors=len(x) + 6)
pal = pal[2 : 2 + len(x)][::-1]
plt.scatter(x, y, s=300, linewidth=0, color=pal, zorder=2)
if err is not None:
plt.errorbar(x, y, yerr=err, linestyle="None", ecolor="black", zorder=1)
plt.xlabel("Wall distance (mm)")
plt.ylabel(ylabel)
plt.xlim([-2.5, 32.5])
errTmp = err
errTmp[isnan(err)] = 0
rng = max([nanmax(ys), nanmax(y + errTmp)])
plt.ylim([0 - rng * 0.1, rng + rng * 0.1])
plt.yticks(linspace(0, rng, 3))
plt.xticks(range(0, 40, 10))
sns.despine()
return rng
开发者ID:speron,项目名称:sofroniew-vlasov-2015,代码行数:26,代码来源:plots.py
示例9: scatter
def scatter(x, y, equal=False, xlabel=None, ylabel=None, xinvert=False, yinvert=False):
"""
Plot a scatter with simple formatting options
"""
plt.scatter(x, y, 200, color=[0.3, 0.3, 0.3], edgecolors="white", linewidth=1, zorder=2)
sns.despine()
if xlabel:
plt.xlabel(xlabel)
if ylabel:
plt.ylabel(ylabel)
if equal:
plt.axes().set_aspect("equal")
plt.plot([0, max([x.max(), y.max()])], [0, max([x.max(), y.max()])], color=[0.6, 0.6, 0.6], zorder=1)
bmin = min([x.min(), y.min()])
bmax = max([x.max(), y.max()])
rng = abs(bmax - bmin)
plt.xlim([bmin - rng * 0.05, bmax + rng * 0.05])
plt.ylim([bmin - rng * 0.05, bmax + rng * 0.05])
else:
xrng = abs(x.max() - x.min())
yrng = abs(y.max() - y.min())
plt.xlim([x.min() - xrng * 0.05, x.max() + xrng * 0.05])
plt.ylim([y.min() - yrng * 0.05, y.max() + yrng * 0.05])
if xinvert:
plt.gca().invert_xaxis()
if yinvert:
plt.gca().invert_yaxis()
开发者ID:speron,项目名称:sofroniew-vlasov-2015,代码行数:27,代码来源:plots.py
示例10: LinRegTest
def LinRegTest(XTrain, YTrain, close, filename):
'''
Using RandomForest learner to predict how much the price will change in 5 days
@filename: the file's true name is ML4T-filename
@XTrain: the train data for feature
@YTrain: the train data for actual price after 5 days
@close: the actual close price of Test data set
@k: the number of trees in the forest
'''
XTest, YTest = TestGenerator(close)
#plot thge feature
plt.clf()
fig = plt.figure()
fig.suptitle('The value of features')
plt.plot(range(100), XTest[0:100, 0], 'b', label = 'One day price change')
plt.plot(range(100), XTest[0:100, 1], 'r', label = 'difference between two day price change')
plt.legend(loc = 4)
plt.ylabel('Price')
filename4 = 'feature' + filename + '.pdf'
fig.savefig(filename4, format = 'pdf')
LRL = LinRegLearner()
cof = LRL.addEvidence(XTrain, YTrain)
YLearn = LRL.query(XTest, cof)
return YLearn
开发者ID:cwss091,项目名称:Forecast_Project,代码行数:27,代码来源:forecaster.py
示例11: 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
示例12: graph
def graph(f, n, xmin, xmax, resolution=1001):
xlist = np.linspace(xmin, xmax, n)
ylist = f(xlist)
xlist_fine = np.linspace(xmin, xmax, resolution)
ylist_fine = p_L(xlist_fine, xlist, ylist)
plt.plot(xlist, ylist, 'ro')
plt.plot(xlist_fine, ylist_fine)
开发者ID:Annekfu,项目名称:python_primer,代码行数:7,代码来源:Lagrange_poly2.py
示例13: plot
def plot(self, nbins=100, range=None):
plt.plot([self.F_[0], self.F_[0]], [0, 100], '--r', lw=2)
h = plt.hist(self.F_, nbins, range)
plt.xlabel('F-value')
plt.ylabel('Count')
plt.grid()
return h
开发者ID:SherazKhan,项目名称:decoding-brain-challenge-2016,代码行数:7,代码来源:stats.py
示例14: draw_img_for_viewing_ice
def draw_img_for_viewing_ice(self):
#print "Press 'p' to save PNG."
global colmax
global colmin
fig = P.figure(num=None, figsize=(13.5, 5), dpi=100, facecolor='w', edgecolor='k')
cid1 = fig.canvas.mpl_connect('key_press_event', self.on_keypress_for_viewing)
cid2 = fig.canvas.mpl_connect('button_press_event', self.on_click)
canvas = fig.add_subplot(121)
canvas.set_title(self.filename)
self.axes = P.imshow(self.inarr, origin='lower', vmax = colmax, vmin = colmin)
self.colbar = P.colorbar(self.axes, pad=0.01)
self.orglims = self.axes.get_clim()
canvas = fig.add_subplot(122)
canvas.set_title("Angular Average")
maxAngAvg = (self.inangavg).max()
numQLabels = len(eDD.iceHInvAngQ.keys())+1
labelPosition = maxAngAvg/numQLabels
for i,j in eDD.iceHInvAngQ.iteritems():
P.axvline(j,0,colmax,color='r')
P.text(j,labelPosition,str(i), rotation="45")
labelPosition += maxAngAvg/numQLabels
P.plot(self.inangavgQ, self.inangavg)
P.xlabel("Q (A-1)")
P.ylabel("I(Q) (ADU/srad)")
pngtag = original_dir + "peakfit-gdvn_%s.png" % (self.filename)
P.savefig(pngtag)
print "%s saved." % (pngtag)
P.close()
开发者ID:sellberg,项目名称:iceFinderCampaign,代码行数:30,代码来源:compareAverageRuns-aerojet.py
示例15: plot
def plot():
elements_list = get_elements()
x = range(0, len(elements_list))
y = elements_list
print(x)
plt.plot(x, y)
plt.show()
开发者ID:manxshearwater-clockshift,项目名称:run-pyAudioAnalysis,代码行数:7,代码来源:AnalyzeNPY.py
示例16: draw_stat
def draw_stat(actual_price, action):
price_list = []
x_list = []
# idx = np.where(actual_price == 0)[0]
# print idx
# print actual_price[np.where(actual_price < 2000)]
# idx = [0] + idx.tolist()
# print idx
# for i in range(len(idx)-1):
# price_list.append(actual_price[idx[i]+1:idx[i+1]-1])
# x_list.append(range(idx[i]+i+1, idx[i+1]+i-1))
# for i in range(len(idx)-1):
# print x_list[i]
# print price_list[i]
# plt.plot(x_list[i], price_list[i], 'r')
x_list = range(1,50)
price_list = actual_price[1:50]
plt.plot(x_list, price_list, 'k')
for i in range(1, 50):
style = 'go'
if action[i] == 1:
style = 'ro'
plt.plot(i, actual_price[i], style)
plt.ylim(2140, 2144.2)
# plt.show()
plt.savefig("action.png")
开发者ID:Hunter-Lin,项目名称:HFT-Prediction,代码行数:26,代码来源:evaluate.py
示例17: compare_chebhist
def compare_chebhist(dname, mylambda, c, Nbin = 25):
if mylambda == 'Do not exist':
print('--!!Warning: eig file does not exist, can not display compare histgram')
else:
mylambda = 1 - mylambda
lmin = max(min(mylambda), -1)
lmax = min(max(mylambda), 1)
# print c
cheb_file_content = '\n'.join([str(st) for st in c])
x = np.linspace(lmin, lmax, Nbin + 1)
y = plot_chebint(c, x)
u = (x[1:] + x[:-1]) / 2
v = y[1:] - y[:-1]
plt.clf()
plt.hold(True)
plt.hist(mylambda,Nbin)
plt.plot(u, v, "r.", markersize=10)
plt.hold(False)
plt.show()
filename = 'data/' + dname + '.png'
plt.savefig(filename)
cheb_filename = 'data/' + dname + '.cheb'
f = open(cheb_filename, 'w+')
f.write(cheb_file_content)
f.close()
开发者ID:jz685,项目名称:MEngProj,代码行数:30,代码来源:compare_chebhist.py
示例18: test_get_obs
def test_get_obs(self):
plt.figure()
ant_sigs = antennas.antennas_signal(self.ants, self.ant_models, self.sources, self.rad.timebase)
rad_sig_full = self.rad.sampled_signal(ant_sigs[0, :], 0)
obs_full = self.rad.get_full_obs(ant_sigs, self.utc_date, self.config)
ant_sigs_simp = antennas.antennas_simplified_signal(self.ants, self.ant_models, self.sources, self.rad.baseband_timebase, self.rad.int_freq)
obs_simp = self.rad.get_simplified_obs(ant_sigs_simp, self.utc_date, self.config)
freqs, spec_full_before_obs = spectrum.plotSpectrum(rad_sig_full, self.rad.ref_freq, label='full_before_obs_obj', c='blue')
freqs, spec_full = spectrum.plotSpectrum(obs_full.get_antenna(1), self.rad.ref_freq, label='full', c='cyan')
freqs, spec_simp = spectrum.plotSpectrum(obs_simp.get_antenna(1), self.rad.ref_freq, label='simp', c='red')
plt.legend()
self.assertTrue((spec_full_before_obs == spec_full).all(), True)
plt.figure()
plt.plot(freqs, (spec_simp-spec_full)/spec_full)
plt.show()
print len(obs_full.get_antenna(1)), obs_full.get_antenna(1).mean()
print len(obs_simp.get_antenna(1)), obs_simp.get_antenna(1).mean()
开发者ID:trigrass2,项目名称:TART,代码行数:25,代码来源:test_radio.py
示例19: 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
示例20: 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
注:本文中的matplotlib.pyplot.plot函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论