Python matplotlib.pyplot.fill_between() Examples

The following are code examples for showing how to use matplotlib.pyplot.fill_between(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: cs294-112_hws   Author: xuwd11   File: plot_3.py    MIT License 6 votes vote down vote up
def plot_3(data):
    x = data.Iteration.unique()
    y_mean = data.groupby('Iteration').mean()
    y_std = data.groupby('Iteration').std()
    
    sns.set(style="darkgrid", font_scale=1.5)
    value = 'AverageReturn'
    plt.plot(x, y_mean[value], label=data['Condition'].unique()[0] + '_train');
    plt.fill_between(x, y_mean[value] - y_std[value], y_mean[value] + y_std[value], alpha=0.2);
    value = 'ValAverageReturn'
    plt.plot(x, y_mean[value], label=data['Condition'].unique()[0] + '_test');
    plt.fill_between(x, y_mean[value] - y_std[value], y_mean[value] + y_std[value], alpha=0.2);
    
    plt.xlabel('Iteration')
    plt.ylabel('AverageReturn')
    plt.legend(loc='best') 
Example 2
Project: Kaggler   Author: jeongyoonlee   File: classification.py    MIT License 6 votes vote down vote up
def plot_pr_curve(y, p):
    precision, recall, _ = precision_recall_curve(y, p)

    plt.step(recall, precision, color='b', alpha=0.2, where='post')
    plt.fill_between(recall, precision, step='post', alpha=0.2, color='b')
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.0]) 
Example 3
Project: euclid   Author: njpayne   File: plot_learning_curve.py    GNU General Public License v2.0 6 votes vote down vote up
def plot_validation_curve(estimator, X, y, title, param_name, param_range, cv = 10):
    train_scores, test_scores = validation_curve(
    estimator, X, y, param_name=param_name, param_range=param_range,
    cv=cv, scoring="accuracy", n_jobs=1)
    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)

    plt.figure()
    plt.title(title)
    plt.xlabel(param_name)
    plt.ylabel("Score")
    plt.ylim(0.0, 1.1)
    #plt.semilogx(param_range, train_scores_mean, label="Training score", color="r")
    plt.fill_between(param_range, train_scores_mean - train_scores_std,
                     train_scores_mean + train_scores_std, alpha=0.2, color="r")
    #plt.semilogx(param_range, test_scores_mean, label="Cross-validation score", color="g")
    plt.fill_between(param_range, test_scores_mean - test_scores_std,
                     test_scores_mean + test_scores_std, alpha=0.2, color="g")
    plt.plot(param_range, train_scores_mean, 'o-', color="r", label="Training score")
    plt.plot(param_range, test_scores_mean, 'o-', color="g", label="Cross-validation score")

    plt.legend(loc="best")
    return plt 
Example 4
Project: QCANet   Author: funalab   File: graph_draw.py    MIT License 6 votes vote down vote up
def graph_draw_volume(self, Time, SumVol, MeanVol, StdVol):
        SumVol = np.array(SumVol) * self.scale
        MeanVol = np.array(MeanVol) * self.scale
        StdVol = np.array(StdVol) * self.scale

        # Volume Mean & SD
        plt.figure()
        plt.plot(Time, MeanVol, color='blue')
        plt.fill_between(Time, np.array(MeanVol)-np.array(StdVol), np.array(MeanVol)+np.array(StdVol), color='blue', alpha=0.4)
        plt.legend(["Mean", "Std. Dev."],loc=1)
        plt.xlabel('Time [day]', size=12)
        plt.ylabel('Volume [$\mu m^{3}$]', size=12)
        if Time[-1] != 0:
            plt.xlim([0.0, round(Time[-1], 1)])
        plt.ylim([0.0, np.max(np.array(MeanVol)+np.array(StdVol)) + 1000])
        filename = self.opbase + self.psep + 'MeanStdVolume.pdf'
        plt.savefig(filename) 
Example 5
Project: QCANet   Author: funalab   File: graph_draw.py    MIT License 6 votes vote down vote up
def graph_draw_surface(self, Time, SumArea, MeanArea, StdArea):
        SumArea = np.array(SumArea) * self.scale
        MeanArea = np.array(MeanArea) * self.scale
        StdArea = np.array(StdArea) * self.scale

        # Surface Mean & SD
        plt.figure()
        plt.plot(Time, MeanArea, color='blue')
        plt.fill_between(Time, np.array(MeanArea)-np.array(StdArea), np.array(MeanArea)+np.array(StdArea), color='blue', alpha=0.4)
        plt.legend(["Mean", "Std. Dev."],loc=1)
        plt.xlabel('Time [day]', size=12)
        plt.ylabel('Surface Area [$\mu m^{2}$]', size=12)
        if Time[-1] != 0:
            plt.xlim([0.0, round(Time[-1], 1)])
        plt.ylim([0.0, np.max(np.array(MeanArea)+np.array(StdArea)) + 1000])
        filename = self.opbase + self.psep + 'MeanStdSurface.pdf'
        plt.savefig(filename) 
Example 6
Project: u8timeseries   Author: unit8co   File: statistics.py    Apache License 2.0 6 votes vote down vote up
def plot_acf(ts: 'TimeSeries', m: int = None, max_lag: int = 24, alpha: float = 0.05,
             fig_size: Tuple[int, int] = (10, 5)):
    """
    Plots the ACF of [ts], highlighting it at lag [m], with corresponding significance interval.

    :param ts: The TimeSeries whose ACF should be plotted.
    :param m:  The lag to highlight.
    :param max_lag: The maximal lag order to consider.
    :param alpha: The confidence interval.
    :param fig_size: The size of the figure to be displayed.
    :return:
    """
    r = acf(ts.values(), nlags=max_lag)

    # Computes the confidence interval at level alpha for all lags.
    stats = []
    for i in range(1, max_lag+1):
        stats.append(_bartlett_formula(r[1:], i, len(ts)))

    plt.figure(figsize=fig_size)

    for i in range(len(r)):
        plt.plot((i, i), (0, r[i]), color=('red' if m is not None and i == m else 'black'), lw=.5)

    upp_band = r[1:].mean() + norm.ppf(1 - alpha/2) * r[1:].var()
    acf_band = [upp_band * stat for stat in stats]

    plt.fill_between(np.arange(1, max_lag+1), acf_band, [-x for x in acf_band], color='blue', alpha=.25)
    plt.plot((0, max_lag+1), (0, 0), color='black')

    plt.show() 
Example 7
Project: hrt   Author: tansey   File: sim_predictors_order.py    MIT License 6 votes vote down vote up
def order_vs_p_scatter(orders, p, n, c):
    plt.close()
    with sns.axes_style('white', {'legend.frameon': True}):
        plt.rc('font', weight='bold')
        plt.rc('grid', lw=3)
        plt.rc('lines', lw=2)
        plt.rc('axes', lw=2)
        ntests = len(order[0])
        buckets = np.zeros((len(order), ntests))
        for trial_idx, (trial_order, trial_p) in enumerate(zip(order, p)):
            buckets[trial_idx, trial_order] = trial_p
        plt.plot(np.arange(ntests)+1, buckets.mean(axis=0), color=c)
        plt.fill_between(np.arange(ntests)+1,
                         buckets.mean(axis=0) - buckets.std(axis=0),
                         buckets.mean(axis=0) + buckets.std(axis=0),
                         color=c,
                         alpha=0.7)
        plt.xlabel('Heuristic rank', fontsize=18, weight='bold')
        plt.ylabel('$\\mathbf{p}$-value', fontsize=18, weight='bold') 
