當前位置: 首頁>>代碼示例>>Python>>正文


Python pyplot.hlines方法代碼示例

本文整理匯總了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() 
開發者ID:chen0040,項目名稱:keras-anomaly-detection,代碼行數:20,代碼來源:plot_utils.py

示例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") 
開發者ID:dantaki,項目名稱:vapeplot,代碼行數:25,代碼來源:vapeplot.py

示例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) 
開發者ID:richieBao,項目名稱:python-urbanPlanning,代碼行數:26,代碼來源:poiRegression.py

示例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) 
開發者ID:richieBao,項目名稱:python-urbanPlanning,代碼行數:24,代碼來源:poiRegression.py

示例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() 
開發者ID:OnlyBelter,項目名稱:machine-learning-note,代碼行數:27,代碼來源:LLN.py

示例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) 
開發者ID:ajtulloch,項目名稱:sklearn-compiledtrees,代碼行數:25,代碼來源:bench_compiled_tree.py

示例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() 
開發者ID:outlace,項目名稱:OpenTDA,代碼行數:16,代碼來源:plotting.py

示例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() 
開發者ID:chen0040,項目名稱:keras-anomaly-detection,代碼行數:12,代碼來源:plot_utils.py

示例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 
開發者ID:Kirubaharan,項目名稱:hydrology,代碼行數:16,代碼來源:ch_591_water_balance.py

示例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() 
開發者ID:dantaki,項目名稱:vapeplot,代碼行數:16,代碼來源:vapeplot.py

示例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) 
開發者ID:Notabela,項目名稱:Lie_to_me,代碼行數:14,代碼來源:thinkplot.py

示例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() 
開發者ID:OGGM,項目名稱:oggm,代碼行數:14,代碼來源:prepare_climate.py

示例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() 
開發者ID:OGGM,項目名稱:oggm,代碼行數:33,代碼來源:test_numerics.py

示例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() 
開發者ID:OGGM,項目名稱:oggm,代碼行數:41,代碼來源:test_numerics.py

示例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' 
開發者ID:Parallel-in-Time,項目名稱:pySDC,代碼行數:32,代碼來源:visualization_helper.py


注:本文中的matplotlib.pyplot.hlines方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。