Python matplotlib.pyplot.legend() Examples

The following are code examples for showing how to use matplotlib.pyplot.legend(). 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: keras-anomaly-detection   Author: chen0040   File: plot_utils.py    MIT License 7 votes vote down vote up
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() 
Example 2
Project: ReinforcementLearningBookExamples   Author: Shawn-Guo-CN   File: 1TenArmedBandits.py    GNU General Public License v3.0 7 votes vote down vote up
def gradient_algorithm(num_bandits, episode_length):
    agents = [Agent(gradient=True, step_size=0.1, gradient_baseline=True),
              Agent(gradient=True, step_size=0.1, gradient_baseline=False),
              Agent(gradient=True, step_size=0.4, gradient_baseline=True),
              Agent(gradient=True, step_size=0.4, gradient_baseline=False)]

    best_action_counts, _ = play_game(num_bandits, episode_length, agents, 4.)
    labels = ['alpha = 0.1, with baseline',
              'alpha = 0.1, without baseline',
              'alpha = 0.4, with baseline',
              'alpha = 0.4, without baseline']
    global figure_index
    plt.figure(figure_index)
    figure_index += 1
    for i in range(0, len(agents)):
        plt.plot(best_action_counts[i], label=labels[i])
    plt.xlabel('Steps')
    plt.ylabel('% Optimal action')
    plt.legend()


# following three example functions are for understanding the playing procedure
# following is for testing whether agent and bandit are rightly implemented 
Example 3
Project: Stock-Price-Prediction   Author: dhingratul   File: helper.py    MIT License 6 votes vote down vote up
def plot_mul(Y_hat, Y, pred_len):
    """
    PLots the predicted data versus true data

    Input: Predicted data, True Data, Length of prediction
    Output: return plot

    Note: Run from timeSeriesPredict.py
    """
    fig = plt.figure(facecolor='white')
    ax = fig.add_subplot(111)
    ax.plot(Y, label='Y')
    # Print the predictions in its respective series-length
    for i, j in enumerate(Y_hat):
        shift = [None for p in range(i * pred_len)]
        plt.plot(shift + j, label='Y_hat')
        plt.legend()
    plt.show() 
Example 4
Project: neural-fingerprinting   Author: StephanZheng   File: util.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def compute_roc(y_true, y_pred, plot=False):
    """
    TODO
    :param y_true: ground truth
    :param y_pred: predictions
    :param plot:
    :return:
    """
    fpr, tpr, _ = roc_curve(y_true, y_pred)
    auc_score = auc(fpr, tpr)
    if plot:
        plt.figure(figsize=(7, 6))
        plt.plot(fpr, tpr, color='blue',
                 label='ROC (AUC = %0.4f)' % auc_score)
        plt.legend(loc='lower right')
        plt.title("ROC Curve")
        plt.xlabel("FPR")
        plt.ylabel("TPR")
        plt.show()

    return fpr, tpr, auc_score 
Example 5
Project: neural-fingerprinting   Author: StephanZheng   File: util.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def compute_roc_rfeinman(probs_neg, probs_pos, plot=False):
    """
    TODO
    :param probs_neg:
    :param probs_pos:
    :param plot:
    :return:
    """
    probs = np.concatenate((probs_neg, probs_pos))
    labels = np.concatenate((np.zeros_like(probs_neg), np.ones_like(probs_pos)))
    fpr, tpr, _ = roc_curve(labels, probs)
    auc_score = auc(fpr, tpr)
    if plot:
        plt.figure(figsize=(7, 6))
        plt.plot(fpr, tpr, color='blue',
                 label='ROC (AUC = %0.4f)' % auc_score)
        plt.legend(loc='lower right')
        plt.title("ROC Curve")
        plt.xlabel("FPR")
        plt.ylabel("TPR")
        plt.show()

    return fpr, tpr, auc_score 
Example 6
Project: tensorflow-DeepFM   Author: ChenglongChen   File: main.py    MIT License 6 votes vote down vote up
def _plot_fig(train_results, valid_results, model_name):
    colors = ["red", "blue", "green"]
    xs = np.arange(1, train_results.shape[1]+1)
    plt.figure()
    legends = []
    for i in range(train_results.shape[0]):
        plt.plot(xs, train_results[i], color=colors[i], linestyle="solid", marker="o")
        plt.plot(xs, valid_results[i], color=colors[i], linestyle="dashed", marker="o")
        legends.append("train-%d"%(i+1))
        legends.append("valid-%d"%(i+1))
    plt.xlabel("Epoch")
    plt.ylabel("Normalized Gini")
    plt.title("%s"%model_name)
    plt.legend(legends)
    plt.savefig("./fig/%s.png"%model_name)
    plt.close()


# load data 
Example 7
Project: deep-learning-note   Author: wdxtub   File: 6_bias_variance.py    MIT License 6 votes vote down vote up
def plot_learning_curve(X, y, Xval, yval, l=0):
    training_cost, cv_cost = [], []
    m = X.shape[0]

    for i in range(1, m + 1):
        # regularization applies here for fitting parameters
        res = linear_regression_np(X[:i, :], y[:i], l=l)

        # remember, when you compute the cost here, you are computing
        # non-regularized cost. Regularization is used to fit parameters only
        tc = cost(res.x, X[:i, :], y[:i])
        cv = cost(res.x, Xval, yval)

        training_cost.append(tc)
        cv_cost.append(cv)

    plt.plot(np.arange(1, m + 1), training_cost, label='training cost')
    plt.plot(np.arange(1, m + 1), cv_cost, label='cv cost')
    plt.legend(loc=1) 