Example 8
Project: pytorch-hessian-eigenthings   Author: noahgolmant   File: utils.py    MIT License 6 votes vote down vote up
def plot_eigenval_estimates(estimates, label):
    """
    estimates = 2D array (num_trials x num_eigenvalues)

    x-axis = eigenvalue index
    y-axis = eigenvalue estimate
    """
    if len(estimates.shape) == 1:
        var = np.zeros_like(estimates)
    else:
        var = np.var(estimates, axis=0)
    y = np.mean(estimates, axis=0)
    x = list(range(len(y)))
    error = np.sqrt(var)
    plt.plot(x, y, label=label)
    plt.fill_between(x, y-error, y+error, alpha=.2) 
Example 9
Project: pytorch-hessian-eigenthings   Author: noahgolmant   File: utils.py    MIT License 6 votes vote down vote up
def plot_eigenvec_errors(true, estimates, label):
    """
    plots error for all eigenvector estimates in L2 norm
    estimates = (num_trials x num_eigenvalues x num_params)
    true = (num_eigenvalues x num_params)
    """
    diffs = []
    num_eigenvals = true.shape[0]
    for i in range(num_eigenvals):
        cur_estimates = estimates[:, i, :]
        cur_eigenvec = true[i]
        diff = compute_eigenvec_cos_similarity(cur_eigenvec, cur_estimates)
        diffs.append(diff)
    diffs = np.array(diffs).T
    var = np.var(diffs, axis=0)
    y = np.mean(diffs, axis=0)
    x = list(range(len(y)))

    error = np.sqrt(var)
    plt.plot(x, y, label=label)
    plt.fill_between(x, y-error, y+error, alpha=.2) 
Example 10
Project: OED   Author: tungk   File: utils.py    GNU General Public License v3.0 6 votes vote down vote up
def PlotPrecisionRecallCurve(_precision, _recall, _average_precision):
    plt.figure(2)
    lw = 2
    plt.step(_recall, _precision, color='darkorange', lw=lw, alpha=1, where='post', label='PR curve (area = %0.2f)' % _average_precision)
    # plt.fill_between(_recall, _precision, step='post', alpha=0.2, color='b')
    plt.plot([0, 1], [1, 0], color='navy', lw=lw, linestyle='--')
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.title('Precision-Recall Curve')
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.0])
    # plt.legend('AP={0:0.2f}'.format(_average_precision))
    plt.legend(loc="lower right")
    plt.show()



# ReadS5Dataset('./YAHOO/data/A1Benchmark/real_1.csv')
# ReadGDDataset('./GD/data/Genesis_AnomalyLabels.csv')
# ReadHSSDataset('./HSS/data/HRSS_anomalous_standard.csv') 
Example 11
Project: nanopores   Author: mitschabaude   File: rw.py    MIT License 6 votes vote down vote up
def plot_evolution(params, color=None, label=None):
    data = get_results(NAME, params, calc=do_calculations)
    times = data.times
    success = data.success
    N = float(len(success))
    t = sorted(times[success])
    p = np.arange(sum(success))/N
    t.append(endtime)
    p = np.append(p, [p[-1]])
    errp = 1.96*np.sqrt(p*(1.-p)/N) # 95% confidence
    
    plt.semilogx(t, p, color=color, label=label)
    plt.fill_between(t, p - errp, p + errp, alpha=0.2,
                     facecolor=color, linewidth=0)
    plt.xlabel("Time [ns]")
    plt.ylabel("Exit probability")
    plt.xlim(xmin=0.1, xmax=5e6)
    print "last time: %.5f ms\nend prob: %.3f\nstd. dev.: %.3f" % (
        t[-2]*1e-6, p[-2], errp[-2]) 
Example 12
Project: TicTacToe   Author: Neural-Network   File: classification.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_module_classification_sequence_performance(module, dataset, sequence_index, bounds=(0, 1)):
        """Plot all outputs and fill the value of the output of the correct category.

        The grapth of a good classifier should be like all white, with all other
        values very low. A graph with lot of black is a bad sign.

        :param module: The module/network to plot.
        :type module: pybrain.structure.modules.module.Module
        :param dataset: Training dataset used as inputs and expected outputs.
        :type dataset: SequenceClassificationDataSet
        :param sequence_index: Sequence index to plot in the dataset.
        :type sequence_index: int
        :param bounds: Outputs lower and upper bound.
        :type bounds: list
        """
        outputs = []
        valid_output = []
        module.reset()
        for sample in dataset.getSequenceIterator(sequence_index):
            out = module.activate(sample[0])
            outputs.append(out)
            valid_output.append(out[sample[1].argmax()])
        plt.fill_between(list(range(len(valid_output))), 1, valid_output, facecolor='k', alpha=0.8)
        plt.plot(outputs, linewidth=4, alpha=0.7)
        plt.yticks(bounds) 
Example 13
Project: DDLO   Author: revenol   File: main.py    MIT License 6 votes vote down vote up
def plot_gain(gain_his,name=None):
    #display data
    import matplotlib.pyplot as plt
    import pandas as pd
    import matplotlib as mpl

    gain_array = np.asarray(gain_his)
    df = pd.DataFrame(gain_his)

    mpl.style.use('seaborn')
    fig, ax = plt.subplots(figsize=(15,8))
    rolling_intv = 60
    df_roll=df.rolling(rolling_intv, min_periods=1).mean()
    if name != None:
        sio.savemat('./data/MUMT(%s)'%name,{'ratio':gain_his})

    plt.plot(np.arange(len(gain_array))+1, df_roll, 'b')
    plt.fill_between(np.arange(len(gain_array))+1, df.rolling(rolling_intv, min_periods=1).min()[0], df.rolling(rolling_intv, min_periods=1).max()[0], color = 'b', alpha = 0.2)
    plt.ylabel('Gain ratio')
    plt.xlabel('learning steps')
    plt.show() 
Example 14
Project: data-analysis-pipelines   Author: radujica   File: plot.py    MIT License 6 votes vote down vote up
def plot_profile_scatter_single_cpu(input_, pipelines):
    dfs = {pipeline: read_collectl_pipelines_cpu(input_, pipeline) for pipeline in pipelines}
    dfs['python'] = dfs['python-libraries']
    del dfs['python-libraries']

    max_x = max([df.index.values[-1] for df in dfs.values()])
    [plt.plot(df.index.values, df['cpu_mean'], '-', label=name, color=pipelines_colors[name])
     for name, df in dfs.items()]
    [plt.fill_between(df.index.values, df['cpu_mean'] - df['cpu_diff'], df['cpu_mean'] + df['cpu_diff'], alpha=0.3, facecolor=pipelines_colors[name])
     for name, df in dfs.items()]
    plt.ylabel('CPU (%)', fontsize=12)
    plt.xlabel('Time (s)', fontsize=12)
    plt.title(input_, fontsize=12)
    plt.legend(fontsize=10, labelspacing=0.05, loc='upper right')

    plt.axhline(y=100, color='k', linewidth=0.5)
    plt.text(max_x - 3, 130, '100') 
