本文整理汇总了Python中matplotlib.pyplot.hlines方法的典型用法代码示例。如果您正苦于以下问题:Python pyplot.hlines方法的具体用法?Python pyplot.hlines怎么用?Python pyplot.hlines使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.pyplot
的用法示例。
在下文中一共展示了pyplot.hlines方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: visualize_anomaly
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def visualize_anomaly(y_true, reconstruction_error, threshold):
error_df = pd.DataFrame({'reconstruction_error': reconstruction_error,
'true_class': y_true})
print(error_df.describe())
groups = error_df.groupby('true_class')
fig, ax = plt.subplots()
for name, group in groups:
ax.plot(group.index, group.reconstruction_error, marker='o', ms=3.5, linestyle='',
label="Fraud" if name == 1 else "Normal")
ax.hlines(threshold, ax.get_xlim()[0], ax.get_xlim()[1], colors="r", zorder=100, label='Threshold')
ax.legend()
plt.title("Reconstruction error for different classes")
plt.ylabel("Reconstruction error")
plt.xlabel("Data point index")
plt.show()
示例2: view_palette
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def view_palette(*args):
if len(args) > 1:
f, ax = plt.subplots(1, len(args), figsize=(3 * len(args), 3))
for i, name in enumerate(args):
check_key(name)
cycle = palettes[name]
for j, c in enumerate(cycle):
ax[i].hlines(j, 0, 1, colors=c, linewidth=15)
ax[i].set_title(name)
despine(ax[i], True)
plt.show()
elif len(args) == 1:
f = plt.figure(figsize=(3, 3))
check_key(args[0])
cycle = palettes[args[0]]
for j, c in enumerate(cycle):
plt.hlines(j, 0, 1, colors=c, linewidth=15)
plt.title(args[0])
despine(plt.axes(), True)
f.tight_layout()
plt.show()
else:
raise NotImplementedError("ERROR: supply a palette to plot. check vapeplot.available() for available palettes")
示例3: LR_multiRegression
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def LR_multiRegression(X_lrm,y_lrm,predFeat=False):
X=X_lrm
y=y_lrm
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=0)
slr=LinearRegression()
slr.fit(X_train,y_train)
y_train_pred=slr.predict(X_train)
y_test_pred=slr.predict(X_test)
plt.scatter(y_train_pred,y_train_pred-y_train,c='blue',marker='o',label='Training data')
plt.scatter(y_test_pred,y_test_pred-y_test,c='lightgreen',marker='s',label='Test data')
plt.xlabel('Predicted values')
plt.ylabel('Residuals')
plt.legend(loc='upper left')
plt.hlines(y=0,xmin=-10,xmax=7,lw=2,color='red')
plt.xlim([0,7])
plt.show()
print(slr.coef_,slr.intercept_)
print('MSE train:%.3f,test:%.3f'%(mean_squared_error(y_train,y_train_pred),mean_squared_error(y_test,y_test_pred))) #MSE, float or ndarray of floats,A non-negative floating point value (the best value is 0.0), or an array of floating point values, one for each individual target.
print('R^2 train:%.3f,test:%.3f'%(r2_score(y_train,y_train_pred),r2_score(y_test,y_test_pred)))
if type(predFeat).__module__=='numpy':
return slr.predict(predFeat)
示例4: rfReg
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def rfReg(X_rfReg,y_rfReg,predFeat=False):
X=X_rfReg
y=y_rfReg
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.4,random_state=1)
forest=RandomForestRegressor(n_estimators=100,criterion='mse',random_state=1,n_jobs=-1)
forest.fit(X_train,y_train)
y_train_pred=forest.predict(X_train)
y_test_pred=forest.predict(X_test)
print('MSE train:%.3f,test:%.3f'%(mean_squared_error(y_train,y_train_pred),mean_squared_error(y_test,y_test_pred)))
print('R^2 train:%.3f,test:%.3f'%(r2_score(y_train,y_train_pred),r2_score(y_test,y_test_pred)))
plt.scatter(y_train_pred,y_train_pred-y_train,c='blue',marker='o',label='Training data')
plt.scatter(y_test_pred,y_test_pred-y_test,c='lightgreen',marker='s',label='Test data')
plt.xlabel('Predicted values')
plt.ylabel('Residuals')
plt.legend(loc='upper left')
plt.hlines(y=0,xmin=0,xmax=6,lw=2,color='red')
plt.xlim([0,6])
plt.show()
if type(predFeat).__module__=='numpy':
return forest.predict(predFeat)
示例5: flip_plot
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def flip_plot(min_exp, max_exp):
"""
Assumes min_exp and min_exp positive integers; min_exp < max_exp
Plots results of 2**min_exp to 2**max_exp coin flips
抛硬币的次数为2的min_exp次方到2的max_exp次方
一共进行了 2**max_exp - 2**min_exp 轮实验,每轮实验抛硬币次数逐渐增加
"""
ratios = []
x_axis = []
for exp in range(min_exp, max_exp + 1):
x_axis.append(2**exp)
for numFlips in x_axis:
num_heads = 0 # 初始化,硬币正面朝上的计数为0
for n in range(numFlips):
if random.random() < 0.5: # random.random()从[0, 1)随机的取出一个数
num_heads += 1 # 当随机取出的数小于0.5时,正面朝上的计数加1
num_tails = numFlips - num_heads # 得到本次试验中反面朝上的次数
ratios.append(num_heads/float(num_tails)) # 正反面计数的比值
plt.title('Heads/Tails Ratios')
plt.xlabel('Number of Flips')
plt.ylabel('Heads/Tails')
plt.plot(x_axis, ratios)
plt.hlines(1, 0, x_axis[-1], linestyles='dashed', colors='r')
plt.show()
示例6: plot
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def plot(args, timings):
for name, cls_timings in timings:
xs, relative_timings = zip(*cls_timings)
ys = [r.normal / r.compiled for r in relative_timings]
for x, y in zip(xs, ys):
print(xs, ys)
if args.show_plot:
plt.plot(xs, ys, '-o', label=name)
plt.hlines(1.0, np.min(xs), np.max(xs), 'k')
if not args.show_plot:
return
plt.xlabel('Number of weak learners')
plt.ylabel('Relative speedup')
plt.axis('tight')
plt.legend()
plt.gca().set_ylim(bottom=0)
title, suptitle = titles(args)
plt.title(title)
plt.suptitle(suptitle, fontsize=3)
filename = "timings{0}.png".format(hash(str(args)))
plt.savefig(filename, dpi=72)
示例7: graph_barcode
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def graph_barcode(data, ph, homology_group=0):
persistence = ph.transform(data)
# this function just produces the barcode graph for each homology group
xstart = [s[1][0] for s in persistence if s[0] == homology_group]
xstop = [s[1][1] for s in persistence if s[0] == homology_group]
y = [0.1 * x + 0.1 for x in range(len(xstart))]
plt.hlines(y, xstart, xstop, color='b', lw=4)
# Setup the plot
ax = plt.gca()
plt.ylim(0, max(y) + 0.1)
ax.yaxis.set_major_formatter(plt.NullFormatter())
plt.xlabel('epsilon')
plt.ylabel("Betti dim %s" % (homology_group,))
plt.show()
示例8: visualize_reconstruction_error
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def visualize_reconstruction_error(reconstruction_error, threshold):
plt.plot(reconstruction_error, marker='o', ms=3.5, linestyle='',
label='Point')
plt.hlines(threshold, xmin=0, xmax=len(reconstruction_error)-1, colors="r", zorder=100, label='Threshold')
plt.legend()
plt.title("Reconstruction error")
plt.ylabel("Reconstruction error")
plt.xlabel("Data point index")
plt.show()
示例9: plot_date
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def plot_date(dataframe, column_name):
"""
:param dataframe:
:param column_name:
:type column_name:str
:return:
"""
fig = plt.figure(figsize=(11.69, 8.27))
p = plt.plot(dataframe.index, dataframe[column_name], 'b-', label=r"%s" % column_name)
plt.hlines(0, min(dataframe.index), max(dataframe.index), 'r')
plt.legend(loc='best')
fig.autofmt_xdate(rotation=90)
return p
示例10: available
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def available(show=True):
if not show:
return palettes.keys()
else:
f, ax = plt.subplots(5, 2, figsize=(5, 8))
for i, name in enumerate(palettes.keys()):
x, y = i // 2, i % 2
cycle = palettes[name]
for j, c in enumerate(cycle):
ax[x, y].hlines(j, 0, 1, colors=c, linewidth=15)
ax[x, y].set_ylim(-1, len(cycle))
ax[x, y].set_title(name)
despine(ax[x, y], True)
plt.show()
示例11: Hlines
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def Hlines(ys, x1, x2, **options):
"""Plots a set of horizontal lines.
Args:
ys: sequence of y values
x1: sequence of x values
x2: sequence of x values
options: keyword args passed to plt.vlines
"""
options = _UnderrideColor(options)
options = _Underride(options, linewidth=1, alpha=0.5)
plt.hlines(ys, x1, x2, **options)
示例12: example_plot_bias_ts
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def example_plot_bias_ts():
ax = pdf.plot(figsize=(8, 4), secondary_y='bias')
plt.hlines(0, 1800, 2015, linestyles='-')
ax.set_ylabel(r'$\mu$ (mm yr$^{-1}$ K$^{-1}$)')
ax.set_title(r'$\mu$ candidates HEF')
plt.ylabel(r'bias (mm yr$^{-1}$)')
yl = plt.gca().get_ylim()
plt.plot((res['t_star'], res['t_star']), (yl[0], 0),
linestyle=':', color='grey')
plt.ylim(yl)
plt.tight_layout()
plt.show()
示例13: test_limiter
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def test_limiter(self, default_calving):
_, ds1, df_diag1 = default_calving
model = FluxBasedModel(bu_tidewater_bed(),
mb_model=ScalarMassBalance(),
is_tidewater=True, calving_use_limiter=False,
flux_gate=0.06, do_kcalving=True,
calving_k=0.2)
_, ds2 = model.run_until_and_store(3000)
df_diag2 = model.get_diagnostics()
assert_allclose(model.volume_m3 + model.calving_m3_since_y0,
model.flux_gate_m3_since_y0)
assert_allclose(ds2.calving_m3[-1], model.calving_m3_since_y0)
assert_allclose(ds2.volume_bsl_m3[-1], model.volume_bsl_km3 * 1e9)
assert_allclose(ds2.volume_bwl_m3[-1], model.volume_bwl_km3 * 1e9)
# Not exact same of course
assert_allclose(ds1.volume_m3[-1], ds2.volume_m3[-1], rtol=0.06)
assert_allclose(ds1.calving_m3[-1], ds2.calving_m3[-1], rtol=0.15)
assert_allclose(ds1.volume_bsl_m3[-1], ds2.volume_bsl_m3[-1], rtol=0.3)
assert_allclose(ds2.volume_bsl_m3, ds2.volume_bwl_m3)
if do_plot:
f, ax = plt.subplots(1, 1, figsize=(12, 5))
df_diag1[['surface_h']].plot(ax=ax, color=['C3'])
df_diag2[['surface_h', 'bed_h']].plot(ax=ax, color=['C1', 'k'])
plt.hlines(0, 0, 60000, color='C0', linestyles=':')
plt.ylim(-350, 800)
plt.ylabel('Altitude [m]')
plt.show()
示例14: test_tributary
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def test_tributary(self, default_calving):
_, ds1, df_diag1 = default_calving
model = FluxBasedModel(bu_tidewater_bed(split_flowline_before_water=5),
mb_model=ScalarMassBalance(),
is_tidewater=True, calving_use_limiter=True,
smooth_trib_influx=False,
flux_gate=[0.06, 0], do_kcalving=True,
calving_k=0.2)
_, ds2 = model.run_until_and_store(3000)
df_diag2_a = model.get_diagnostics(fl_id=0)
df_diag2_b = model.get_diagnostics(fl_id=1)
assert_allclose(model.volume_m3 + model.calving_m3_since_y0,
model.flux_gate_m3_since_y0)
assert_allclose(ds2.calving_m3[-1], model.calving_m3_since_y0)
assert_allclose(ds2.volume_bsl_m3[-1], model.volume_bsl_km3 * 1e9)
assert_allclose(ds2.volume_bwl_m3[-1], model.volume_bwl_km3 * 1e9)
# should be veeery close
rtol = 5e-4
assert_allclose(ds1.volume_m3[-1], ds2.volume_m3[-1], rtol=rtol)
assert_allclose(ds1.calving_m3[-1], ds2.calving_m3[-1], rtol=rtol)
assert_allclose(ds1.volume_bsl_m3[-1], ds2.volume_bsl_m3[-1],
rtol=rtol)
assert_allclose(ds2.volume_bsl_m3, ds2.volume_bwl_m3, rtol=rtol)
df_diag1['surface_h_trib'] = np.append(df_diag2_a['surface_h'],
df_diag2_b['surface_h'])
if do_plot:
f, ax = plt.subplots(1, 1, figsize=(12, 5))
df_diag1[['surface_h', 'surface_h_trib',
'bed_h']].plot(ax=ax, color=['C3', 'C1', 'k'])
plt.hlines(0, 0, 60000, color='C0', linestyles=':')
plt.ylim(-350, 800)
plt.ylabel('Altitude [m]')
plt.show()
示例15: show_iter_hist
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import hlines [as 别名]
def show_iter_hist(fname, maxiter, nruns):
"""
Helper routine to visualize the maximal iteration number across the simulation in a histogram
Args:
stats (dict): statistics object
fname (str): filename
maxiter: maximal iterations per run
nruns: number of runs
"""
# create plot and save
fig, ax = plt.subplots(figsize=(15, 10))
plt.hist(maxiter, bins=np.arange(min(maxiter), max(maxiter) + 2, 1), align='left', rwidth=0.9)
# with correction allowed: axis instead of xticks
# plt.axis([12, 51, 0, nruns+1])
plt.xticks([13, 15, 20, 25, 30, 35, 40, 45, 50])
ax.set_xlabel('iterations until convergence')
plt.hlines(nruns, min(maxiter), max(maxiter), colors='red', linestyle='dashed')
# with correction allowed: no logscale
plt.yscale('log')
plt.savefig(fname)
assert os.path.isfile(fname), 'ERROR: plotting did not create PNG file'