Example 8
Project: deep-learning-note   Author: wdxtub   File: simulate_sin.py    MIT License 6 votes vote down vote up
def run_eval(sess, test_X, test_y):
    ds = tf.data.Dataset.from_tensor_slices((test_X, test_y))
    ds = ds.batch(1)
    X, y = ds.make_one_shot_iterator().get_next()

    with tf.variable_scope("model", reuse=True):
        prediction, _, _ = lstm_model(X, [0.0], False)
        predictions = []
        labels = []
        for i in range(TESTING_EXAMPLES):
            p, l = sess.run([prediction, y])
            predictions.append(p)
            labels.append(l)

    predictions = np.array(predictions).squeeze()
    labels = np.array(labels).squeeze()
    rmse = np.sqrt(((predictions-labels) ** 2).mean(axis=0))
    print("Mean Square Error is: %f" % rmse)

    plt.figure()
    plt.plot(predictions, label='predictions')
    plt.plot(labels, label='real_sin')
    plt.legend()
    plt.show() 
Example 9
Project: ReinforcementLearningBookExamples   Author: Shawn-Guo-CN   File: 1TenArmedBandits.py    GNU General Public License v3.0 6 votes vote down vote up
def epsilon_greedy(num_bandits, episode_length):
    epsilons = [0., 0.1, 0.01]
    agents = []
    for ep_idx, ep in enumerate(epsilons):
        agents.append(Agent(epsilon=ep, sample_average=True))
    best_action_counts, average_rewards = play_game(num_bandits, episode_length, agents)
    global figure_index
    plt.figure(figure_index)
    figure_index += 1
    for eps, counts in zip(epsilons, best_action_counts):
        plt.plot(counts, label='epsilon = ' + str(eps))
    plt.xlabel('Steps')
    plt.ylabel('% optimal action')
    plt.legend()
    plt.figure(figure_index)
    figure_index += 1
    for eps, rewards in zip(epsilons, average_rewards):
        plt.plot(rewards, label='epsilon = ' + str(eps))
    plt.xlabel('Steps')
    plt.ylabel('average reward')
    plt.legend()


# generate figure 2.3 
Example 10
Project: ReinforcementLearningBookExamples   Author: Shawn-Guo-CN   File: 1TenArmedBandits.py    GNU General Public License v3.0 6 votes vote down vote up
def play_nbandit_1agent(num_bandit, time_step):
    agent = Agent(epsilon=0.1, sample_average=True)

    bandits = [Bandit() for _ in range(num_bandit)]

    rewards = np.zeros(time_step, dtype='float')
    best_action_counts = np.zeros(time_step)

    for bandit_idx, bandit in enumerate(bandits):
        agent.reset()
        for t in range(time_step):
            action = agent.get_action()
            reward = bandit.take_arm(action)
            agent.update_values(action, reward)
            rewards[t] += reward
            if action == bandit.best_action:
                best_action_counts[t] += 1

    plt.figure(1)
    plt.plot(rewards / num_bandit, label='rewards')
    plt.plot(best_action_counts / num_bandit, label='best action counts')
    plt.legend() 
Example 11
Project: beta3_IRT   Author: yc14600   File: plots.py    MIT License 6 votes vote down vote up
def plot_noisy_points(xtest, disc=None):
    sns.set_context('paper')
    cls = sns.color_palette("BuGn_r")
    lgd = []
    f = plt.figure()
    
    plt.scatter(xtest.x[xtest.noise==0],xtest.y[xtest.noise==0],facecolors='none',edgecolors='k',s=60)
    lgd.append('non-noise item')
    plt.scatter(xtest.x[xtest.noise>0],xtest.y[xtest.noise>0],c=cls[3],s=60)
    lgd.append('noise item')
    if not disc is None:
        plt.scatter(xtest.x[disc<0],xtest.y[disc<0],c=cls[0],marker='+',facecolors='none')
        lgd.append('detected noise item')
    
    plt.title('True and detected noise items')
    l = plt.legend(lgd,frameon=True,fontsize=12)
    l.get_frame().set_edgecolor('g')
    return f 
Example 12
Project: beta3_IRT   Author: yc14600   File: plots.py    MIT License 6 votes vote down vote up
def plot_item_parameters_corr(irt_prob_avg,difficulty,noise,disc=None):
    sns.set_context('paper')
    cls = sns.color_palette("BuGn_r")
    lgd = []

    f = plt.figure()
    plt.xlim([0.,1.])
    plt.ylim([0.,1.])
    
    
    plt.scatter(irt_prob_avg[noise>0],difficulty[noise>0],c=cls[3],s=60)
    lgd.append('noise item')
    if not disc is None:
        plt.scatter(irt_prob_avg[disc<0],difficulty[disc<0],c=cls[0],marker='+',facecolors='none')
        lgd.append('detected noise item')
    plt.scatter(irt_prob_avg[noise==0],difficulty[noise==0],facecolors='none',edgecolors='k',s=60)
    lgd.append('non-noise item')

    plt.title('Correlation between difficulty and response')
    plt.xlabel('Average response',fontsize=14)
    plt.ylabel('Difficulty',fontsize=14)
    l=plt.legend(lgd,frameon=True,fontsize=12)
    l.get_frame().set_edgecolor('g')
    return f 