Example 15
Project: consistent-dynamics   Author: shagunsodhani   File: plot.py    MIT License 6 votes vote down vote up
def make_variance_plot(grouped_config_ids):
    def _plot_variance_curve(data, label):
        for i in data:
            print(i.shape)
        mean_data = np.mean(data, axis=0)
        std_data = np.std(data, axis=0)
        x = range(len(mean_data))
        plt.plot(x, mean_data, label=label)
        plt.fill_between(x, mean_data + std_data, mean_data - std_data, alpha=0.2)

    mode = "val"
    metric_keys = set(["imagination_log_likelihood", "imitation_learning_loss", "discriminator_loss", "consistency_loss"])
    for metric in metric_keys:
        for grouped_config in grouped_config_ids:
            grouped_logs = np.asarray(list((seq(grouped_config)
                            .map(get_logs_from_config_id)
                            .map(lambda logs: logs[mode][metric], ))))
            alpha = get_logs_from_config_id(grouped_config[0])['config'][-1]['model']['imagination_model']['consistency_model']['alpha']
            _plot_variance_curve(grouped_logs, label=alpha)
        title = metric
        plot_dir = "."
        path = os.path.join(plot_dir, "_".join(title.split()) + ".png")
        plt.legend()
        plt.savefig(path)
        plt.clf() 
Example 16
Project: kicker-module   Author: EvanTheB   File: graph.py    GNU General Public License v3.0 5 votes vote down vote up
def graph_skill_error(p, g, ladder):
    def get_names_skill(data):
        ret = []
        for l in data:
            ret.append((l.name, l.extra[1][1]))
        return ret

    def get_names_err(data):
        ret = []
        for l in data:
            ret.append((l.name, l.extra[2][1]))
        return ret

    def get_top_n(data):
        tup = sorted(data, key=lambda x: float(x[1]))
        names = [t[0] for t in tup[:6]]
        return names

    graph_data = []
    err_data = []
    for i in range(1, len(g) + 1):
        data = ladder.process(p, g[0:i])
        graph_data.append(get_names_skill(data))
        err_data.append(get_names_err(data))
    names = sorted(get_top_n(err_data[-1]))
    graph_data = [sorted(x) for x in get_subset(graph_data, names)]
    err_data = [sorted(x) for x in get_subset(err_data, names)]

    ys = data_to_yarr(graph_data)
    errs = data_to_yarr(err_data)
    for i in range(len(ys)):
        err = np.array(errs[i])
        y = np.array(ys[i])
        plt.fill_between(range(len(y)), y+err, y-err, alpha=0.25, color=COLOURS[i])
        plt.plot(range(len(y)), y, COLOURS[i] +'-', label = names[i])
        plt.plot(y)
    plt.legend(loc=3, ncol=len(names)/2)
    pylab.savefig('graph_error.svg')
#    plt.show() 
Example 17
Project: sfcc   Author: kv-kunalvyas   File: auxiliary.py    MIT License 5 votes vote down vote up
def plotLearningCurves(train, classifier):
    #P.show()
    X = train.values[:, 1::]
    y = train.values[:, 0]

    train_sizes, train_scores, test_scores = learning_curve(
            classifier, X, y, cv=10, n_jobs=-1, train_sizes=np.linspace(.1, 1., 10), verbose=0)

    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)

    plt.figure()
    plt.title("Learning Curves")
    plt.legend(loc="best")
    plt.xlabel("Training samples")
    plt.ylabel("Error Rate")
    plt.ylim((0, 1))
    plt.gca().invert_yaxis()
    plt.grid()

    # Plot the average training and test score lines at each training set size
    plt.plot(train_sizes, train_scores_mean, 'o-', color="b", label="Training score")
    plt.plot(train_sizes, test_scores_mean, 'o-', color="r", label="Test score")

    # Plot the std deviation as a transparent range at each training set size
    plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std,
                     alpha=0.1, color="b")
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std,
                     alpha=0.1, color="r")

    # Draw the plot and reset the y-axis
    plt.draw()
    plt.gca().invert_yaxis()

    # shuffle and split training and test sets
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.25)
    classifier.fit(X_train, y_train)
    plt.show() 
