本文整理汇总了Python中matplotlib.pyplot.xlim函数的典型用法代码示例。如果您正苦于以下问题:Python xlim函数的具体用法?Python xlim怎么用?Python xlim使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了xlim函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: exec_transmissions
def exec_transmissions():
IP,IP_AP,files=parser_reduce()
plt.figure("GRAPHE_D'EVOLUTION_DES_TRANSMISSIONS")
ENS_TEMPS_, TRANSMISSION_ = transmissions(files)
plt.plot(ENS_TEMPS_, TRANSMISSION_,"r.", label="Transmissions: ")
lot = map(inet_aton, IP)
lot.sort()
iplist1 = map(inet_ntoa, lot)
for i in iplist1: #ici j'affiche les annotations et vérifie si j'ai des @ip de longueur 9 ou 8 pour connaitre la taille de la fenetre du graphe
if len(i)==9:
maxim_=i[-2:] #Sera utilisé pour la taille de la fenetre du graphe
plt.annotate(' Machine: '+ i ,horizontalalignment='left', xy=(1, float(i[-2:])), xytext=(1, float(i[-2:])-0.4),arrowprops=dict(facecolor='black', shrink=0.05),)
else:
maxim_=i[-1:] #Sera utilisé pour la taille de la fenetre du graphe
plt.annotate(' Machine: '+ i ,horizontalalignment='left', xy=(1, float(i[7])), xytext=(1, float(i[7])-0.4),arrowprops=dict(facecolor='black', shrink=0.05),)
for i in IP_AP: #ACCESS POINT ( cas spécial )
if i[-2:]:
plt.annotate(' access point: '+ i , xy=(1, i[7]), xytext=(1, float(i[7])-0.4),arrowprops=dict(facecolor='black', shrink=0.05),)
plt.ylim(0, (float(maxim_))+1) #C'est à ça que sert le tri
plt.xlim(1, 1.1)
plt.legend(loc='best',prop={'size':10})
plt.xlabel('Temps (s)')
plt.ylabel('IP machines transmettrices')
plt.grid(True)
plt.title("GRAPHE_D'EVOLUTION_DES_TRANSMISSIONS")
plt.legend(loc='best')
plt.show()
示例2: 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()
示例3: scree_plot
def scree_plot(pca_obj, fname=None):
'''
Scree plot for variance & cumulative variance by component from PCA.
Arguments:
- pca_obj: a fitted sklearn PCA instance
- fname: path to write plot to file
Output:
- scree plot
'''
components = pca_obj.n_components_
variance = pca.explained_variance_ratio_
plt.figure()
plt.plot(np.arange(1, components + 1), np.cumsum(variance), label='Cumulative Variance')
plt.plot(np.arange(1, components + 1), variance, label='Variance')
plt.xlim([0.8, components]); plt.ylim([0.0, 1.01])
plt.xlabel('No. Components', labelpad=11); plt.ylabel('Variance Explained', labelpad=11)
plt.legend(loc='best')
plt.tight_layout()
if fname is not None:
plt.savefig(fname)
plt.close()
else:
plt.show()
return
示例4: 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
示例5: draw
def draw(data, classes, model, resolution=100):
mycm = mpl.cm.get_cmap('Paired')
one_min, one_max = data[:, 0].min()-0.1, data[:, 0].max()+0.1
two_min, two_max = data[:, 1].min()-0.1, data[:, 1].max()+0.1
xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
np.arange(two_min, two_max, (two_max-two_min)/resolution))
inputs = np.c_[xx1.ravel(), xx2.ravel()]
z = []
for i in range(len(inputs)):
z.append(predict(model, inputs[i])[0])
result = np.array(z).reshape(xx1.shape)
plt.contourf(xx1, xx2, result, cmap=mycm)
plt.scatter(data[:, 0], data[:, 1], s=50, c=classes, cmap=mycm)
t = np.zeros(15)
for i in range(15):
if i < 5:
t[i] = 0
elif i < 10:
t[i] = 1
else:
t[i] = 2
plt.scatter(model[:, 0], model[:, 1], s=150, c=t, cmap=mycm)
plt.xlim([0, 10])
plt.ylim([0, 10])
plt.show()
示例6: plot_wav_fft
def plot_wav_fft(wav_filename, desc=None):
plt.clf()
plt.figure(num=None, figsize=(6, 4))
sample_rate, X = scipy.io.wavfile.read(wav_filename)
spectrum = np.fft.fft(X)
freq = np.fft.fftfreq(len(X), 1.0 / sample_rate)
plt.subplot(211)
num_samples = 200.0
plt.xlim(0, num_samples / sample_rate)
plt.xlabel("time [s]")
plt.title(desc or wav_filename)
plt.plot(np.arange(num_samples) / sample_rate, X[:num_samples])
plt.grid(True)
plt.subplot(212)
plt.xlim(0, 5000)
plt.xlabel("frequency [Hz]")
plt.xticks(np.arange(5) * 1000)
if desc:
desc = desc.strip()
fft_desc = desc[0].lower() + desc[1:]
else:
fft_desc = wav_filename
plt.title("FFT of %s" % fft_desc)
plt.plot(freq, abs(spectrum), linewidth=5)
plt.grid(True)
plt.tight_layout()
rel_filename = os.path.split(wav_filename)[1]
plt.savefig("%s_wav_fft.png" % os.path.splitext(rel_filename)[0],
bbox_inches='tight')
示例7: 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')
示例8: plot_dens_par_comp_single_obs
def plot_dens_par_comp_single_obs(obs, pars, comps, ax = None, legend = False, loc = 2, vline = None, xlim = None):
"""Density plot of results from both partitions and compositions with value from a single observation.
"""
if not ax:
fig = plt.figure(figsize = (3.5, 3.5))
ax = plt.subplot(111)
full_values = list(pars) + list(comps) + list([obs])
min_plot = 0.9 * min(full_values)
max_plot = 1.1 * max(full_values)
xs = np.linspace(min_plot, max_plot, 200)
cov_factor = 0.2
dens_par = comp_dens(pars, cov_factor)
dens_comp = comp_dens(comps, cov_factor)
par_plot, = plt.plot(xs, dens_par(xs), c = '#228B22', linewidth=2)
comp_plot, = plt.plot(xs, dens_comp(xs), c = '#CD69C9', linewidth=2)
ymax = 1.1 * max([max(dens_par(xs)), max(dens_comp(xs))])
plt.plot((obs, obs), (0, ymax), 'k-', linewidth = 2)
if legend:
plt.legend([par_plot, comp_plot], ['Partitions', 'Compositions'], loc = loc, prop = {'size': 10})
ax.tick_params(axis = 'both', which = 'major', labelsize = 8)
if xlim != None:
plt.xlim(xlim)
else: plt.xlim((0.9 * min(full_values), 1.1 * max(full_values)))
return ax
示例9: plot_per_min_debate
def plot_per_min_debate(tweets, cands, interval, \
start = DEBATE_START // 60, end = DEBATE_END // 60, tic_inc = 15, save_to = None):
'''
Plots data from beg of debate to end. For Task 4a.
Note: start and end should be in minutes, not seconds
'''
fig = plt.figure(figsize = (FIGWIDTH, FIGHEIGHT))
period = range(start, end, interval)
c_dict = tweets.get_candidate_mentions_per_minute(cands, interval, period)
y = np.row_stack()
for candidate in c_dict:
plt.plot(period, c_dict[candidate], label = CANDIDATE_NAMES[candidate])
if interval == 1:
plt.title("Mentions per Minute During Debate")
else:
plt.title("Mentions per {} minutes before, during, and after debate".\
format(interval))
plt.xlabel("Time")
plt.ylabel("Number of Tweets")
plt.legend()
ticks_range = range(start, end, tic_inc)
labels = list(map(lambda x: str(x - start) + " min", ticks_range))
plt.xticks(ticks_range, labels, rotation = 'vertical')
plt.xlim( (start, end) )
if save_to:
fig.savefig(save_to)
plt.show()
示例10: plot_dens
def plot_dens(obs, expc, obs_type, ax = None, legend = False, loc = 2, vline = None, xlim = None):
"""Plot the density of observed and expected values, with spatial and temporal observations
distinguished by color.
"""
if not ax:
fig = plt.figure(figsize = (3.5, 3.5))
ax = plt.subplot(111)
obs_spatial = [obs[i] for i in range(len(obs)) if obs_type[i] == 'spatial']
obs_temporal = [obs[i] for i in range(len(obs)) if obs_type[i] == 'temporal']
full_values = list(obs) + list(expc)
min_plot = 0.9 * min(full_values)
max_plot = 1.1 * max(full_values)
xs = np.linspace(min_plot, max_plot, 200)
cov_factor = 0.2
dens_obs_spatial = comp_dens(obs_spatial, cov_factor)
dens_obs_temporal = comp_dens(obs_temporal, cov_factor)
dens_expc = comp_dens(expc, cov_factor)
spat, = plt.plot(xs, dens_obs_spatial(xs), c = '#EE4000', linewidth=2)
temp, = plt.plot(xs, dens_obs_temporal(xs), c = '#1C86EE', linewidth=2)
feas, = plt.plot(xs, dens_expc(xs), 'k-', linewidth=2)
if vline != None:
ymax = 1.1 * max([max(dens_obs_spatial(xs)), max(dens_obs_temporal(xs)), max(dens_expc(xs))])
plt.plot((vline, vline), (0, ymax), 'k--')
if legend:
plt.legend([spat, temp, feas], ['Spatial', 'Temporal', 'Feasible Set'], loc = loc, prop = {'size': 8})
ax.tick_params(axis = 'both', which = 'major', labelsize = 6)
if xlim != None:
plt.xlim(xlim)
return ax
示例11: plot_dens_par_comp
def plot_dens_par_comp(obs, pars, comps, ax = None, legend = False, loc = 2, vline = None, xlim = None):
"""Density plot of the spatial and temporal data pooled together, and results from both partitions and compositions.
"""
if not ax:
fig = plt.figure(figsize = (3.5, 3.5))
ax = plt.subplot(111)
full_values = list(obs) + list(pars) + list(comps)
min_plot = 0.9 * min(full_values)
max_plot = 1.1 * max(full_values)
xs = np.linspace(min_plot, max_plot, 200)
cov_factor = 0.2
dens_obs = comp_dens(obs, cov_factor)
dens_par = comp_dens(pars, cov_factor)
dens_comp = comp_dens(comps, cov_factor)
obs_plot, = plt.plot(xs, dens_obs(xs), 'k-', linewidth=2)
par_plot, = plt.plot(xs, dens_par(xs), c = '#228B22', linewidth=2)
comp_plot, = plt.plot(xs, dens_comp(xs), c = '#CD69C9', linewidth=2)
if vline != None:
ymax = 1.1 * max([max(dens_obs(xs)), max(dens_par(xs)), max(dens_comp(xs))])
plt.plot((vline, vline), (0, ymax), 'k--')
if legend:
plt.legend([obs_plot, par_plot, comp_plot], ['Empirical', 'Partitions', 'Compositions'], loc = loc, prop = {'size': 8})
ax.tick_params(axis = 'both', which = 'major', labelsize = 6)
if xlim != None:
plt.xlim(xlim)
return ax
示例12: plot_obs_expc_new
def plot_obs_expc_new(obs, expc, expc_upper, expc_lower, analysis, log, ax = None):
"""Modified version of obs-expc plot suggested by R2. The points are separated by whether their CIs are above, below,
or overlapping the empirical value
Input:
obs - list of observed values
expc_mean - list of mean simulated values for the corresponding observed values
expc_upper - list of the 97.5% quantile of the simulated vlaues
expc_lower - list of the 2.5% quantile of the simulated values
analysis - whether it is patitions or compositions
log - whether the y axis is to be transformed. If True, expc/obs is plotted. If Flase, expc - obs is plotted.
ax - whether the plot is generated on a given figure, or a new plot object is to be created
"""
obs, expc, expc_upper, expc_lower = list(obs), list(expc), list(expc_upper), list(expc_lower)
if not ax:
fig = plt.figure(figsize = (3.5, 3.5))
ax = plt.subplot(111)
ind_above = [i for i in range(len(obs)) if expc_lower[i] > obs[i]]
ind_below = [i for i in range(len(obs)) if expc_upper[i] < obs[i]]
ind_overlap = [i for i in range(len(obs)) if expc_lower[i] <= obs[i] <= expc_upper[i]]
if log:
expc_standardize = [expc[i] / obs[i] for i in range(len(obs))]
expc_upper_standardize = [expc_upper[i] / obs[i] for i in range(len(obs))]
expc_lower_standardize = [expc_lower[i] / obs[i] for i in range(len(obs))]
axis_min = 0.9 * min([expc_lower_standardize[i] for i in range(len(expc_lower_standardize)) if expc_lower_standardize[i] != 0])
axis_max = 1.5 * max(expc_upper_standardize)
else:
expc_standardize = [expc[i] - obs[i] for i in range(len(obs))]
expc_upper_standardize = [expc_upper[i] - obs[i] for i in range(len(obs))]
expc_lower_standardize = [expc_lower[i] - obs[i] for i in range(len(obs))]
axis_min = 1.1 * min(expc_lower_standardize)
axis_max = 1.1 * max(expc_upper_standardize)
if analysis == 'partition': col = '#228B22'
else: col = '#CD69C9'
ind_full = []
for index in [ind_below, ind_overlap, ind_above]:
expc_standardize_ind = [expc_standardize[i] for i in index]
sort_ind_ind = sorted(range(len(expc_standardize_ind)), key = lambda i: expc_standardize_ind[i])
sorted_index = [index[i] for i in sort_ind_ind]
ind_full.extend(sorted_index)
xaxis_max = len(ind_full)
for i, ind in enumerate(ind_full):
plt.plot([i, i],[expc_lower_standardize[ind], expc_upper_standardize[ind]], '-', c = col, linewidth = 0.4)
plt.scatter(range(len(ind_full)), [expc_standardize[i] for i in ind_full], c = col, edgecolors='none', s = 8)
if log:
plt.plot([0, xaxis_max + 1], [1, 1], 'k-', linewidth = 1.5)
ax.set_yscale('log')
else: plt.plot([0, xaxis_max + 1], [0, 0], 'k-', linewidth = 1.5)
plt.plot([len(ind_below) - 0.5, len(ind_below) - 0.5], [axis_min, axis_max], 'k--')
plt.plot([len(ind_below) + len(ind_overlap) - 0.5, len(ind_below) + len(ind_overlap) - 0.5], [axis_min, axis_max], 'k--')
plt.xlim(0, xaxis_max)
plt.ylim(axis_min, axis_max)
plt.tick_params(axis = 'y', which = 'major', labelsize = 8, labelleft = 'on')
plt.tick_params(axis = 'x', which = 'major', top = 'off', bottom = 'off', labelbottom = 'off')
return ax
示例13: plot_convergence
def plot_convergence():
data = np.loadtxt("smooth-error.out")
nx = data[:,0]
aerr = data[:,1]
ax = plt.subplot(111)
ax.set_xscale('log')
ax.set_yscale('log')
plt.scatter(nx, aerr, marker="x", color="r")
plt.plot(nx, aerr[0]*(nx[0]/nx)**2, "--", color="k")
plt.xlabel("number of zones")
plt.ylabel("L2 norm of abs error")
plt.title(r"convergence for smooth advection problem", fontsize=11)
f = plt.gcf()
f.set_size_inches(5.0,5.0)
plt.xlim(8,256)
plt.savefig("smooth_converge.eps", bbox_inches="tight")
示例14: plt_data
def plt_data():
t = [[0,1], [1,0], [1, 1], [0, 0]]
t2 = [1, 1, 1, 0]
X = np.array(t)
Y = np.array(t2)
h = .02 # step size in the mesh
logreg = linear_model.LogisticRegression(C=1e5)
# we create an instance of Neighbours Classifier and fit the data.
logreg.fit(X, Y)
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, m_max]x[y_min, y_max].
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = logreg.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(1, figsize=(4, 3))
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.xticks(())
plt.yticks(())
plt.show()
示例15: make_entity_plot
def make_entity_plot(filename, title, fixed_noip, fixed_ip, dynamic_noip, dynamic_ip):
plt.figure(figsize=(12,5))
plt.title("Settings comparison - " + title)
plt.xlabel('Time (ms)', fontsize=12)
plt.xlim([0,62000])
x = 0
barwidth = 0.5
bargroupspacing = 1.5
fixed_noip_mean,fixed_noip_conf = conf_stats(fixed_noip)
fixed_ip_mean,fixed_ip_conf = conf_stats(fixed_ip)
dynamic_noip_mean,dynamic_noip_conf = conf_stats(dynamic_noip)
dynamic_ip_mean,dynamic_ip_conf = conf_stats(dynamic_ip)
values = [fixed_noip_mean,fixed_ip_mean,dynamic_noip_mean, dynamic_ip_mean]
errs = [fixed_noip_conf,fixed_ip_conf,dynamic_noip_conf, dynamic_ip_conf]
y_pos = numpy.arange(len(values))
plt.barh(y_pos, values, xerr=errs, align='center', color=['r', 'b', 'r', 'b'], ecolor='black', alpha=0.7)
plt.yticks(y_pos, ["Fixed | no I.P.", "Fixed | I.P.", "Dynamic | no I.P.", "Dynamic | I.P."])
plt.savefig(output_file(filename))
plt.clf()