本文整理汇总了Python中matplotlib.pyplot.semilogx函数的典型用法代码示例。如果您正苦于以下问题:Python semilogx函数的具体用法?Python semilogx怎么用?Python semilogx使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了semilogx函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: comp_conv
def comp_conv(f,a,b,exact_value):
nmax = 100
x = np.arange(1.0, nmax, 1.0)
t = np.arange(1.0, nmax, 1.0)
u = np.arange(1.0, nmax, 1.0)
v = np.arange(1.0, nmax, 1.0)
w = np.arange(1.0, nmax, 1.0)
for i in np.arange(0.0,t.size):
t[i] = rect_meth(a,b,x[i],f)
for i in np.arange(0.0,u.size):
u[i] = simpson_meth(a,b,x[i],f)
for i in np.arange(0.0,v.size):
v[i] = midpoint_meth(a,b,x[i],f)
for i in np.arange(0.0,v.size):
w[i] = exact_value
mp.clf()
mp.semilogx()
mp.plot(x, t, linewidth=1.0, label='Rectangle')
mp.plot(x, u, linewidth=1.0, label='Simpson')
mp.plot(x, v, linewidth=1.0, label='Midpoint')
mp.plot(x, w, linewidth=1.0, label='Value of the integral')
mp.title("Illustration of the convergence of the three integration methods");
mp.xlabel('Number of subdivision points')
mp.ylabel('Integral of f between a and b')
mp.legend(loc='upper right')
mp.show()
示例2: plot_validation_curve
def plot_validation_curve(model, X, y, scorer, param_name, param_range=np.linspace(0.1, 1, 5), cv=None, n_jobs=5,
ylim=None, title="Xval. validation curve"):
''' Plot learning curve for model on data '''
df = pd.DataFrame()
df['param_range'] = param_range
train_scores, test_scores = validation_curve(model, X, y, param_name=param_name, param_range=param_range,
cv=cv, scoring=scorer, n_jobs=n_jobs)
df['train_mean'] = 1 - np.mean(train_scores, axis=1)
df['train_std'] = np.std(train_scores, axis=1)
df['test_mean'] = 1 - np.mean(test_scores, axis=1)
df['test_std'] = np.std(test_scores, axis=1)
plt.figure()
plt.title(title)
if ylim is not None:
plt.ylim(*ylim)
plt.xlabel("Parameter value")
plt.ylabel("Error (1-score)")
plt.grid()
plt.semilogx(param_range, df.train_mean, color="r", label="Training")
plt.fill_between(param_range, df.train_mean - df.train_std, df.train_mean + df.train_std, alpha=0.1, color="r")
plt.semilogx(param_range, df.test_mean, color="g", label="Test")
plt.fill_between(param_range, df.test_mean - df.test_std, df.test_mean + df.test_std, alpha=0.1, color="g")
plt.legend(loc="best")
plt.show()
return df, plt
示例3: demon
def demon(n, d, g, kgiven=0):
ks = np.arange(n + 1)
c1, c2 = [], []
for k in ks:
a = hyp2f1(1, n - k + 1, n + 2, 1 - d)
b = 0 if g == 0 else hyp2f1(1, n - k + 1, n + 2, 1 - d * g)
c1.append(a * d - b * d * g)
c2.append(a)
plt.plot(ks / n, c1, label='c1')
plt.plot(ks / n, c2, label='c2')
plt.xlabel('k / n')
plt.ylabel('Effective n / n')
plt.legend()
plt.figure()
S = [100 * generalised_entropy_gain(n, k, d, g) for k in ks]
plt.plot(ks / n, S, label='S')
plt.xlabel('k / n')
plt.ylabel('information gain')
plt.figure()
dif = np.logspace(-1, 1, 100)
S = [100 * generalised_entropy_gain(n, kgiven, d, g) for d in dif]
plt.semilogx(dif, S, label='S')
plt.xlabel('difficulty')
plt.ylabel('information gain')
示例4: main
def main():
edges = [30, 60, 120, 240]
corners = zip(edges[:-1], edges[1:])
centres = [(a + b) / 2 for a, b in corners]
#c = [get_linkwitz_riley_coeffs(1, b, a, edges[-1] * 2) for b, a in corners]
sr = 2000
c = [get_peak_coeffs(-24, i, sr, 1) for i in centres]
c.append([[1, 0, 0], [1, 0, 0]])
bm = [BiquadMemory(0, 0) for _ in c]
bc = [BiquadCoefficients(b0, b1, b2, a1, a2)
for [b0, b1, b2], [a0, a1, a2] in c]
c.append(series_coeffs(c))
# c.append(impedance_filter(c[-1]))
wh = [signal.freqz(b, a) for b, a in c]
plt.subplot(111)
plt.title("Frequency response - reflection filter")
for w, h in wh:
plt.semilogx(w, 20 * np.log10(np.abs(h)))
plt.ylabel('Amplitude Response (dB)')
plt.xlabel('Frequency (rad/sample)')
plt.grid()
plt.show()
示例5: plotPredictions
def plotPredictions(self):
plt.semilogx(self.freqs, self.sPLs, label = 'ISO target')
plt.semilogx(self.freqs, self.predictions, color = 'r',
linestyle = '--', label = 'Predicted')
plt.legend()
plt.show()
示例6: plot_containment_radii
def plot_containment_radii(fraction):
"""Plotting script for 68% and 95% containment radii."""
psf_gc = FermiGalacticCenter.psf()
gtpsf_table_gc = get_psf_table(psf_gc, 10000, 300000, 15)
psf_vela = FermiVelaRegion.psf()
gtpsf_table_vela = get_psf_table(psf_vela, 10000, 300000, 15)
if fraction == 68:
true_table_rep = load_lat_psf_performance('P7REP_SOURCE_V15_68')
true_table = load_lat_psf_performance('P7SOURCEV6_68')
rad = 'CONT_68'
elif fraction == 95:
true_table_rep = load_lat_psf_performance('P7REP_SOURCE_V15_95')
true_table = load_lat_psf_performance('P7SOURCEV6_95')
rad = 'CONT_95'
plt.plot(gtpsf_table_gc['ENERGY'], gtpsf_table_gc[rad],
color='red',label='Fermi Tools PSF @ Galactic Center')
plt.plot(gtpsf_table_vela['ENERGY'], gtpsf_table_vela[rad],
color='blue', label='Fermi Tools PSF @ Vela Region')
plt.plot(true_table_rep['energy'], true_table_rep['containment_angle'],
color='green', linestyle='--', label='P7REP_SOURCE_V15')
plt.plot(true_table['energy'], true_table['containment_angle'],
color='black', linestyle='--', label='P7SOURCEV6')
plt.xlim([10000, 300000])
plt.legend()
plt.semilogx()
plt.xlabel('Energy/MeV')
plt.ylabel('PSF Containment Radius/deg')
return plt
示例7: plotGroupXS
def plotGroupXS(group_xs, title='', filename=''):
global subdirectory
directory = pinspec.get_output_directory() + subdirectory
# Make directory if it does not exist
if not os.path.exists(directory):
os.makedirs(directory)
# Plot Resonance Integrals
fig = plt.figure()
bins = group_xs.bin_edges
plt.semilogx(bins[0:-1], group_xs.groupXS[:,:], drawstyle='steps-post')
plt.xlabel('Energy [eV]')
plt.ylabel('Group XS')
plt.grid()
if title is '':
plt.title('Group XS')
else:
plt.title(title.title() + ' Group XS')
if filename is '':
filename = directory + '/group-xs.png'
else:
filename = directory + filename.replace(' ', '-').lower() + \
'-group-xs.png'
plt.savefig(filename)
plt.close(fig)
示例8: plotValidationCurve
def plotValidationCurve(c, training_avgs, validation_avgs, model_name,
x_label = 'C'):
"""
This function plots the training and validation averages
Against the parameter we are trying to optimize
"""
plt.clf()
p1, = plt.plot(c, training_avgs, 'ro-', label = 'training')
p2, = plt.plot(c, validation_avgs, 'go-', label = 'validation')
plt.xlabel(x_label, fontsize = 16)
plt.ylabel('Score', fontsize = 16)
plt.title(model_name + ' Validation Curve',
fontdict = {'fontsize': 16})
plt.legend(loc = 0)
plt.semilogx()
# now save the figure
model_name = re.sub(r'\W', '_', model_name)
plt.savefig(model_name + '_validation.png',
format = 'png')
return None
示例9: plotDimensionsUpdateFrequencyEstimation
def plotDimensionsUpdateFrequencyEstimation(self, returnAxisValuesOnly=True):
'''
numberOfTimeUnits=10*24*12
Experts stream 12
Houston stream 2
'''
dataDistribution = defaultdict(list)
for line in FileIO.iterateJsonFromFile(self.dimensionsUpdateFrequencyFile):
for k, v in line[ParameterEstimation.dimensionsUpdateFrequencyId].iteritems():
k = int(k) / self.timeUnitInSeconds.seconds
if k not in dataDistribution: dataDistribution[k] = [0., 0.]
dataDistribution[k][0] += v; dataDistribution[k][1] += 1
x, y = [], []; [(x.append(k), y.append((dataDistribution[k][0] / dataDistribution[k][1]))) for k in sorted(dataDistribution)]
x1, y1 = [], []; [(x1.append(k), y1.append((dataDistribution[k][0] / dataDistribution[k][1]) / k)) for k in sorted(dataDistribution)]
x = x[:numberOfTimeUnits]; y = y[:numberOfTimeUnits]; x1 = x1[:numberOfTimeUnits]; y1 = y1[:numberOfTimeUnits]
def subPlot(id):
plt.subplot(id)
inactivityCorordinates = max(zip(x1, y1), key=itemgetter(1))
plt.semilogx(x1, y1, '-', color=self.stream_settings['plot_color'], label=getLatexForString(self.stream_settings['plot_label'] + ' (Update frequency=%d TU)' % inactivityCorordinates[0]), lw=2)
plt.subplot(id).yaxis.set_major_formatter(FuncFormatter(lambda x, i: '%0.1f' % (x / 10. ** 3)))
plt.semilogx([inactivityCorordinates[0]], [inactivityCorordinates[1]], 'o', alpha=0.7, color='r')
plt.subplot(id).yaxis.set_major_formatter(FuncFormatter(lambda x, i: '%0.1f' % (x / 10. ** 3)))
plt.yticks((min(y1), max(y1)))
print self.stream_settings['plot_label'], inactivityCorordinates[0]
plt.subplot(311)
plt.title(getLatexForString('Dimensions update frequency estimation'))
plt.semilogx(x, y, '-', color=self.stream_settings['plot_color'], label=getLatexForString(self.stream_settings['plot_label']), lw=2)
plt.subplot(311).yaxis.set_major_formatter(FuncFormatter(lambda x, i: '%0.1f' % (x / 10. ** 5)))
plt.text(0.0, 1.01, getLatexForString('10^5'), transform=plt.gca().transAxes)
plt.ylabel(getLatexForString('\# of decayed dimensions'))
if self.stream_settings['stream_id'] == 'experts_twitter_stream': subPlot(312)
else: subPlot(313); plt.xlabel(getLatexForString(xlabelTimeUnits))
plt.ylabel(getLatexForString('Rate of DD (10^3)'))
plt.legend(loc=3)
if returnAxisValuesOnly: plt.show()
示例10: Pl
def Pl(Outfile,line='-.',label=''):
dd=np.loadtxt(Outfile+'PS_DD')
dk=np.loadtxt(Outfile+'PS_DK')
kk=np.loadtxt(Outfile+'PS_KK')
halo=np.loadtxt('/home/mtx/data/tide/outdata/test/PS_haloDD')
#plt.figure('Power Spectrum')
#n=np.ones_like(kk[:,1])
#plt.loglog(dd[:,0],dd[:,1],'b.-',label='P_DD')
#plt.loglog(halo[:,0],halo[:,1],'m.-',label='P_halo')
#plt.loglog(dk[:,0],dk[:,1],'g.-',label='P_DK')
#plt.loglog(kk[:,0],kk[:,1],'r.-',label='P_KK')
#plt.loglog(kk[:,0],n*noise3,'k-.',alpha=0.8,label='noise')
#plt.title('Power Spectrum')
#plt.xlabel('k $(h/Mpc)$')
#plt.ylabel('P(k) $(Mpc^{3}/h^{3})$')
#plt.legend()
#plt.ylim(10**1,6*10**4)
#plt.xlim([9*10**-3,1])
##plt.savefig(name+'PS.eps')
plt.figure('correlation coefficient')
plt.title('correlation coefficient')
plt.semilogx(kk[:,0],dk[:,1]/np.sqrt(dd[:,1]*kk[:,1]),line,label=label)
plt.xlabel('k $(h/Mpc)$')
plt.ylabel('r')
示例11: plot_fft
def plot_fft(self, plotname=None, window='hann', normalise=True, **kwargs):
"""Make a plot (in the frequency domain) of all channels"""
ymin = kwargs.get('ymin', -160) #dB
freq, mag = self.fft(window=window, normalise=normalise)
fig_id = 1
plt.figure(fig_id)
#plt.semilogx(freq, mag, **kwargs) # plots all channel directly
plt.hold(True)
for ch in range(self.ch):
plt.semilogx(freq, mag[:,ch], label='ch%2i' %(ch+1))
plt.hold(False)
plt.xlim(xmin=1) # we're not interested in freqs. below 1 Hz
plt.ylim(ymin=ymin)
plt.xlabel('Frequency [Hz]')
plt.ylabel('Magnitude [dB]')
plt.legend(loc='best')
plt.grid(True)
if plotname is None:
plt.show()
else:
plt.savefig(plotname)
plt.close(fig_id)
示例12: make_plot
def make_plot():
def u(t):
return sym.exp(-a*t)
a, t, dt, p = sym.symbols('a t dt p')
dudt = sym.diff(u(t), t)
from numpy import logspace, exp
from matplotlib.pyplot import (
semilogx, legend, show, loglog, savefig)
# Map operator function name to logical names
operator2name = dict(
D_f='forward', D_b='backward', D_c='central')
legends = []
for operator in D_f, D_b, D_c:
E = operator(u, dt, t)/dudt
# Expand, set p=a*dt, simplify
E = sym.expand(E)
E = E.subs(a*dt, p)
E = sym.simplify(E)
print '%s E:' % operator2name[operator.__name__], E
print 'Taylor series:', E.series(p, 0, 3)
latex_expr = sym.latex(E)
E = sym.lambdify([p], E, modules='numpy')
p_values = logspace(-6, -0.5, 101)
y = E(p_values)
semilogx(p_values, y)
legends.append(operator2name[operator.__name__] +
': $' + latex_expr + '$')
legend(legends, loc='lower left')
savefig('tmp.png'); savefig('tmp.pdf')
show()
示例13: plotActiveFilters
def plotActiveFilters(self, colour='r'):
if self.initialized:
plt.semilogx(self.freqs, 10 *
np.log10(self.wActive + 1e-10), colour)
plt.xlabel('Frequency, Hz')
plt.ylabel('Response, dB')
plt.show()
示例14: test_frequency
def test_frequency(self):
import scipy.signal as ss
nsteps = 10000
dt = 0.1
t,w = self.regular_integrator.run(self.regular_w0, dt=dt, nsteps=nsteps)
f,fft = fft_orbit(t, w)
peak_ix = ss.find_peaks_cwt(fft[:,0], widths=np.linspace(dt*2, dt*100, 10))
print(peak_ix)
plt.clf()
plt.axvline(self.regular_par[1]/(2*np.pi), linewidth=3., alpha=0.35, color='b')
plt.axvline(1/(2*np.pi), linewidth=3., alpha=0.35, color='r')
plt.semilogx(f[:,0], fft[:,0], marker=None)
plt.savefig(os.path.join(plot_path,"pend_fft_regular.png"))
# ----------------------------------------------------------------------
t,w = self.chaotic_integrator.run(self.chaotic_w0, dt=dt, nsteps=nsteps)
f,fft = fft_orbit(t, w)
peak_ix = ss.find_peaks_cwt(fft[:,0], widths=np.linspace(dt*2, dt*100, 10))
print(peak_ix)
plt.clf()
plt.axvline(self.chaotic_par[1]/(2*np.pi), linewidth=3., alpha=0.35, color='b')
plt.axvline(1/(2*np.pi), linewidth=3., alpha=0.35, color='r')
plt.semilogx(f[:,0], fft[:,0], marker=None)
plt.savefig(os.path.join(plot_path,"pend_fft_chaotic.png"))
示例15: cmc
def cmc(cmc_scores, logx = True, **kwargs):
"""Plots the (cumulative) match characteristics curve and returns the maximum rank.
This function plots a CMC curve using the given CMC scores, which can be read from the our score files using the :py:func:`bob.measure.load.cmc_four_column` or :py:func:`bob.measure.load.cmc_five_column` methods.
The structure of the ``cmc_scores`` parameter is relatively complex.
It contains a list of pairs of lists.
For each probe object, a pair of list negative and positive scores is required.
**Parameters:**
``cmc_scores`` : [(array_like(1D, float), array_like(1D, float))]
See :py:func:`bob.measure.cmc`
``logx`` : bool
Plot the rank axis in logarithmic scale using :py:func:`matplotlib.pyplot.semilogx` or in linear scale using :py:func:`matplotlib.pyplot.plot`? (Default: ``True``)
``kwargs`` : keyword arguments
Extra plotting parameters, which are passed directly to :py:func:`matplotlib.pyplot.plot` or :py:func:`matplotlib.pyplot.semilogx`.
**Returns:**
The number of classes (clients) in the given scores.
"""
from matplotlib import pyplot
from . import cmc as calc
out = calc(cmc_scores)
if logx:
pyplot.semilogx(range(1, len(out)+1), out * 100, **kwargs)
else:
pyplot.plot(range(1, len(out)+1), out * 100, **kwargs)
return len(out)