Example 13
Project: beta3_IRT   Author: yc14600   File: plots.py    MIT License 6 votes vote down vote up
def vis_performance(gather_prec,gather_recal,path,asd='[email protected]',vtype='nfrac'):
    fig = plt.figure()      
    plt.plot(gather_recal.index, gather_recal.mean(axis=1),marker='o')
    plt.plot(gather_prec.index, gather_prec.mean(axis=1),marker='^')

    plt.errorbar(gather_recal.index, gather_recal.mean(axis=1), gather_recal.std(axis=1), linestyle='None')
    plt.errorbar(gather_prec.index, gather_prec.mean(axis=1), gather_prec.std(axis=1), linestyle='None')
    
    if vtype=='nfrac':
        plt.title('Precision and recall under different noise fractions')
        plt.xlabel('Noise fraction (percentile)')
        plt.ylim(-0.05,1.1)
        plt.yticks(np.arange(0,1.2,0.2))
        plt.legend(['Recall','Precision'],loc=0)
        plt.savefig(path+'gathered_dnoise_performance_nfrac_'+asd+'.pdf') 
    elif vtype=='astd':
        plt.title('Precision and recall under different prior SD')
        plt.xlabel('Prior standard deviation of discrimination')
        plt.xlim(0.5,3.25)
        plt.ylim(-0.05,1.1)
        plt.yticks(np.arange(0,1.2,0.2))
        plt.legend(['Recall','Precision'],loc=0)
        plt.savefig(path+'gathered_dnoise_performance_asd_nfrac20.pdf')
    plt.close(fig) 
Example 14
Project: CNN_based_indoor_localization   Author: weimengmeng1999   File: epoch_graph.py    GNU General Public License v3.0 6 votes vote down vote up
def loss_plot(self, loss_type):
        iters = range(len(self.losses[loss_type]))
        plt.figure()
        # acc
        plt.plot(iters, self.accuracy[loss_type], 'r', label='train acc')
        # loss
        plt.plot(iters, self.losses[loss_type], 'g', label='train loss')
        if loss_type == 'epoch':
            # val_acc
            plt.plot(iters, self.val_acc[loss_type], 'b', label='val acc')
            # val_loss
            plt.plot(iters, self.val_loss[loss_type], 'k', label='val loss')
        plt.grid(True)
        plt.xlabel(loss_type)
        plt.ylabel('acc-loss')
        plt.legend(loc="upper right")
        plt.show() 
Example 15
Project: RNASEqTool   Author: armell   File: mpld3_rendering.py    MIT License 6 votes vote down vote up
def plot_distribution_for_genes(data, genes):
    distributions = generate_distribution_for_genes(data, genes)
    sns.set_palette("deep", desat=.6)
    i = 0
    hist = None
    fig = plt.figure()
    for dist in distributions:
        plt.hist(dist, alpha=0.5, label=genes[i])
        i += 1

    plt.legend()
    plt.title(genes.__str__() + " distribution")

    #script, div = components(mpl.to_bokeh(), CDN)

    #return {"js": script, "html": div}
    plugins.connect(fig, extra.InteractiveLegendPlugin())
    return fig_to_html(fig) 
Example 16
Project: cs294-112_hws   Author: xuwd11   File: plot_part1.py    MIT License 6 votes vote down vote up
def plot_12(data):
    r1, r2, r3, r4 = data
    plt.figure()
    add_plot(r1, 'MeanReward100Episodes');
    add_plot(r1, 'BestMeanReward', 'vanilla DQN');
    add_plot(r2, 'MeanReward100Episodes');
    add_plot(r2, 'BestMeanReward', 'double DQN');
    plt.xlabel('Time step');
    plt.ylabel('Reward');
    plt.legend();
    plt.savefig(
        os.path.join('results', 'p12.png'),
        bbox_inches='tight',
        transparent=True,
        pad_inches=0.1
    ) 
Example 17
Project: cs294-112_hws   Author: xuwd11   File: plot_part1.py    MIT License 6 votes vote down vote up
def plot_13(data):
    r1, r2, r3, r4 = data
    plt.figure()
    add_plot(r3, 'MeanReward100Episodes');
    add_plot(r3, 'BestMeanReward', 'gamma = 0.9');
    add_plot(r2, 'MeanReward100Episodes');
    add_plot(r2, 'BestMeanReward', 'gamma = 0.99');
    add_plot(r4, 'MeanReward100Episodes');
    add_plot(r4, 'BestMeanReward', 'gamma = 0.999');
    plt.legend();
    plt.xlabel('Time step');
    plt.ylabel('Reward');
    plt.savefig(
        os.path.join('results', 'p13.png'),
        bbox_inches='tight',
        transparent=True,
        pad_inches=0.1
    ) 