Example 18
Project: helloworld   Author: pip-uninstaller-python   File: matplotlibTest.py    GNU General Public License v2.0 5 votes vote down vote up
def main():
    # line
    x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
    c, s = np.cos(x), np.sin(x)
    plt.figure(1)
    plt.plot(x, c, color="blue", linewidth=1.0, linestyle="-", label="COS", alpha=0.5)  # 自变量, 因变量
    plt.plot(x, s, "r.", label="SIN")  # 正弦  "-"/"r-"/"r."
    plt.title("COS & SIN")
    ax = plt.gca()
    ax.spines["right"].set_color("none")
    ax.spines["top"].set_color("none")
    ax.spines["left"].set_position(("data", 0))  # 横轴位置
    ax.spines["bottom"].set_position(("data", 0))  # 纵轴位置
    ax.xaxis.set_ticks_position("bottom")
    ax.yaxis.set_ticks_position("left")
    plt.xticks([-np.pi, -np.pi / 2.0, np.pi / 2, np.pi],
               [r'$-\pi/2$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$-\pi$'])
    plt.yticks(np.linspace(-1, 1, 5, endpoint=True))
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontsize(16)
        label.set_bbox(dict(facecolor="white", edgecolor="None", alpha=0.2))
    plt.legend(loc="upper left")  # 左上角的显示图标
    plt.grid()  # 网格线
    # plt.axis([-1, 1, -0.5, 1])  # 显示范围
    plt.fill_between(x, np.abs(x) < 0.5, c, c < 0.5, color="green", alpha=0.25)
    t = 1
    plt.plot([t, t], [0, np.cos(t)], "y", linewidth=3, linestyle="--")
    # 注释
    plt.annotate("cos(1)", xy=(t, np.cos(1)), xycoords="data", xytext=(+10, +30),
                 textcoords="offset points", arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=.2"))
    plt.show()


# Scatter --> 散点图 
Example 19
Project: euclid   Author: njpayne   File: plot_learning_curve.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_learning_curve_iter(estimator, title, cv = 10):

    test_scores = []
    test_std =[]
    iteration_count = []

    for i in range(len(estimator.grid_scores_)):
        #get the cross validation results from the estimator
        iteration_count.append(estimator.grid_scores_[i][0]["n_iter"])
        test_scores.append(estimator.grid_scores_[i].mean_validation_score)
        test_std.append(np.std(estimator.grid_scores_[i].cv_validation_scores))

    #convert arrays to numpy
    test_scores = np.array(test_scores)
    test_std = np.array(test_std)
    iteration_count = np.array(iteration_count)

    plt.figure()
    plt.title(title)
    plt.xlabel("Epochs")
    plt.ylabel("Score")
    plt.ylim(0.0, 1.1)
    plt.grid()
    #plt.semilogx(param_range, test_scores_mean, label="Cross-validation score", color="g")
    plt.fill_between(iteration_count, test_scores - test_std ,
                     test_scores + test_std , alpha=0.2, color="g")
    plt.plot(iteration_count, test_scores, 'o-', color="g",
             label="Cross-validation score")
    plt.legend(loc="best")

    return plt 
Example 20
Project: aftershoq   Author: mfranckie   File: gaussopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def plotGP(self):
        '''Plot the GP at its current stage in the minimization.
        '''
        maxloc = self.maxloc; umax = self.umax
        xt = self.xt; mean = np.squeeze( self.mean )
        cov = self.cov; u = self.u;
        x = self.x; y = self.y;

        var = np.reshape( np.abs( np.diag( self.cov ) ), (self.Nx,1) )

        pl.figure(5)
        pl.clf()
        pl.plot(xt,mean)
        pl.plot(x,y,'*')
        pl.fill_between(np.squeeze(xt), mean-np.squeeze(2*np.sqrt(var)),
                        mean+np.squeeze(2*np.sqrt(var)),
                        facecolor = "grey", alpha=0.5)
        pl.plot(xt,u/5,'-g')
        pl.plot(maxloc,umax,'*')
        pl.ylim(-5, 5)

        lim_diff = (np.max(y) - np.min(y))/2.

        pl.gca().set_xlim( 0, np.max(x) )
        pl.gca().set_ylim( np.min(y) - lim_diff, np.max(y) + lim_diff )

        #writer.grab_frame()
        pl.pause(0.01) 
Example 21
Project: aftershoq   Author: mfranckie   File: gaussopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def plotGP_testfunc(self, model, hutil):
        '''Plot the GP at its current stage in the minimization
        with the test function "model".

        Parameters

        model: A tets function giving a fast merit function evaluation'''

        xt = self.xt; mean = np.squeeze( self.mean ); cov = self.cov; u = self.u;
        maxloc = self.maxloc; umax = self.umax
        x = self.x; y = self.y;

        var = np.reshape( np.abs( np.diag( self.cov ) ), (self.Nx,1) )

        yt = []
        [yt.append(-model.getMerit((hutil.interp_coords_from_dist(xx)/float(2**hutil.p)))) for xx in xt]

        pl.figure(5)
        pl.hold(False)
        pl.plot(xt,mean)
        pl.hold(True)
        pl.plot(x,y,'*')
        pl.fill_between(np.squeeze(xt), mean-np.squeeze(2*np.sqrt(var)),mean+np.squeeze(2*np.sqrt(var)), facecolor = "grey", alpha=0.5)
        pl.plot(xt,yt,'-')
        pl.plot(xt,u/5,'-g')
        pl.plot(maxloc,umax,'*')
        pl.ylim(-5, 5)

        lim_diff = (np.max(y) - np.min(y))/2.

        pl.gca().set_xlim( 0, np.max(x) )
        pl.gca().set_ylim( np.min(y) - lim_diff, np.max(y) + lim_diff )

        #writer.grab_frame()
        pl.pause(0.01) 
Example 22
Project: moodle-mlbackend-python   Author: moodlehq   File: chart.py    GNU General Public License v3.0 5 votes vote down vote up
def store(self, X, y, figure_id=1):
        """Save the learning curve"""

        plt.figure(figure_id)
        plt.xlabel("Training samples")
        plt.ylabel("Error")

        train_sizes, train_scores, test_scores = learning_curve(
            self.classifier, X, y[:, 0])

        train_error_mean = 1 - np.mean(train_scores, axis=1)
        train_scores_std = np.std(train_scores, axis=1)
        test_error_mean = 1 - np.mean(test_scores, axis=1)
        test_scores_std = np.std(test_scores, axis=1)
        plt.grid()

        plt.fill_between(train_sizes, train_error_mean + train_scores_std,
                         train_error_mean - train_scores_std, alpha=0.1,
                         color="r")
        plt.fill_between(train_sizes, test_error_mean + test_scores_std,
                         test_error_mean - test_scores_std, alpha=0.1, color="g")
        plt.plot(train_sizes, train_error_mean, 'o-', color="r",
                 label="Training error")
        plt.plot(train_sizes, test_error_mean, 'o-', color="g",
                 label="Cross-validation error")
        plt.legend(loc="best")

        filepath = os.path.join(self.dirname, 'learning-curve.png')
        plt.savefig(filepath, format='png')

        if not os.path.isfile(filepath):
            return False

        return filepath 
Example 23
Project: bert_lamb_pretrain   Author: goldenbili   File: evaluate-v2.0.py    Apache License 2.0 5 votes vote down vote up
def plot_pr_curve(precisions, recalls, out_image, title):
  plt.step(recalls, precisions, color='b', alpha=0.2, where='post')
  plt.fill_between(recalls, precisions, step='post', alpha=0.2, color='b')
  plt.xlabel('Recall')
  plt.ylabel('Precision')
  plt.xlim([0.0, 1.05])
  plt.ylim([0.0, 1.05])
  plt.title(title)
  plt.savefig(out_image)
  plt.clf() 
Example 24
Project: u8timeseries   Author: unit8co   File: timeseries.py    Apache License 2.0 5 votes vote down vote up
def plot(self, *args, plot_ci=True, **kwargs):
        """
        Currently this is just a wrapper around pd.Series.plot()
        """
        # temporary work-around for the pandas.plot issue
        plt.plot(self.time_index(), self.values(), *args, **kwargs)
        x_label = self.time_index().name
        if x_label is not None and len(x_label) > 0:
            plt.xlabel(x_label)
        # TODO: use pandas plot in the future
        if plot_ci and self._confidence_lo is not None and self._confidence_hi is not None:
            plt.fill_between(self.time_index(), self._confidence_lo.values, self._confidence_hi.values, alpha=0.5) 
Example 25
Project: it-net   Author: wentaoyuan   File: visu_util.py    MIT License 5 votes vote down vote up
def plot_mean_std(figpath, x, y, label):
    mean = np.mean(y, axis=1)
    std = np.std(y, axis=1)
    fig = plt.figure()
    plt.plot(x, mean)
    plt.fill_between(x, mean-std, mean+std, alpha=0.3)
    plt.xlabel('Iteration', fontsize=18)
    plt.xticks(x)
    plt.ylabel(label, fontsize=18)
    plt.ylim(bottom=0)
    plt.tick_params(labelsize=18)
    plt.subplots_adjust(left=0.16, right=0.98, bottom=0.13, top=0.98)
    plt.savefig(figpath)
    plt.close(fig) 
Example 26
Project: ctfdist   Author: ustunb   File: plot_helper.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_descent_profile(results, max_iterations = None):

    max_iterations = None
    # Plot Discrimination Gap Over Time
    sns.set(font_scale = 2, font = 'sans-serif')
    sns.set_style("whitegrid")

    f = plt.figure(figsize = (10, 8))
    ax = plt.gca()

    plot_df = pd.DataFrame(results)
    plot_test_df = plot_df[plot_df['type'] == 'descent'].get(['iteration', 'gap'])

    # determine best iteration
    best_iteration = plot_df.query('is_best_iteration')['iteration'].values[0]
    best_gap = plot_test_df[plot_test_df['iteration'] == best_iteration]['gap'].mean()

    # progress
    plot_test_df = plot_test_df.groupby(['iteration'], as_index = False).agg(['mean', 'min', 'max'])
    plot_test_df.columns = ['.'.join(col).strip() for col in plot_test_df.columns.values]
    plot_test_df = plot_test_df.reset_index()
    plot_test_df.index = plot_test_df['iteration']
    plot_test_df = plot_test_df.drop(columns = ['iteration'])


    plt.fill_between(x = plot_test_df.index.tolist(),
                     y1 = plot_test_df['gap.min'].tolist(),
                     y2 = plot_test_df['gap.max'].tolist(),
                     facecolor = 'green', alpha = 0.5, zorder = 1)

    plt.plot(plot_test_df.get(['gap.mean']), lw = 2, zorder = 2)

    plt.scatter(x = [best_iteration], y = [best_gap], s = [300], marker = 'o', label = 'final iteration', color = 'black', zorder = 3)
    plt.legend(frameon = True, loc = 'upper right', framealpha = 1.0)

    ax.set_xlabel('Iteration')
    ax.set_ylabel('Disparity Metric')
    if max_iterations is not None:
        ax.set_xlim(0, min(max_iterations, max(results['iteration'])))

    return f, ax 
Example 27
Project: LSDMappingTools   Author: LSDtopotools   File: plot_hillslope_morphology.py    MIT License 5 votes vote down vote up
def JoyPlot(HillslopeData,Column,XLabel,Colour,Outfile,BinMin,BinSpacing,BinMax):
    
    CreateFigure(AspectRatio=0.5,FigSizeFormat="small")
    Ax = plt.subplot(111)
    
    Basins = np.sort(HillslopeData.BasinID.unique())
    
    for Basin in range(0,NoBasins):
        #Get hillslopes for basin
        BasinHillslopeData = HillslopeData[HillslopeData.BasinID == Basins[Basin]]

        #create the PDF
        freq, BinEdges = np.histogram(BasinHillslopeData[Column],bins=np.arange(BinMin,BinMax+BinSpacing,BinSpacing))
        BinMidpoints = BinEdges+BinSpacing*0.5
        freq_norm = freq.astype(np.float)/float(np.max(freq))

        #plot, offset by Basin #
        plt.plot(BinMidpoints[:-1],freq_norm-Basin,'k-',linewidth=1)
        plt.fill_between(BinMidpoints[:-1],freq_norm-Basin,-Basin,color=Colour)
    
    if np.abs(BinMin) < np.abs(BinMax):
        plt.xlim(BinMin,BinMax)
    else:
        plt.xlim(BinMax,BinMin)
        BinSpacing *= -1
        
    plt.xlabel(XLabel)
    plt.text(-BinSpacing,0,"North-West",rotation=90,verticalalignment='top')
    plt.text(-BinSpacing,-(NoBasins-1),"South-East",rotation=90,verticalalignment='bottom')
    
    #only display bottom axis
    Ax.spines['right'].set_visible(False)
    Ax.spines['top'].set_visible(False)
    Ax.spines['left'].set_visible(False)
    Ax.yaxis.set_visible(False)
    
    plt.tight_layout(rect=[0.02, 0.02, 0.98, 0.98])
    plt.savefig(PlotDirectory+Outfile, dpi=300)
    plt.clf() 
Example 28
Project: stock-analysis   Author: stefmolin   File: stock_visualizer.py    MIT License 5 votes vote down vote up
def open_to_close(self, figsize=(10, 4)):
        """
        Visualize the daily change from open to close price.

        Parameters:
            - figsize: A tuple of (width, height) for the plot dimensions.

        Returns:
            A matplotlib Figure object.
        """
        is_higher = self.data.close - self.data.open > 0

        fig = plt.figure(figsize=figsize)

        for exclude_mask, color, label in zip(
            (is_higher, np.invert(is_higher)),
            ('g', 'r'),
            ('price rose', 'price fell')
        ):
            plt.fill_between(
                self.data.index,
                self.data.open,
                self.data.close,
                figure=fig,
                where=exclude_mask,
                color=color,
                label=label
            )
        plt.suptitle('Daily price change (open to close)')
        plt.xlabel('date')
        plt.ylabel('price')
        plt.legend()
        plt.close()
        return fig 
Example 29
Project: stock-analysis   Author: stefmolin   File: stock_visualizer.py    MIT License 5 votes vote down vote up
def fill_between_other(self, other_df, figsize=(10, 4)):
        """
        Visualize the difference in closing price between assets.

        Parameters:
            - other_df: The dataframe with the other asset's data.
            - figsize: A tuple of (width, height) for the plot dimensions.

        Returns:
            A matplotlib Figure object.
        """
        is_higher = self.data.close - other_df.close > 0

        fig = plt.figure(figsize=figsize)

        for exclude_mask, color, label in zip(
            (is_higher, np.invert(is_higher)),
            ('g', 'r'),
            ('asset is higher', 'asset is lower')
        ):
            plt.fill_between(
                self.data.index,
                self.data.close,
                other_df.close,
                figure=fig,
                where=exclude_mask,
                color=color,
                label=label
            )
        plt.suptitle(
            'Differential between asset closing price (this - other)'
        )
        plt.legend()
        plt.ylabel('price')
        plt.close()
        return fig 
Example 30
Project: pytorch_pretrained_BERT   Author: Meelfy   File: eval_squad_v2.0.py    Apache License 2.0 5 votes vote down vote up
def plot_pr_curve(precisions, recalls, out_image, title):
  plt.step(recalls, precisions, color='b', alpha=0.2, where='post')
  plt.fill_between(recalls, precisions, step='post', alpha=0.2, color='b')
  plt.xlabel('Recall')
  plt.ylabel('Precision')
  plt.xlim([0.0, 1.05])
  plt.ylim([0.0, 1.05])
  plt.title(title)
  plt.savefig(out_image)
  plt.clf() 
Example 31
Project: Chinese-PreTrained-XLNet   Author: ymcui   File: squad_utils.py    Apache License 2.0 5 votes vote down vote up
def plot_pr_curve(precisions, recalls, out_image, title):
  plt.step(recalls, precisions, color='b', alpha=0.2, where='post')
  plt.fill_between(recalls, precisions, step='post', alpha=0.2, color='b')
  plt.xlabel('Recall')
  plt.ylabel('Precision')
  plt.xlim([0.0, 1.05])
  plt.ylim([0.0, 1.05])
  plt.title(title)
  plt.savefig(out_image)
  plt.clf() 
Example 32
Project: SparseSC   Author: microsoft   File: example_graphs.py    MIT License 5 votes vote down vote up
def sc_diff(est_ret, treatment_date, unit_idx, treatment_date_fit=None):
    fig, ax = plt.subplots(num="sc_diff")
    if isinstance(est_ret.Y, pd.DataFrame):
        Y_target = est_ret.Y.iloc[unit_idx,:]
        Y_target_sc = est_ret.get_sc(treatment_date).iloc[unit_idx,:]
    else:
        Y_target = est_ret.Y[unit_idx,:]
        Y_target_sc = est_ret.get_sc(treatment_date)[unit_idx,:]

    diff = Y_target - Y_target_sc
    if est_ret.ind_CI is not None:
        ind_ci = est_ret.ind_CI[treatment_date]
        if isinstance(est_ret.Y, pd.DataFrame):
            fb_index = Y_target.index
        else:
            fb_index = range(len(ind_ci.ci_low))
        plt.fill_between(
            fb_index,
            diff + ind_ci.ci_low,
            diff + ind_ci.ci_high,
            facecolor="gray",
            label="CI",
        )
    plt.axhline(y=0, linestyle="--")
    plt.plot(diff, "kx--", label="Unit Diff")
    if treatment_date_fit is not None:
        plt.axvline(x=treatment_date, linestyle="--", label="Treatment")
        plt.axvline(x=treatment_date_fit, linestyle=":", label="End Fit Window")
    else:
        plt.axvline(x=treatment_date, linestyle="--")
    plt.xlabel("Time")
    plt.ylabel("Real-SC Outcome Difference")
    plt.legend(loc=1)
    return fig, ax 
Example 33
Project: SparseSC   Author: microsoft   File: example_graphs.py    MIT License 5 votes vote down vote up
def sc_raw(est_ret, treatment_date, unit_idx, treatment_date_fit=None):
    fig, ax = plt.subplots(num="sc_raw")
    if isinstance(est_ret.Y, pd.DataFrame):
        Y_target = est_ret.Y.iloc[unit_idx,:]
        Y_target_sc = est_ret.get_sc(treatment_date).iloc[unit_idx,:]
    else:
        Y_target = est_ret.Y[unit_idx,:]
        Y_target_sc = est_ret.get_sc(treatment_date)[unit_idx,:]

    if est_ret.ind_CI is not None:
        ind_ci = est_ret.ind_CI[treatment_date]
        if isinstance(est_ret.Y, pd.DataFrame):
            fb_index = Y_target.index
        else:
            fb_index = range(len(Y_target_sc))
        plt.fill_between(
            fb_index,
            Y_target_sc + ind_ci.ci_low,
            Y_target_sc + ind_ci.ci_high,
            facecolor="gray",
            label="CI",
        )
    if treatment_date_fit is not None:
        plt.axvline(x=treatment_date, linestyle="--", label="Treatment")
        plt.axvline(x=treatment_date_fit, linestyle=":", label="End Fit Window")
    else:
        plt.axvline(x=treatment_date, linestyle="--")
    plt.plot(Y_target, "bx-", label="Unit")
    plt.plot(Y_target_sc, "gx--", label="SC")
    plt.xlabel("Time")
    plt.ylabel("Outcome")
    plt.legend(loc=1)
    return fig, ax 
Example 34
Project: SparseSC   Author: microsoft   File: example_graphs.py    MIT License 5 votes vote down vote up
def te_plot(est_ret, treatment_date, treatment_date_fit=None):
    fig, ax = plt.subplots(num="te_plot")
    if isinstance(est_ret.pl_res_pre.effect_vec.effect, pd.Series):
        effect_vec = pd.concat((est_ret.pl_res_pre.effect_vec.effect, 
                                est_ret.pl_res_post.effect_vec.effect))
    else:
        effect_vec = np.concatenate((est_ret.pl_res_pre.effect_vec.effect, 
                                     est_ret.pl_res_post.effect_vec.effect))
    if est_ret.pl_res_pre.effect_vec.ci is not None:
        if isinstance(est_ret.pl_res_pre.effect_vec.ci.ci_low, pd.Series):
            ci0 = pd.concat((est_ret.pl_res_pre.effect_vec.ci.ci_low, 
                             est_ret.pl_res_post.effect_vec.ci.ci_low))
            ci1 = pd.concat((est_ret.pl_res_pre.effect_vec.ci.ci_high,
                             est_ret.pl_res_post.effect_vec.ci.ci_high))
            plt.fill_between(ci0.index, ci0, ci1, facecolor="gray", label="CI")
        else:
            ci0 = np.concatenate((est_ret.pl_res_pre.effect_vec.ci.ci_low, 
                                  est_ret.pl_res_post.effect_vec.ci.ci_low))
            ci1 = np.concatenate((est_ret.pl_res_pre.effect_vec.ci.ci_high,
                                  est_ret.pl_res_post.effect_vec.ci.ci_high))
            plt.fill_between(range(len(ci0)), ci0, ci1, facecolor="gray", label="CI")

    plt.plot(effect_vec, "kx--", label="Treated Diff")
    if treatment_date_fit is not None:
        plt.axvline(x=treatment_date, linestyle="--", label="Treatment")
        plt.axvline(x=treatment_date_fit, linestyle=":", label="End Fit Window")
    else:
        plt.axvline(x=treatment_date, linestyle="--")
    plt.axhline(y=0, linestyle="--")
    plt.xlabel("Time")
    plt.ylabel("Real-SC Outcome Difference")
    plt.legend(loc=1)
    return fig, ax 
Example 35
Project: SITE   Author: Osier-Yi   File: plotting.py    MIT License 5 votes vote down vote up
def plot_with_fill(x, y, axis=0, std_error=False, color='r'):
    plt.plot(x, np.mean(y, axis), '.-', linewidth=2, color=color)
    lb, ub = fill_bounds(y, axis=axis, std_error=std_error)
    plt.fill_between(x, lb, ub, linewidth=0, facecolor=color, alpha=0.1) 
Example 36
Project: CoRL2019-DREX   Author: dsbrown1331   File: bc_noise_dataset.py    MIT License 5 votes vote down vote up
def draw_fig(self,log_dir,demo_trajs):
        demo_returns = [np.sum(rewards) for _,_,rewards in demo_trajs]
        demo_ave, demo_std = np.mean(demo_returns), np.std(demo_returns)

        noise_levels = [noise for noise,_ in self.trajs]
        returns = np.array([[np.sum(rewards) for _,_,rewards in agent_trajs] for _,agent_trajs in self.trajs])

        random_agent = RandomAgent(self.env.action_space)
        random_returns = [np.sum(gen_traj(self.env,random_agent,-1)[2]) for _ in range(20)]
        random_ave, random_std = np.mean(random_returns), np.std(random_returns)

        from_to = [np.min(noise_levels), np.max(noise_levels)]

        plt.figure()
        plt.fill_between(from_to,
                         [demo_ave - demo_std, demo_ave - demo_std], [demo_ave + demo_std, demo_ave + demo_std], alpha = 0.3)
        plt.plot(from_to,[demo_ave, demo_ave], label='demos')

        plt.fill_between(noise_levels,
                         np.mean(returns, axis=1)-np.std(returns, axis=1), np.mean(returns, axis=1) + np.std(returns, axis=1), alpha = 0.3)
        plt.plot(noise_levels, np.mean(returns, axis = 1),'-.', label="bc")

        #plot the average of pure noise in dashed line for baseline
        plt.fill_between(from_to,
                         [random_ave - random_std, random_ave - random_std], [random_ave + random_std, random_ave + random_std], alpha = 0.3)
        plt.plot(from_to,[random_ave, random_ave], '--', label='random')

        plt.legend(loc="best")
        plt.xlabel("Epsilon")
        #plt.xticks([0.0, 0.25, 0.5, 0.75, 1.0])
        plt.ylabel("Return")
        plt.tight_layout()
        plt.savefig(os.path.join(log_dir,"degredation_plot.pdf"))
        plt.close() 
Example 37
Project: vogel   Author: usaa   File: stats.py    Apache License 2.0 5 votes vote down vote up
def plot_recall(actual, prediction, plt_size=(7, 7)):
    """
    Precision-Recall plot for Bimodal targets.
    
    Args:
    
    actual: 
        list: target values
    perdicted: 
        list: predicted values
    plt_size: (7.0, 7.0)
        tuple: (width, height)
    """
    _plt.rcParams['figure.figsize'] = plt_size

    average_precision = _metrics.average_precision_score(actual, prediction)

    precision, recall, _ = _metrics.precision_recall_curve(actual, prediction)

    _plt.step(recall, precision, color='b', alpha=0.2, where='post')
    _plt.fill_between(recall, precision, step='post', alpha=0.2, color='b')

    _plt.xlabel('Recall')
    _plt.ylabel('Precision')
    _plt.ylim([0.0, 1.05])
    _plt.xlim([0.0, 1.0])
    _plt.title('2-class Precision-Recall curve: AP={0:0.2f}'.format(
        average_precision))

    _plt.show() 
Example 38
Project: spatial_patterns   Author: sim-web   File: plotting.py    GNU General Public License v3.0 5 votes vote down vote up
def mean_output_rate_time_evolution(self, end_frame=None,
                                        n_individual_plots=0):
        # mpl.style.use('ggplot')
        output_rates = self.get_output_rates_over_all_psps()
        mean = np.nanmean(output_rates, axis=0)[:end_frame]
        std = np.nanstd(output_rates, axis=0)[:end_frame]
        time = (np.arange(0, len(output_rates[0]))
                * self.params['sim']['every_nth_step_weights']
                * self.params['sim']['dt'])[:end_frame]
        plt.plot(time, mean)
        plt.fill_between(time,
                         mean + std,
                         mean - std, alpha=0.5)
        # Plot some invidivual traces
        for j in np.arange(n_individual_plots):
            plt.plot(time, output_rates[j][:end_frame])
        # plt.ylim([-0.5, 1.0])
        plt.ticklabel_format(axis='x', style='sci', scilimits=(0, 0)) 
Example 39
Project: tgirt-dna-seq   Author: wckdouglas   File: plotIsize.py    MIT License 5 votes vote down vote up
def plotFigure(figurename, df):
    x_axis_range = np.arange(0,301,50)
    with sns.plotting_context('paper',font_scale=1.5):
        p = sns.FacetGrid(data=df, col = 'samplename', col_wrap = 4)
    p.map(plt.plot, 'isize', 'normCount')
    p.map(plt.fill_between, 'isize','normCount')
    p.set_titles('{col_name}')
    p.set_xticklabels(rotation=60)
    p.set(xlabel ='Insert Size', ylabel = 'Relative abundance')
    p.savefig(figurename)
    print 'Saved %s' %figurename
    return 0 
Example 40
Project: tgirt-dna-seq   Author: wckdouglas   File: plotIsizeBam.py    MIT License 5 votes vote down vote up
def plotFigure(figurename, df):
    with sns.plotting_context('paper',font_scale=1.5):
        plt.figure()
        print 'Normalized counts'
        p = sns.FacetGrid(data=df, col = 'samplename', col_wrap = 4,sharey=False)
        p.map(plt.plot, 'isize', 'normCount')
        p.map(plt.fill_between, 'isize', 'normCount')
        p.set_titles('{col_name}')
        p.savefig(figurename)
        print 'Saved %s' %figurename
    return 0 
Example 41
Project: tgirt-dna-seq   Author: wckdouglas   File: plotIsizeBam.py    MIT License 5 votes vote down vote up
def plotFigure(figurename, df):
    with sns.plotting_context('paper',font_scale=1.5):
        plt.figure()
        print 'Normalized counts'
        p = sns.FacetGrid(data=df, col = 'samplename', col_wrap = 5,sharey=False)
        p.map(plt.plot, 'isize', 'normCount')
        p.map(plt.fill_between, 'isize', 'normCount')
        p.set_titles('{col_name}')
        p.set(xlabel='Insert size',ylabel='Normalized count')
        p.savefig(figurename)
        print 'Saved %s' %figurename
    return 0 
Example 42
Project: survival   Author: ryu577   File: compare_survival_approaches.py    MIT License 5 votes vote down vote up
def non_parametric_comparison():
	num_samples = []
	threshs = []
	tru_opt = 0.0
	for filename in os.listdir('./data/'):
		dd = genfromtxt('./data/' + filename)
		samples = dd[1]
		num_samples.append(samples)
		tru_thresh = dd[4]
		non_prm = dd[5]
		threshs.append(non_prm)
		tru_opt = dd[4]
	plt.plot(num_samples, threshs, 'ro')
	num_samples = np.array(num_samples)
	threshs = np.array(threshs)
	stds = []
	means = []
	for i in np.unique(num_samples):
		stds.append(np.std(threshs[num_samples==i]))
		means.append(np.mean(threshs[num_samples==i]))
	means = np.array(means)
	stds = np.array(stds)
	plt.plot(np.unique(num_samples), means, 'k-')
	plt.axhline(tru_opt, color='g')
	plt.fill_between(np.unique(num_samples), means+stds, means-stds)
	plt.xlabel('Number of samples generated')
	plt.ylabel('Optimum threshold values')
	plt.show() 
Example 43
Project: fisher-rao-regularization   Author: brain-research   File: plot_utils.py    Apache License 2.0 5 votes vote down vote up
def draw_plot(data_mean, data_std, label, title, color, factor):
  """Draws plot with two standard deviation error bars."""
  num_iter = np.multiply(factor, range(0, len(data_mean)))

  low_fill = np.subtract(data_mean, np.multiply(2., data_std))
  high_fill = np.add(data_mean, np.multiply(2., data_std))
  plt.plot(num_iter, data_mean, color=color, alpha=ALPHA1, label=label)
  plt.fill_between(num_iter, low_fill, high_fill, color=color, lw=0,
                   alpha=ALPHA2)

  plt.xlabel("# iter")
  plt.ylabel(title)
  plt.legend(loc="best") 
Example 44
Project: vnpy_crypto   Author: birforce   File: test_predict_functional.py    MIT License 5 votes vote down vote up
def test_lm_contrast(self):

        np.random.seed(542)
        n = 200
        x1 = np.random.normal(size=n)
        x2 = np.random.normal(size=n)
        x3 = np.random.normal(size=n)
        y = x1 + 2*x2 + x3 - x1*x2 + x2*x3 + np.random.normal(size=n)

        df = pd.DataFrame({"y": y, "x1": x1, "x2": x2, "x3": x3})

        fml = "y ~ x1 + x2 + x3 + x1*x2 + x2*x3"
        model = sm.OLS.from_formula(fml, data=df)
        result = model.fit()

        values = {"x2": 1, "x3": 1} # y = 4
        values2 = {"x2": 0, "x3": 0} # y = x1
        pr, cb, fvals = predict_functional(result, "x1", values=values,
                                           values2=values2, ci_method='scheffe')

        plt.clf()
        fig = plt.figure()
        ax = plt.axes([0.1, 0.1, 0.67, 0.8])
        plt.plot(fvals, pr, '-', label="Estimate", color='orange', lw=4)
        plt.plot(fvals, 4 - fvals, '-', label="Truth", color='lime', lw=4)
        plt.fill_between(fvals, cb[:, 0], cb[:, 1], color='grey')
        ha, lb = ax.get_legend_handles_labels()
        leg = plt.figlegend(ha, lb, "center right")
        leg.draw_frame(False)
        plt.xlabel("Focus variable", size=15)
        plt.ylabel("Mean contrast", size=15)
        plt.title("Linear model contrast")
        self.close_or_save(fig) 
Example 45
Project: vnpy_crypto   Author: birforce   File: test_predict_functional.py    MIT License 5 votes vote down vote up
def test_glm_formula_contrast(self):

        np.random.seed(542)
        n = 50
        x1 = np.random.normal(size=n)
        x2 = np.random.normal(size=n)
        x3 = np.random.normal(size=n)
        mn = 5 + 0.1*x1 + 0.1*x2 + 0.1*x3 - 0.1*x1*x2
        y = np.random.poisson(np.exp(mn), size=len(mn))

        df = pd.DataFrame({"y": y, "x1": x1, "x2": x2, "x3": x3})

        fml = "y ~ x1 + x2 + x3 + x1*x2"
        model = sm.GLM.from_formula(fml, data=df, family=sm.families.Poisson())
        result = model.fit()

        values = {"x2": 1, "x3": 1} # y = 5.2
        values2 = {"x2": 0, "x3": 0} # y = 5 + 0.1*x1
        pr, cb, fvals = predict_functional(result, "x1", values=values,
                                           values2=values2, ci_method='simultaneous')

        plt.clf()
        fig = plt.figure()
        ax = plt.axes([0.1, 0.1, 0.67, 0.8])
        plt.plot(fvals, pr, '-', label="Estimate", color='orange', lw=4)
        plt.plot(fvals, 0.2 - 0.1*fvals, '-', label="Truth", color='lime', lw=4)
        plt.fill_between(fvals, cb[:, 0], cb[:, 1], color='grey')
        ha, lb = ax.get_legend_handles_labels()
        leg = plt.figlegend(ha, lb, "center right")
        leg.draw_frame(False)
        plt.xlabel("Focus variable", size=15)
        plt.ylabel("Linear predictor contrast", size=15)
        plt.title("Poisson regression contrast")
        self.close_or_save(fig) 
Example 46
Project: garage   Author: rlworkgroup   File: benchmark_helper.py    MIT License 5 votes vote down vote up
def plot_average_over_trials(csvs, ys, plt_file, env_id, x_label, y_label,
                             names):
    """Plot mean and confidence area of benchmark from csv files of algorithms.

    x-value is step and y-value depends on the parameter ys.
    Calculate mean and std for the y values and draw a line using mean and
    show confidence area using std.

    Step length of every csv data ans ys should be same.

    Args:
        csvs (list[list]): A list of list of csvs which contains all csv files
            for each algorithms in the task.
        ys (list[int]): A list of Y column names of algorithms csv.
        plt_file (string): Path of the plot png file.
        env_id (string): String contains the id of the environment. (for title)
        x_label (string): label for x axis of the plot
        y_label (string): label for y axis of the plot
        names (list[string]): labels for each line in the graph

    """
    assert all(len(x) == len(csvs[0]) for x in csvs)

    for trials, y, name in zip(csvs, ys, names):
        y_vals = np.array([np.array(pd.read_csv(t)[y]) for t in trials])
        y_mean, y_std = y_vals.mean(axis=0), y_vals.std(axis=0)

        # pylint: disable=unsubscriptable-object
        plt.plot(list(range(y_vals.shape[-1])), y_mean, label=name)
        # pylint: disable=unsubscriptable-object
        plt.fill_between(list(range(y_vals.shape[-1])), (y_mean - y_std),
                         (y_mean + y_std),
                         alpha=.1)

    plt.legend()
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    plt.title(env_id)

    plt.savefig(plt_file)
    plt.close() 
Example 47
Project: isic2018-skin-lesion-classifier-tensorflow   Author: abhishekrana   File: utils.py    Apache License 2.0 5 votes vote down vote up
def gen_precision_recall_curve(config, labels_gt, labels_prob, mode_ds):


    labels_map_inv = {v: k for k, v in config.labels.items()}
    plot_path = os.path.join(config.output_path, config.exp_name, config.exp_cascade_name, 'plots', mode_ds)
    os.makedirs(plot_path, exist_ok=True)

    for class_idx in range(config.num_classes):

        labels_gt_bin = [1 if x==class_idx else 0 for x in labels_gt]
        labels_prob_bin = [x[class_idx] for x in labels_prob]

        average_precision = average_precision_score(labels_gt_bin, labels_prob_bin)
        precision, recall, thresholds = precision_recall_curve(labels_gt_bin, labels_prob_bin)

        for p, r, t in zip(precision, recall, thresholds):
            print('Precision:{:0.2}, Recall:{:0.2}, Thresholds:{:0.2}'.format(p, r, t))

        plt.figure(figsize=(10,10))
        plt.plot(recall, precision)
        plt.step(recall, precision, color='b', alpha=0.2, where='post')
        plt.fill_between(recall, precision, step='post', alpha=0.2, color='b')

        plt.xlabel('Recall')
        plt.ylabel('Precision')
        plt.title('2-class Precision-Recall curve: AP={0:0.2f} [{1}]'.format(average_precision, labels_map_inv[class_idx]))

        img_path_name = os.path.join(plot_path, 'pr_curve_' + labels_map_inv[class_idx] + '.jpg')
        logging.debug('img_path_name {}'.format(img_path_name))

        plt.savefig(img_path_name)
        plt.close() 
Example 48
Project: ge-vae   Author: tonyduan   File: test.py    MIT License 5 votes vote down vote up
def plot_prior_histograms(model, dataloader):
    z = []
    for E_batch, A_batch, V_batch in tqdm(iter(dataloader)):
        z_batch, _, _ = model.forward(E_batch, A_batch, V_batch)
        z += [np.vstack(z_batch.data.numpy())]
    z = np.vstack(z)
    x_axis = np.linspace(-4, 4, 200)
    embedding_dim = z.shape[-1]
    plt.figure(figsize = (embedding_dim, 6))
    for i in range(embedding_dim):
        plt.subplot(3, embedding_dim // 2, i + 1)
        density = sp.stats.gaussian_kde(z[:, i], "silverman")
        plt.plot(x_axis, density(x_axis))
        plt.fill_between(x_axis, 0, density(x_axis), alpha=0.2)
        plt.title(f"Dimension {i + 1}")
    plt.subplot(3, embedding_dim // 2, embedding_dim + 1)
    density = sp.stats.gaussian_kde(z.flatten(), "silverman")
    plt.plot(x_axis, density(x_axis))
    plt.fill_between(x_axis, 0, density(x_axis), alpha=0.2)
    plt.title("Aggregate")
    plt.subplot(3, embedding_dim // 2, embedding_dim + 2)
    density = sp.stats.norm.pdf(x_axis)
    plt.plot(x_axis, density)
    plt.fill_between(x_axis, 0, density, alpha=0.2)
    plt.title("Ideal")
    plt.tight_layout() 
Example 49
Project: Cursive_handwriting_recognition   Author: RiteshKH   File: segmentation.py    Apache License 2.0 5 votes vote down vote up
def histogram(letter2, upper_baseline, lower_baseline):
    ##------------Making Histograms (Default)------------------------######
    cropped = letter2[upper_baseline:lower_baseline,0:w]
    plt.imshow(cropped)
    plt.show()
    colcnt = np.sum(cropped==255, axis=0)
    x = list(range(len(colcnt)))
    plt.plot(colcnt)
    plt.fill_between(x, colcnt, 1, facecolor='blue', alpha=0.5)
    plt.show()  
    return colcnt     
####---------------------------------------------------------------------------#####

# In[Visualize]:
##*******************************************************************************### 
Example 50
Project: ble5-nrf52-mac   Author: tomasero   File: mlab.py    MIT License 5 votes vote down vote up
def offset_line(y, yerr):
    """
    Offsets an array *y* by +/- an error and returns a tuple
    (y - err, y + err).

    The error term can be:

    * A scalar. In this case, the returned tuple is obvious.
    * A vector of the same length as *y*. The quantities y +/- err are computed
      component-wise.
    * A tuple of length 2. In this case, yerr[0] is the error below *y* and
      yerr[1] is error above *y*. For example::

        import numpy as np
        import matplotlib.pyplot as plt

        x = np.linspace(0, 2*np.pi, num=100, endpoint=True)
        y = np.sin(x)
        y_minus, y_plus = mlab.offset_line(y, 0.1)
        plt.plot(x, y)
        plt.fill_between(x, y_minus, y2=y_plus)
        plt.show()

    """
    if cbook.is_numlike(yerr) or (cbook.iterable(yerr) and
                                  len(yerr) == len(y)):
        ymin = y - yerr
        ymax = y + yerr
    elif len(yerr) == 2:
        ymin, ymax = y - yerr[0], y + yerr[1]
    else:
        raise ValueError("yerr must be scalar, 1xN or 2xN")
    return ymin, ymax