Example 18
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 19
Project: HandPostureTranslator   Author: Wissben   File: ArchGenerators.py    GNU General Public License v3.0 6 votes vote down vote up
def plotCallback(variator: Variator, model: Model):
    # get last history
    pathlib.Path('Graphs').mkdir(parents=True, exist_ok=True)
    history = variator.histories[-1]
    # summarize history for accuracy
    fig = plt.figure()
    plt.plot(history.history['acc'])
    plt.plot(history.history['val_acc'])
    plt.title(variator.currentParameters['modelName'] + ' accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    fig.savefig("Graphs/"+variator.currentParameters['modelName'] + '.png', dpi=fig.dpi)
    # from PIL import Image
    # Image.open(variator.currentParameters['modelName']+'.png').show()
    # plt.show()
    # plot(plt) 
Example 20
Project: kicker-module   Author: EvanTheB   File: graph.py    GNU General Public License v3.0 5 votes vote down vote up
def graph_skill_topn(p, g, ladder, n):
    def get_names_skill(data):
        ret = []
        for l in data:
            ret.append((l.name, l.extra[1][1]))
        return ret

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

    graph_data = []
    for i in range(1, len(g) + 1):
        data = ladder.process(p, g[0:i])
        graph_data.append(get_names_skill(data))

    names = sorted(get_top_n(graph_data[-1]))
    graph_data = [sorted(x) for x in get_subset(graph_data, names)]

    ys = data_to_yarr(graph_data)
    for i in range(len(ys)):
        y = np.array(ys[i])
        plt.plot(range(len(y)), y, label = names[i])
    plt.legend(loc=3, ncol=len(names)/2)
    pylab.savefig('graph_skill_topn.svg')
 #   plt.show() 
Example 21
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 22
Project: projection-methods   Author: akshayka   File: circles.py    GNU General Public License v3.0 5 votes vote down vote up
def main():
    x = cp.Variable(2)
    r = 10
    left_circle = ConvexSet(x, [cp.square(x[0] + r) + cp.square(x[1]) <= r**2])
    right_circle = ConvexSet(x, [cp.square(x[0] - r) + cp.square(x[1]) <= r**2])

    problem = FeasibilityProblem([left_circle, right_circle], np.array([0, 0]))

    initial_iterate = np.array([0, r])
    max_iters = 10

    plt.figure()
    plot_circles(r)
    solver = AltP(max_iters=max_iters, initial_iterate=initial_iterate)
    solver.solve(problem)
    plot_iterates(solver.all_iterates, 'Alternating Projections')

    solver = Polyak(max_iters=max_iters, initial_iterate=initial_iterate)
    it, res, status = solver.solve(problem)
    plot_iterates(it, 'Polyak\'s acceleration')

    solver = APOP(max_iters=max_iters, initial_iterate=initial_iterate,
        average=False)
    it, res, status = solver.solve(problem)
    plot_iterates(it, 'APOP')
    plt.title('Motivating APOP: Circles')
    plt.legend()
    plt.show() 
Example 23
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 24
Project: wikilinks   Author: trovdimi   File: normalized_entropy.py    MIT License 5 votes vote down vote up
def plot_entropy_ccdf():
    entropy = read_pickle('output/normalized_entropy.obj')


    fig = plt.figure()
    ax = fig.add_subplot(111)


    powerlaw.plot_ccdf(entropy, ax, label='normalized entropy')
    # further plotting
    ax.set_xlabel("Normalized entropy e")
    ax.set_ylabel("Pr(X>=e)")
    plt.legend(fancybox=True, loc='lower left', ncol=1,prop={'size':5})

    plt.tight_layout()
    plt.savefig('output/normalized_entropy_distribution_ccdf.pdf')

    fig = plt.figure()
    ax = fig.add_subplot(111)

    powerlaw.plot_cdf(entropy, ax, label='normalized entropy',color='r')
    # further plotting
    ax.set_xlabel("Normalized entropy e")
    ax.set_ylabel("Pr(X<=e)")
    plt.legend(fancybox=True, loc='lower left', ncol=1,prop={'size':5})

    plt.tight_layout()
    plt.savefig('output/normalized_entropy_distribution_cdf.pdf') 
Example 25
Project: OpenAPS   Author: medicinexlab   File: bglomb.py    MIT License 5 votes vote down vote up
def _get_lomb_scargle(bg_df, start_index, end_index, plot_lomb_array):
        bg_time_array, bg_value_array, bg_gap_start_time, bg_gap_end_time = _make_data_array(bg_df, start_index, end_index, 'bg')
        iob_time_array, iob_value_array, iob_gap_start_time, iob_gap_end_time = _make_data_array(bg_df, start_index, end_index, 'IOB')
        cob_time_array, cob_value_array, cob_gap_start_time, cob_gap_end_time = _make_data_array(bg_df, start_index, end_index, 'COB')

        #Keep track of the data start and end times in the array
        data_gap_start_time = bg_gap_start_time + iob_gap_start_time + cob_gap_start_time
        data_gap_end_time = bg_gap_end_time + iob_gap_end_time + cob_gap_end_time

        period = np.linspace(0, int(bg_time_array.max()), int(bg_time_array.max()) + 1) #set period to be as large as possible

        bg_lomb = _run_lomb_scargle(bg_time_array, bg_value_array, period)
        iob_lomb = _run_lomb_scargle(iob_time_array, iob_value_array, period)
        cob_lomb = _run_lomb_scargle(cob_time_array, cob_value_array, period)

        #Set all bg/cob values below zero equal to zero (iob can be negative if it is below baseline levels)
        bg_lomb[bg_lomb < 0] = 0
        cob_lomb[cob_lomb < 0] = 0

        #Plot lomb-scargle if values in the plot_lomb_array
        if len(plot_lomb_array) > 0:
            plt.clf()
            if "bg" in plot_lomb_array: _plot_lomb(period, bg_lomb, bg_time_array, bg_value_array, "BG")
            if "iob" in plot_lomb_array: _plot_lomb(period, iob_lomb, iob_time_array, iob_value_array, "IOB")
            if "cob" in plot_lomb_array: _plot_lomb(period, cob_lomb, cob_time_array, cob_value_array, "COB")
            plt.legend(loc='upper left')
            plt.show()

        return period, bg_lomb, iob_lomb, cob_lomb, data_gap_start_time, data_gap_end_time


#Class to store the lomb data 
Example 26
Project: OpenAPS   Author: medicinexlab   File: oldpred.py    MIT License 5 votes vote down vote up
def _plot_old_pred_data(old_pred_data, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str, algorithm_str, minutes_str):
    actual_bg_array = old_pred_data.result_actual_bg_array
    actual_bg_time_array = old_pred_data.result_actual_bg_time_array
    pred_array = old_pred_data.result_pred_array
    pred_time_array = old_pred_data.result_pred_time_array

    #Root mean squared error
    rms = math.sqrt(metrics.mean_squared_error(actual_bg_array, pred_array))
    print "                Root Mean Squared Error: " + str(rms)
    print "                Mean Absolute Error: " + str(metrics.mean_absolute_error(actual_bg_array, pred_array))
    print "                R^2 Coefficient of Determination: " + str(metrics.r2_score(actual_bg_array, pred_array))

    plot, zone = ClarkeErrorGrid.clarke_error_grid(actual_bg_array, pred_array, id_str + " " + algorithm_str + " " + minutes_str)
    print "                Percent A:{}".format(float(zone[0]) / (zone[0] + zone[1] + zone[2] + zone[3] + zone[4]))
    print "                Percent C, D, E:{}".format(float(zone[2] + zone[3] + zone[4])/ (zone[0] + zone[1] + zone[2] + zone[3] + zone[4]))
    print "                Zones are A:{}, B:{}, C:{}, D:{}, E:{}\n".format(zone[0],zone[1],zone[2],zone[3],zone[4])
    if save_clarke_plot: plt.savefig(id_str + algorithm_str.replace(" ", "") + minutes_str + "clarke.png")
    if show_clarke_plot: plot.show()

    plt.clf()
    plt.plot(actual_bg_time_array, actual_bg_array, label="Actual BG", color='black', linestyle='-')
    plt.plot(pred_time_array, pred_array, label="BG Prediction", color='black', linestyle=':')
    plt.title(id_str + " " + algorithm_str + " " + minutes_str + " BG Analysis")
    plt.ylabel("Blood Glucose Level (mg/dl)")
    plt.xlabel("Time (minutes)")
    plt.legend(loc='upper left')

    # SHOW/SAVE PLOT DEPENDING ON THE BOOLEAN PARAMETER
    if save_pred_plot: plt.savefig(id_str + algorithm_str.replace(" ","") + minutes_str + "plot.png")
    if show_pred_plot: plt.show()


#Function to analyze the old OpenAPS data 
Example 27
Project: ml_news_popularity   Author: khaledJabr   File: lr.py    MIT License 5 votes vote down vote up
def plot(self):
        lw = 2
        plt.scatter(range(len(self.targets)), self.targets, color='darkorange', label='data')
        plt.scatter(range(len(self.predicted)), self.predicted, color='cornflowerblue', lw=lw, label='Polynomial model')
        plt.xlabel('Data')
        plt.ylabel('Target')
        plt.title('Lasso Regression')
        plt.legend()
        plt.show() 
Example 28
Project: RandomFourierFeatures   Author: tiskw   File: sample_rff_regression.py    MIT License 5 votes vote down vote up
def main():

    ### Fix seed for random fourier feature calclation
    pyrff.seed(111)

    ### Prepare training data
    Xs_train = np.linspace(0, 3, 21).reshape((21, 1))
    ys_train = np.sin(Xs_train**2)
    Xs_test  = np.linspace(0, 3, 101).reshape((101, 1))
    ys_test  = np.sin(Xs_test**2)

    ### Create classifier instance
    reg = pyrff.RFFRegression(dim_output = 8, std = 0.5)

    ### Train regression with random fourier features
    reg.fit(Xs_train, ys_train)

    ### Conduct prediction for the test data
    predict = reg.predict(Xs_test)

    ### Plot regression results
    mpl.figure(0)
    mpl.title("Regression for function y = sin(x^2) with RFF")
    mpl.xlabel("X")
    mpl.ylabel("Y")
    mpl.plot(Xs_train, ys_train, "o")
    mpl.plot(Xs_test,  ys_test,  ".")
    mpl.plot(Xs_test,  predict,  "-")
    mpl.legend(["Training data", "Test data", "Prediction by RFF regression"])
    mpl.grid()
    mpl.show() 
Example 29
Project: mmdetection   Author: open-mmlab   File: analyze_logs.py    Apache License 2.0 5 votes vote down vote up
def add_plot_parser(subparsers):
    parser_plt = subparsers.add_parser(
        'plot_curve', help='parser for plotting curves')
    parser_plt.add_argument(
        'json_logs',
        type=str,
        nargs='+',
        help='path of train log in json format')
    parser_plt.add_argument(
        '--keys',
        type=str,
        nargs='+',
        default=['bbox_mAP'],
        help='the metric that you want to plot')
    parser_plt.add_argument('--title', type=str, help='title of figure')
    parser_plt.add_argument(
        '--legend',
        type=str,
        nargs='+',
        default=None,
        help='legend of each plot')
    parser_plt.add_argument(
        '--backend', type=str, default=None, help='backend of plt')
    parser_plt.add_argument(
        '--style', type=str, default='dark', help='style of plt')
    parser_plt.add_argument('--out', type=str, default=None) 
Example 30
Project: mmdetection   Author: open-mmlab   File: coco_error_analysis.py    Apache License 2.0 5 votes vote down vote up
def makeplot(rs, ps, outDir, class_name, iou_type):
    cs = np.vstack([
        np.ones((2, 3)),
        np.array([.31, .51, .74]),
        np.array([.75, .31, .30]),
        np.array([.36, .90, .38]),
        np.array([.50, .39, .64]),
        np.array([1, .6, 0])
    ])
    areaNames = ['allarea', 'small', 'medium', 'large']
    types = ['C75', 'C50', 'Loc', 'Sim', 'Oth', 'BG', 'FN']
    for i in range(len(areaNames)):
        area_ps = ps[..., i, 0]
        figure_tile = iou_type + '-' + class_name + '-' + areaNames[i]
        aps = [ps_.mean() for ps_ in area_ps]
        ps_curve = [
            ps_.mean(axis=1) if ps_.ndim > 1 else ps_ for ps_ in area_ps
        ]
        ps_curve.insert(0, np.zeros(ps_curve[0].shape))
        fig = plt.figure()
        ax = plt.subplot(111)
        for k in range(len(types)):
            ax.plot(rs, ps_curve[k + 1], color=[0, 0, 0], linewidth=0.5)
            ax.fill_between(
                rs,
                ps_curve[k],
                ps_curve[k + 1],
                color=cs[k],
                label=str('[{:.3f}'.format(aps[k]) + ']' + types[k]))
        plt.xlabel('recall')
        plt.ylabel('precision')
        plt.xlim(0, 1.)
        plt.ylim(0, 1.)
        plt.title(figure_tile)
        plt.legend()
        # plt.show()
        fig.savefig(outDir + '/{}.png'.format(figure_tile))
        plt.close(fig) 
Example 31
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def plot(self, names=None):
        names = self.names if names == None else names
        numbers = self.numbers
        for _, name in enumerate(names):
            x = np.arange(len(numbers[name]))
            plt.plot(x, np.asarray(numbers[name]))
        plt.legend([self.title + '(' + name + ')' for name in names])
        plt.grid(True) 
Example 32
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def plot(self, names=None):
        plt.figure()
        plt.plot()
        legend_text = []
        for logger in self.loggers:
            legend_text += plot_overlap(logger, names)
        legend_text = ['WRN-28-10+Ours (error 17.65%)', 'WRN-28-10 (error 18.68%)']
        plt.legend(legend_text, loc=0)
        plt.ylabel('test error (%)')
        plt.xlabel('epoch')
        plt.grid(True) 
Example 33
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def plot_log(filename, show=True):
    # load data
    keys = []
    values = []
    with open(filename, 'r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            if keys == []:
                for key, value in row.items():
                    keys.append(key)
                    values.append(float(value))
                continue

            for _, value in row.items():
                values.append(float(value))

        values = np.reshape(values, newshape=(-1, len(keys)))
        values[:,0] += 1

    fig = plt.figure(figsize=(4,6))
    fig.subplots_adjust(top=0.95, bottom=0.05, right=0.95)
    fig.add_subplot(211)
    for i, key in enumerate(keys):
        if key.find('loss') >= 0 and not key.find('val') >= 0:  # training loss
            plt.plot(values[:, 0], values[:, i], label=key)
    plt.legend()
    plt.title('Training loss')

    fig.add_subplot(212)
    for i, key in enumerate(keys):
        if key.find('acc') >= 0:  # acc
            plt.plot(values[:, 0], values[:, i], label=key)
    plt.legend()
    plt.title('Training and validation accuracy')

    # fig.savefig('result/log.png')
    if show:
        plt.show() 
Example 34
Project: Random-Erasing   Author: zhunzhong07   File: logger.py    Apache License 2.0 5 votes vote down vote up
def plot(self, names=None):   
        names = self.names if names == None else names
        numbers = self.numbers
        for _, name in enumerate(names):
            x = np.arange(len(numbers[name]))
            plt.plot(x, np.asarray(numbers[name]))
        plt.legend([self.title + '(' + name + ')' for name in names])
        plt.grid(True) 
Example 35
Project: Random-Erasing   Author: zhunzhong07   File: logger.py    Apache License 2.0 5 votes vote down vote up
def plot(self, names=None):
        plt.figure()
        plt.plot()
        legend_text = []
        for logger in self.loggers:
            legend_text += plot_overlap(logger, names)
        legend_text = ['WRN-28-10+Ours (error 17.65%)', 'WRN-28-10 (error 18.68%)']
        plt.legend(legend_text, loc=0)
        plt.ylabel('test error (%)')
        plt.xlabel('epoch')
        plt.grid(True) 
Example 36
Project: deep-learning-note   Author: wdxtub   File: utils.py    MIT License 5 votes vote down vote up
def semilogy(x_vals, y_vals, x_label, y_label, x2_vals=None, y2_vals=None, legend=None):
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    plt.semilogy(x_vals, y_vals)
    if x2_vals and y2_vals:
        plt.semilogy(x2_vals, y2_vals, linestyle=':')
        plt.legend(legend)
    plt.show() 
Example 37
Project: keras-anomaly-detection   Author: chen0040   File: h2o_ecg_pulse_detection.py    MIT License 5 votes vote down vote up
def plot_stacked_time_series(df, title):
    stacked = df.stack()
    stacked = stacked.reset_index()
    total = [data[0].values for name, data in stacked.groupby('level_0')]
    # pd.DataFrame({idx: pos for idx, pos in enumerate(total)}, index=stacked['level_1']).plot(title=title)
    pd.DataFrame({idx: pos for idx, pos in enumerate(total)}).plot(title=title)
    plt.legend(bbox_to_anchor=(1.05, 1))
    plt.show() 
Example 38
Project: keras-anomaly-detection   Author: chen0040   File: plot_utils.py    MIT License 5 votes vote down vote up
def plot_training_history(history):
    if history is None:
        return
    plt.plot(history['loss'])
    plt.plot(history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper right')
    plt.show() 
Example 39
Project: keras-anomaly-detection   Author: chen0040   File: plot_utils.py    MIT License 5 votes vote down vote up
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() 
Example 40
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 41
Project: FCOS_GluonCV   Author: DetectionTeamUCAS   File: plot_history.py    Apache License 2.0 5 votes vote down vote up
def plot(self, labels=None, colors=None, y_lim=(0, 1),
             save_path=None, legend_loc='upper right'):
        r"""Update the training history

        Parameters
        ---------
        labels: list of str
            List of label names to plot.
        colors: list of str
            List of line colors.
        save_path: str
            Path to save the plot. Will plot to screen if is None.
        legend_loc: str
            location of legend. upper right by default.
        """
        import matplotlib.pyplot as plt

        if labels is None:
            labels = self.labels
        n = len(labels)

        line_lists = [None]*n
        if colors is None:
            colors = ['C'+str(i) for i in range(n)]
        else:
            assert len(colors) == n

        plt.ylim(y_lim)
        for i, lb in enumerate(labels):
            line_lists[i], = plt.plot(list(range(self.epochs)),
                                      self.history[lb],
                                      colors[i],
                                      label=lb)
        plt.legend(tuple(line_lists), labels, loc=legend_loc)
        if save_path is None:
            plt.show()
        else:
            save_path = os.path.expanduser(save_path)
            plt.savefig(save_path) 
Example 42
Project: order   Author: ipudu   File: plot.py    MIT License 5 votes vote down vote up
def plot_ionic(self):
        """plot distribution"""

        data1 = np.loadtxt(self.fprefix+'_'+self.taskname+'_ti.dat')
        data2 = np.loadtxt(self.fprefix+'_'+self.taskname+'_iaafp.dat')

        #plot setting
        #plt.rcParams['font.family'] = 'serif'
        #plt.rcParams['font.serif'] = 'Ubuntu'
        #plt.rcParams['font.monospace'] = 'Ubuntu Mono'
        plt.rcParams['font.size'] = 10
        plt.rcParams['axes.labelsize'] = 10
        #plt.rcParams['axes.labelweight'] = 'bold'
        plt.rcParams['xtick.labelsize'] = 8
        plt.rcParams['ytick.labelsize'] = 8
        plt.rcParams['legend.fontsize'] = 10
        plt.rcParams['figure.titlesize'] = 12

        #clean last plot
        plt.clf()

        plt.xlabel("Simulation time(ps)")
        plt.ylabel("Charge from ions crossing the plane (e)")

        x1 = data1[:,0]
        y1 = data1[:,1]

        x2 = data2[:,0]
        y2 = data2[:,1]


        plt.plot(x1, y1, label='ti')
        plt.plot(x2, y2, label='iaafp')
        plt.legend()
        
        figure = self.fprefix + '_' + self.taskname.upper() + '.pdf'
        plt.savefig(figure, bbox_inches="tight") 
Example 43
Project: ReinforcementLearningBookExamples   Author: Shawn-Guo-CN   File: 1TenArmedBandits.py    GNU General Public License v3.0 5 votes vote down vote up
def optimal_initial_values(num_bandits, episode_length):
    agents = [Agent(epsilon=0, initial_value=5, step_size=.1),
              Agent(epsilon=0.1, initial_value=0, step_size=0.1)]
    best_action_counts, _ = play_game(num_bandits, episode_length, agents)
    global figure_index
    plt.figure(figure_index)
    plt.plot(best_action_counts[0], label='epsilon = 0, q = 5')
    plt.plot(best_action_counts[1], label='epsilon = 0.1, q = 0')
    plt.xlabel('Steps')
    plt.ylabel('% optimal action')
    plt.legend()


# for figure 2.4 
Example 44
Project: ReinforcementLearningBookExamples   Author: Shawn-Guo-CN   File: 1TenArmedBandits.py    GNU General Public License v3.0 5 votes vote down vote up
def ucb(num_bandits, episode_length):
    agents = [Agent(epsilon=0, step_size=0.1, UCB_param=2),
              Agent(epsilon=0.1, step_size=0.1)]
    _, avg_rewards = play_game(num_bandits, episode_length, agents)
    global figure_index
    plt.figure(figure_index)
    figure_index += 1
    plt.plot(avg_rewards[0], label='UCB c = 2')
    plt.plot(avg_rewards[1], label='epsilon greedy epsilon = 0.1')
    plt.xlabel('Steps')
    plt.ylabel('Average reward')
    plt.legend()


# for figure 2.5 
Example 45
Project: ReinforcementLearningBookExamples   Author: Shawn-Guo-CN   File: 1TenArmedBandits.py    GNU General Public License v3.0 5 votes vote down vote up
def play_1bandit_1agent():
    bandit = Bandit()
    agent = Agent(epsilon=0.05, sample_average=True)

    total_reward = 0.
    right_times = 0

    avg_rewards = []
    right_times_freq = []

    for t in range(1, 1001):
        action = agent.get_action()
        reward = bandit.take_arm(action)
        agent.update_values(action, reward)
        total_reward += reward
        if action == bandit.best_action:
            right_times += 1
        avg_rewards.append(total_reward / t)
        right_times_freq.append(right_times / t)

    plt.plot(right_times_freq, label='right freq')
    plt.plot(avg_rewards, label='avg reward')
    plt.plot([bandit.means[bandit.best_action]] * 1000, label='best reward')
    plt.legend()


# following is for testing whether agent and bandit are rightly implemented 
Example 46
Project: deep-summarization   Author: harpribot   File: plotter.py    MIT License 5 votes vote down vote up
def plot_one_metric(self, models_metric, title):
        """

        :param models_metric:
        :param title:
        :return:
        """
        for index, model_metric in enumerate(models_metric):
            plt.plot(self.steps, model_metric, label=self.file_desc[index])
        plt.title(title)
        plt.legend()
        plt.xlabel('Number of batches')
        plt.ylabel('Score') 
Example 47
Project: Deep_Learning_Weather_Forecasting   Author: BruceBinBoxing   File: utils.py    Apache License 2.0 5 votes vote down vote up
def plot_prediction(x, y_true, y_pred, input_ruitu=None):
    """Plots the predictions.
    
    Arguments
    ---------
    x: Input sequence of shape (input_sequence_length,
        dimension_of_signal)
    y_true: True output sequence of shape (input_sequence_length,
        dimension_of_signal)
    y_pred: Predicted output sequence (input_sequence_length,
        dimension_of_signal)
    """

    plt.figure(figsize=(12, 3))

    output_dim = x.shape[-1]# feature dimension
    for j in range(output_dim):
        past = x[:, j] 
        true = y_true[:, j]
        pred = y_pred[:, j]
        if input_ruitu is not None:
            ruitu = input_ruitu[:, j]

        label1 = "Seen (past) values" if j==0 else "_nolegend_"
        label2 = "True future values" if j==0 else "_nolegend_"
        label3 = "Predictions" if j==0 else "_nolegend_"
        label4 = "Ruitu values" if j==0 else "_nolegend_"

        plt.plot(range(len(past)), past, "o-g",
                 label=label1)
        plt.plot(range(len(past),
                 len(true)+len(past)), true, "x--g", label=label2)
        plt.plot(range(len(past), len(pred)+len(past)), pred, "o--y",
                 label=label3)
        if input_ruitu is not None:
            plt.plot(range(len(past), len(ruitu)+len(past)), ruitu, "o--r",
                 label=label4)
    plt.legend(loc='best')
    plt.title("Predictions v.s. true values v.s. Ruitu")
    plt.show() 
Example 48
Project: Deep_Learning_Weather_Forecasting   Author: BruceBinBoxing   File: competition_model_class.py    Apache License 2.0 5 votes vote down vote up
def plot_prediction(self, x, y_true, y_pred, input_ruitu=None):
        """Plots the predictions.

        Arguments
        ---------
        x: Input sequence of shape (input_sequence_length,
            dimension_of_signal)
        y_true: True output sequence of shape (input_sequence_length,
            dimension_of_signal)
        y_pred: Predicted output sequence (input_sequence_length,
            dimension_of_signal)
        input_ruitu: Ruitu output sequence 
        """

        plt.figure(figsize=(12, 3))

        output_dim = x.shape[-1]# feature dimension
        for j in range(output_dim):
            past = x[:, j] 
            true = y_true[:, j]
            pred = y_pred[:, j]
            if input_ruitu is not None:
                ruitu = input_ruitu[:, j]

            label1 = "Seen (past) values" if j==0 else "_nolegend_"
            label2 = "True future values" if j==0 else "_nolegend_"
            label3 = "Predictions" if j==0 else "_nolegend_"
            label4 = "Ruitu values" if j==0 else "_nolegend_"

            plt.plot(range(len(past)), past, "o-g",
                     label=label1)
            plt.plot(range(len(past),
                     len(true)+len(past)), true, "x--g", label=label2)
            plt.plot(range(len(past), len(pred)+len(past)), pred, "o--y",
                     label=label3)
            if input_ruitu is not None:
                plt.plot(range(len(past), len(ruitu)+len(past)), ruitu, "o--r",
                     label=label4)
        plt.legend(loc='best')
        plt.title("Predictions v.s. true values v.s. Ruitu")
        plt.show() 
Example 49
Project: DiscEvolution   Author: rbooth200   File: reconstruction.py    GNU General Public License v3.0 5 votes vote down vote up
def _run_tests(IC, N=64, tol=1e9, reverse=False):
    a = 1.

    if reverse:
        a *= -1


    #### IC
    xc, Q0 = _test_scheme(10**3, IC, DonorCell, 0.,a)
    plt.plot(xc, Q0, 'k-')

    #### Donor
    xc, Q  = _test_scheme(N, IC, DonorCell, 1.,a)

    plt.plot(xc, Q, 'o', label='Donor Cell')

    # Check the symmetry:
    xc, Q1 = _test_scheme(N, IC, DonorCell, 1., -a)
    assert( (abs(1 - Q/Q1[::-1]).mean() < tol))


    #### Van Leer
    xc, Q = _test_scheme(N, IC, VanLeer, 1.,a)
    plt.plot(xc, Q, '+', label='Van Leer')
    plt.legend()
    
    # Check the symmetry:
    xc, Q1 = _test_scheme(N, IC, VanLeer, 1., -a)

    assert( abs(1 - Q/Q1[::-1]).mean() < tol)

    
    #### Weno3
    xc, Q = _test_scheme(N, IC, Weno3, 1.,a)
    plt.plot(xc, Q, 'x', label='WENO-3')
    plt.legend()
    
    # Check the symmetry:
    xc, Q1 = _test_scheme(N, IC, Weno3, 1., -a)
    assert( (abs(1 - Q/Q1[::-1]).mean() < tol)) 
Example 50
Project: whatsapp-stats   Author: nielsrolf   File: analyze.py    Apache License 2.0 5 votes vote down vote up
def plot(self, stat_name, keys, values):
        plt.clf()
        fig = plt.figure()

        cats = list(dict(keys).keys()) # keys are cat, time pairs
        for cat in cats:
            filtered_values = [value for key, value in zip(keys, values) if key[0]==cat]
            time_labels = [key[1] for key in keys if key[0]==cat]
            self.time_group._plot(cat, stat_name, time_labels, filtered_values, fig)

        plt.legend()
        plt.title(stat_name + " " + self.name)
        plt.savefig(PLOT_PATH + "/" + self.name+" "+stat_name+".png")
        plt.close('all')