Python matplotlib.pyplot.plot() Examples

The following are code examples for showing how to use matplotlib.pyplot.plot(). 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: s2g   Author: caesar0301   File: test.py    MIT License 6 votes vote down vote up
def test_point_projects_to_edge(self):
        # p = (114.83299055, 26.8892277)
        p = (121.428387, 31.027371)
        a = time.time()
        edges, segments = self.sg.point_projects_to_edges(p, 0.01)
        print(time.time() - a)

        if self.show_plots:
            plt.figure()
            s2g.plot_lines(MultiLineString(segments), color='orange')  # original roads
            for i in range(0, len(edges)):
                s, e = edges[i]
                sxy = self.sg.node_xy[s]
                exy = self.sg.node_xy[e]
                plt.plot([sxy[0], exy[0]], [sxy[1], exy[1]], color='green')  # graph edges
            plt.plot(p[0], p[1], color='red', markersize=12, marker='o')  # bridges
            plt.show() 
Example 3
Project: PEAKachu   Author: tbischler   File: window.py    ISC License 6 votes vote down vote up
def _plot_and_write_windows_gfold(self):
        # plot windows
        print("* Plotting normalized windows...", flush=True)
        t_start = time()
        sig_window_df = self._window_df[self._window_df.significant]
        unsig_window_df = self._initial_window_df[
            ~self._initial_window_df.index.isin(sig_window_df.index)]
        self._plot_initial_windows(unsig_window_df.base_means,
                                   unsig_window_df.fold_change,
                                   sig_window_df.base_means,
                                   sig_window_df.fold_change)
        t_end = time()
        print("Plotting took {} seconds.".format(t_end-t_start), flush=True)
        # write windows after prefiltering with test results
        self._window_df.to_csv(
            "{}/windows_after_prefiltering.csv".format(self._output_folder),
            sep='\t', index=False, encoding='utf-8') 
Example 4
Project: PEAKachu   Author: tbischler   File: window.py    ISC License 6 votes vote down vote up
def _plot_and_write_windows_deseq(self):
        # plot windows
        print("* Plotting normalized windows...", flush=True)
        t_start = time()
        sig_window_df = self._window_df[self._window_df.significant]
        unsig_window_df = self._window_df[
            ~self._window_df.index.isin(sig_window_df.index)]
        self._plot_initial_windows(
            unsig_window_df.baseMean,
            np.power(2.0, unsig_window_df.log2FoldChange),
            sig_window_df.baseMean,
            np.power(2.0, sig_window_df.log2FoldChange))
        t_end = time()
        print("Plotting took {} seconds.".format(t_end-t_start), flush=True)
        # write windows after prefiltering with test results
        self._window_df.to_csv(
            "{}/windows_after_prefiltering.csv".format(self._output_folder),
            sep='\t', index=False, encoding='utf-8') 
Example 5
Project: kicker-module   Author: EvanTheB   File: graph.py    GNU General Public License v3.0 6 votes vote down vote up
def graph_ranks(p, g, ladder):
    def get_names_ranks(data):
        ret = []
        for l in data:
            if float(l.extra[2][1]) > 7.:
                ret.append((l[1], len(data)))
            else:
                ret.append((l.name, l.rank))
        return ret

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

    for y in data_to_yarr(graph_data):
        plt.plot(y)
    pylab.savefig('graph_ranks.svg')
    #plt.show() 
Example 6
Project: kicker-module   Author: EvanTheB   File: graph.py    GNU General Public License v3.0 6 votes vote down vote up
def graph_level(p, g, ladder):
    def get_names_lvl(data):
        ret = []
        for l in data:
            ret.append((l.name, l.extra[0][1]))
        return ret

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

    for y in data_to_yarr(graph_data):
        plt.plot(y)
    pylab.savefig('graph_level.svg')
   # plt.show() 
Example 7
Project: kicker-module   Author: EvanTheB   File: graph.py    GNU General Public License v3.0 6 votes vote down vote up
def graph_skill(p, g, ladder):
    def get_names_skill(data):
        ret = []
        for l in data:
            if float(l.extra[2][1]) > 7.:
                ret.append((l.name, 0.))
            else:
                ret.append((l.name, l.extra[1][1]))
        return ret

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

    for y in data_to_yarr(graph_data):
        plt.plot(y)
    pylab.savefig('graph_skill.svg')
  #  plt.show() 
Example 8
Project: OpenAPS   Author: medicinexlab   File: oldpred.py    MIT License 6 votes vote down vote up
def _get_old_pred(bg_df, start_index, end_index, num_pred_minutes):
    #The number of 5 minute sections until the prediction (e.g. 30 minutes = 6 sections)
    pred_array_index = num_pred_minutes / DATA_SPACING

    actual_bg_array, actual_bg_time_array, eventual_pred_array, eventual_pred_time_array, iob_pred_array, iob_pred_time_array, cob_pred_array, cob_pred_time_array, acob_pred_array, acob_pred_time_array = _get_raw_pred_array(bg_df, start_index, end_index, pred_array_index)

    eventual_pred_data = _find_compare_array(actual_bg_array, actual_bg_time_array, eventual_pred_array, eventual_pred_time_array, 30)
    iob_pred_data = _find_compare_array(actual_bg_array, actual_bg_time_array, iob_pred_array, iob_pred_time_array, num_pred_minutes)
    cob_pred_data= _find_compare_array(actual_bg_array, actual_bg_time_array, cob_pred_array, cob_pred_time_array, num_pred_minutes)
    acob_pred_data = _find_compare_array(actual_bg_array, actual_bg_time_array, acob_pred_array, acob_pred_time_array, num_pred_minutes)

    return eventual_pred_data, iob_pred_data, cob_pred_data, acob_pred_data


#Plots old pred data given namedtuple of old data (eventualBG, acob, cob, or iob).
#Can show or save prediction plot based on show_pred_plot or save_pred_plot, respectively.
#Same goes for the Clarke Error grid with show_clarke_plot or save_clarke_plot, respectively.
#id_str, algorithm_str, minutes_str are strings of the ID, the prediction algorithm and the number of prediction minutes used for the title. 
Example 9
Project: OpenAPS   Author: medicinexlab   File: oldpred.py    MIT License 6 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 10
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 11
Project: mmdetection   Author: open-mmlab   File: recall.py    Apache License 2.0 6 votes vote down vote up
def plot_num_recall(recalls, proposal_nums):
    """Plot Proposal_num-Recalls curve.

    Args:
        recalls(ndarray or list): shape (k,)
        proposal_nums(ndarray or list): same shape as `recalls`
    """
    if isinstance(proposal_nums, np.ndarray):
        _proposal_nums = proposal_nums.tolist()
    else:
        _proposal_nums = proposal_nums
    if isinstance(recalls, np.ndarray):
        _recalls = recalls.tolist()
    else:
        _recalls = recalls

    import matplotlib.pyplot as plt
    f = plt.figure()
    plt.plot([0] + _proposal_nums, [0] + _recalls)
    plt.xlabel('Proposal num')
    plt.ylabel('Recall')
    plt.axis([0, proposal_nums.max(), 0, 1])
    f.show() 
Example 12
Project: mmdetection   Author: open-mmlab   File: recall.py    Apache License 2.0 6 votes vote down vote up
def plot_iou_recall(recalls, iou_thrs):
    """Plot IoU-Recalls curve.

    Args:
        recalls(ndarray or list): shape (k,)
        iou_thrs(ndarray or list): same shape as `recalls`
    """
    if isinstance(iou_thrs, np.ndarray):
        _iou_thrs = iou_thrs.tolist()
    else:
        _iou_thrs = iou_thrs
    if isinstance(recalls, np.ndarray):
        _recalls = recalls.tolist()
    else:
        _recalls = recalls

    import matplotlib.pyplot as plt
    f = plt.figure()
    plt.plot(_iou_thrs + [1.0], _recalls + [0.])
    plt.xlabel('IoU')
    plt.ylabel('Recall')
    plt.axis([iou_thrs.min(), 1, 0, 1])
    f.show() 
Example 13
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 14
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 15
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 16
Project: cplot   Author: sunchaoatmo   File: cstimeserial.py    GNU General Public License v3.0 6 votes vote down vote up
def setmonthlyticklabe(yb,ye,units_cur,calendar_cur):
  x_tickloc_major=[]
  labels_major   =[]
  x_tickloc_major=[0]
  begdate=datetime.datetime(yb,1 , 1, 0,0,0)                
  enddate=datetime.datetime(ye,12 , 1, 0,0,0)                
  T0=date2num( curdate,units=units_cur,calendar=calendar_cur)
  labels_major=[curdate.strftime("%m-%d")]
  for imonth,month in enumerate(range(LLJ_sm+1,LLJ_em+2)):
    curdate=datetime.datetime(years[0],month , 1, 0,0,0)                
    T_loc=date2num( curdate,units=units_cur,calendar=calendar_cur)-T0
    ax.plot([T_loc,T_loc],[0,len(xlat)-1], lw=1, c="r",linestyle="--")
    x_tickloc_major.append(T_loc)
    labels_major.append(curdate.strftime("%m/%d"))
  ax.set_xticks( x_tickloc_major )
  ax.set_xticklabels(labels_major,color='brown') 
Example 17
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 18
Project: DOTA_models   Author: ringringyi   File: plot_lfads.py    Apache License 2.0 6 votes vote down vote up
def plot_time_series(vals_bxtxn, bidx=None, n_to_plot=np.inf, scale=1.0,
                     color='r', title=None):

  if bidx is None:
    vals_txn = np.mean(vals_bxtxn, axis=0)
  else:
    vals_txn = vals_bxtxn[bidx,:,:]

  T, N = vals_txn.shape
  if n_to_plot > N:
    n_to_plot = N

  plt.plot(vals_txn[:,0:n_to_plot] + scale*np.array(range(n_to_plot)),
           color=color, lw=1.0)
  plt.axis('tight')
  if title:
    plt.title(title) 
Example 19
Project: ortholotree   Author: oxpeter   File: internal.py    GNU General Public License v2.0 6 votes vote down vote up
def rank_scores(homologlist, thresh1=0, thresh2=None, genename=None, outfile=None, showplot=False):
    yvalues = sorted([val[1] for val in homologlist.values()], reverse=True)
    plt.plot(yvalues)
    score_cutoff = thresh1 * max(yvalues)
    sample_cutoff = sum(1 for s in yvalues if s >= thresh1 * max(yvalues))
    plt.axhline( score_cutoff , color='r' )
    if thresh2:
        plt.axhline( thresh2 * max(yvalues) , color='r' )
    plt.axvline( sample_cutoff -1 , color='g' )
    plt.text(sample_cutoff + 1,score_cutoff + 10 , "(%d,%d)" % (sample_cutoff,score_cutoff) )
    plt.xlabel("Gene rank")
    plt.ylabel("Phmmer score")
    plt.title("Ranking of phmmer scores for alignment with %s" % genename)
    if outfile:
        plt.savefig(outfile, format='png')
    if showplot:
        plt.show()
    else:
        plt.close() 
Example 20
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 21
Project: simulated-annealing-tsp   Author: chncyhn   File: anneal.py    MIT License 5 votes vote down vote up
def plot_learning(self):
        """
        Plot the fitness through iterations.
        """
        plt.plot([i for i in range(len(self.fitness_list))], self.fitness_list)
        plt.ylabel("Fitness")
        plt.xlabel("Iteration")
        plt.show() 
Example 22
Project: PEAKachu   Author: tbischler   File: window.py    ISC License 5 votes vote down vote up
def _plot_initial_windows(self, unsig_base_means, unsig_fcs,
                              sig_base_means, sig_fcs):
        # create plot folder if it does not exist
        plot_folder = "{}/plots".format(self._output_folder)
        if not exists(plot_folder):
            makedirs(plot_folder)
        # MA plot
        plt.plot(np.log10(unsig_base_means),
                 np.log2(unsig_fcs), ".",
                 markersize=2.0, alpha=0.3)
        plt.plot(np.log10(sig_base_means),
                 np.log2(sig_fcs), ".",
                 markersize=2.0, color="red", alpha=0.3)
        plt.axhline(y=np.median(np.log2(unsig_fcs.append(sig_fcs))))
        plt.axvline(x=np.median(np.log10(unsig_base_means.append(
                                         sig_base_means))))
        plt.title("Initial_windows_MA_plot")
        plt.xlabel("log10 base mean")
        plt.ylabel("log2 fold-change")
        plt.savefig("{}/Initial_windows_MA_plot.png".format(plot_folder),
                    dpi=600)
        plt.close()
        # HexBin plot
        df = pd.DataFrame({'log10 base mean': np.log10(unsig_base_means.append(
            sig_base_means)), 'log2 fold-change': np.log2(unsig_fcs.append(
                sig_fcs))})
        df.plot(kind='hexbin', x='log10 base mean',
                y='log2 fold-change', gridsize=50, bins='log')
        plt.axhline(y=np.median(np.log2(unsig_fcs.append(sig_fcs))))
        plt.axvline(x=np.median(np.log10(unsig_base_means.append(
                                         sig_base_means))))
        plt.title("Initial_windows_HexBin_plot")
        plt.savefig("{}/Initial_windows_HexBin_plot.pdf".format(plot_folder))
        plt.close() 
Example 23
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 24
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 25
Project: projection-methods   Author: akshayka   File: circles.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_iterates(iterates, label):
    x = [float(i[0]) for i in iterates]
    y = [float(i[1]) for i in iterates]
    plt.scatter(x=x, y=y)
    plt.plot(x, y, label=label) 
Example 26
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    MIT License 5 votes vote down vote up
def _initialisePlot(self):

        plt.rc('grid', linestyle=":", color='black')
        plt.rcParams['axes.facecolor'] = 'black'
        plt.rcParams['axes.edgecolor'] = 'white'
        plt.rcParams['grid.alpha'] = 1
        plt.rcParams['grid.color'] = "green"
        plt.grid(True)
        plt.xlim(self.PLOTXMIN, self.PLOTXMAX)
        plt.ylim(self.PLOTYMIN, self.PLOTYMAX)
        self.graph, = plt.plot([], [], 'o')

        return 
Example 27
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    MIT License 5 votes vote down vote up
def run(self):
        self._printLogs("Waiting for the robot to be in wake up position", "OKBLUE")

        self.motion_service.wakeUp()
        self.posture_service.goToPosture("StandInit", 0.1)

        self.create_callbacks()
        # self.startDLServer()
        self._addTopic()

        # graphplots
        self._initialisePlot()
        ani = animation.FuncAnimation(self.fig, self._animate, blit=False, interval=500 ,repeat=False)


        # loop on, wait for events until manual interruption
        try:
            # while True:
            #     time.sleep(1)
            # starting graph plot
            plt.show() # blocking call hence no need for while(True)

        except KeyboardInterrupt:
            self._printLogs("Interrupted by user, shutting down", "FAIL")
            self._cleanUp()

            self._printLogs("Waiting for the robot to be in rest position", "FAIL")
            # self.motion_service.rest()
            sys.exit(0)

        return 
Example 28
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 29
Project: fenics-topopt   Author: zfergus   File: triangulate.py    MIT License 5 votes vote down vote up
def plot_mesh(V, F, plot_f=False):
    plt.scatter(V[:, 0], V[:, 1])
    if not plot_f:
        return
    for i in range(F.shape[0]):
        vf = V[F[i, :], :]
        plt.plot(vf[:, 0], vf[:, 1]) 
Example 30
Project: kipet   Author: salvadorgarciamunoz   File: data_tools.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_spectral_data(dataFrame,dimension='2D'):
    """ Plots spectral data
    
        Args:
            dataFrame (DataFrame): spectral data
          
        Returns:
            None

    """
    if dimension=='3D':
        lambdas = dataFrame.columns
        times = dataFrame.index
        D = np.array(dataFrame)
        L, T = np.meshgrid(lambdas, times)
        fig = plt.figure()
        #ax = fig.add_subplot(111, projection='3d')
        #ax.plot_wireframe(L, T, D, rstride=10, cstride=10)
        ax = fig.gca(projection='3d')
        ax.plot_surface(L, T, D, rstride=10, cstride=10, alpha=0.2)
        #cset = ax.contour(L, T, D, zdir='z',offset=-10)
        cset = ax.contour(L, T, D, zdir='x',offset=-20,cmap='coolwarm')
        cset = ax.contour(L, T, D, zdir='y',offset=times[-1]*1.1,cmap='coolwarm')
        
        ax.set_xlabel('Wavelength')
        ax.set_xlim(lambdas[0]-20, lambdas[-1])
        ax.set_ylabel('time')
        ax.set_ylim(0, times[-1]*1.1)
        ax.set_zlabel('Spectra')
        #ax.set_zlim(-10, )


    else:
        plt.figure()
        plt.plot(dataFrame)

#=============================================================================
#--------------------------- DIAGNOSTIC TOOLS ------------------------
#============================================================================= 
Example 31
Project: wikilinks   Author: trovdimi   File: click_distributions.py    MIT License 5 votes vote down vote up
def plot_counts_frequency():

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


    category_distributions = read_pickle(HOME+'output/category_counts_distribution.obj')
    data = category_distributions['counts']
    data = [int(x[0]) for x in data]
    #to consider the edges that have zero transitions we substract the number transitions from the number of edges in wikipeida
    #number_of_edges = 339463340
    #zeros = np.zeros((number_of_edges - len(data)))
    #data = np.append(zeros, data)
    #bins = [0,11]
    #bins.extend(np.linspace(100,10000))
    #data = data.extend(listofzeros)
    #print data
    hist, bin_edges = np.histogram(data, bins=10000)
    #print len(hist)
    #print len(bin_edges)
    print hist, bin_edges

    ax.set_yscale('log')
    ax.set_xscale('log')
    ax.plot(bin_edges[:-1], hist, marker='o', markersize=3, markeredgecolor='none', color='#D65F5F')

    #ax.set_ylim([10**0, 10**6])
    #ax.set_xlim([10**0, 10**6])
    ax.set_xlabel('Number of transitions')
    ax.set_ylabel('Frequency')

    fig.tight_layout()
    fig.savefig( 'output/agg_counts_distributions.pdf', bbox_inches='tight') 
Example 32
Project: OpenAPS   Author: medicinexlab   File: bglomb.py    MIT License 5 votes vote down vote up
def _plot_lomb(period, lomb, time_array, value_array, name_str):
    plt.plot(time_array, value_array, label='Actual ' + name_str)
    plt.plot(period, lomb, label='Lomb ' + name_str)


#This function gets the data from the lomb scargle. It takes in the start and end indices and returns a lomb scargle model for BG, IOB, and COB as well as the period 
Example 33
Project: OpenAPS   Author: medicinexlab   File: bglomb.py    MIT License 5 votes vote down vote up
def get_lomb_data(bg_df, start_index, end_index, plot_lomb_array):
    """
    Function to make a lomb-scargle periodogram from the OpenAPS data in order to get
    data for every minute, not just every 5 minutes. It takes in the dataframe
    and the start and stop indices along with the plot_lomb_array, which is an array
    with the values that allow you to plot the lomb-scargle values with matplotlib.

    Input:      bg_df                           Pandas dataframe of all of the data from ./data/[id_str]/devicestatus.json
                start_index                     The start index of the set. Should be higher in value than end_index, as
                                                    the earlier times have higher indices
                end_index                       The end index of the set. Should be lower in value than start_index, as
                                                    the later times have lower indices. Inclusive, so this index is included in the data
                plot_lomb_array                 Array with the types to be plotted as strings. e.g. ['bg','iob','cob']
.
    Output:     lomb_data                       The namedtuple holding the lomb-scargle data with these arrays:
                                                    ['period', 'bg_lomb', 'iob_lomb', 'cob_lomb', 'time_value_array', data_gap_start_time, data_gap_end_time]
                                                    data_gap_start_time: Array with the start times of the data gaps that will be skipped
                                                    The indices of this and data_gap_end_time correspond to the same data gap
                                                    data_gap_end_time: Array with the end times of the data gaps that will be skipped
                                                    The indices of this and data_gap_start_time correspond to the same data gap
    Usage:      train_lomb_data = get_lomb_data(bg_df, start_train_index, end_train_index, ['bg', 'iob'])
    """

    #Make the time_value_array, which is the array of hours from midnight
    time_value_array = _make_time_value_array(bg_df, start_index, end_index)
    period, bg_lomb, iob_lomb, cob_lomb, data_gap_start_time, data_gap_end_time = _get_lomb_scargle(bg_df, start_index, end_index, plot_lomb_array)

    lomb_data = LombData(period, bg_lomb, iob_lomb, cob_lomb, time_value_array, data_gap_start_time, data_gap_end_time)

    return lomb_data 
Example 34
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 35
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 36
Project: mmdetection   Author: open-mmlab   File: analyze_logs.py    Apache License 2.0 5 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(description='Analyze Json Log')
    # currently only support plot curve and calculate average train time
    subparsers = parser.add_subparsers(dest='task', help='task parser')
    add_plot_parser(subparsers)
    add_time_parser(subparsers)
    args = parser.parse_args()
    return args 
Example 37
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def plot_overlap(logger, names=None):
    names = logger.names if names == None else names
    numbers = logger.numbers
    for _, name in enumerate(names):
        x = np.arange(len(numbers[name]))
        if name in ['Train Acc.', 'Valid Acc.']:
            plt.plot(x, 100 - np.asarray(numbers[name], dtype='float'))
        else:
            plt.plot(x, np.asarray(numbers[name]))
    return [logger.title + '(' + name + ')' for name in names] 
Example 38
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 39
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 40
Project: Sessile.drop.analysis   Author: mvgorcum   File: GUI_sessile_drop_analysis.py    GNU General Public License v3.0 5 votes vote down vote up
def plotstuff(typexplot,typeyplot,logxbool,logybool,pxscale,fps):
    x=np.float()
    y=np.float()
    if typexplot==1:
        x=thetal
    elif typexplot==2:
        x=thetar
    elif typexplot==3:
        x=dropvolume*pxscale**3
    elif typexplot==3:
        x=leftspeed*pxscale*fps
    elif typexplot==4:
        x=rightspeed*pxscale*fps
    else:
        print('no x variable set')
    if typeyplot==1:
        y=thetal
    elif typeyplot==2:
        y=thetar
    elif typeyplot==3:
        y=dropvolume
    elif typeyplot==3:
        y=leftspeed
    elif typeyplot==4:
        y=rightspeed
    else:
        print('no y variable set')
    if x.size==1 or y.size==1:
        plt.scatter(x,y)
    else:
        plt.plot(x,y)
    
    if logxbool:
        plt.xscale('log')
    if logybool:
        plt.yscale('log')
    plt.show() 
Example 41
Project: neural-fingerprinting   Author: StephanZheng   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pair_visual(original, adversarial, figure=None):
    """
    This function displays two images: the original and the adversarial sample
    :param original: the original input
    :param adversarial: the input after perterbations have been applied
    :param figure: if we've already displayed images, use the same plot
    :return: the matplot figure to reuse for future samples
    """
    import matplotlib.pyplot as plt

    # Squeeze the image to remove single-dimensional entries from array shape
    original = np.squeeze(original)
    adversarial = np.squeeze(adversarial)

    # Ensure our inputs are of proper shape
    assert(len(original.shape) == 2 or len(original.shape) == 3)

    # To avoid creating figures per input sample, reuse the sample plot
    if figure is None:
        plt.ion()
        figure = plt.figure()
        figure.canvas.set_window_title('Cleverhans: Pair Visualization')

    # Add the images to the plot
    perterbations = adversarial - original
    for index, image in enumerate((original, perterbations, adversarial)):
        figure.add_subplot(1, 3, index + 1)
        plt.axis('off')

        # If the image is 2D, then we have 1 color channel
        if len(image.shape) == 2:
            plt.imshow(image, cmap='gray')
        else:
            plt.imshow(image)

        # Give the plot some time to update
        plt.pause(0.01)

    # Draw the plot and return
    plt.show()
    return figure 
Example 42
Project: neural-fingerprinting   Author: StephanZheng   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def grid_visual(data):
    """
    This function displays a grid of images to show full misclassification
    :param data: grid data of the form;
        [nb_classes : nb_classes : img_rows : img_cols : nb_channels]
    :return: if necessary, the matplot figure to reuse
    """
    import matplotlib.pyplot as plt

    # Ensure interactive mode is disabled and initialize our graph
    plt.ioff()
    figure = plt.figure()
    figure.canvas.set_window_title('Cleverhans: Grid Visualization')

    # Add the images to the plot
    num_cols = data.shape[0]
    num_rows = data.shape[1]
    num_channels = data.shape[4]
    current_row = 0
    for y in xrange(num_rows):
        for x in xrange(num_cols):
            figure.add_subplot(num_rows, num_cols, (x + 1) + (y * num_cols))
            plt.axis('off')

            if num_channels == 1:
                plt.imshow(data[x, y, :, :, 0], cmap='gray')
            else:
                plt.imshow(data[x, y, :, :, :])

    # Draw the plot and return
    plt.show()
    return figure 
Example 43
Project: voice-recognition   Author: golabies   File: filters.py    MIT License 5 votes vote down vote up
def show(func, *inputs):
        x = func(*inputs)
        y = np.arange(len(x))
        plt.plot(y, x)
        plt.show() 
Example 44
Project: voice-recognition   Author: golabies   File: read_data.py    MIT License 5 votes vote down vote up
def show(self):
        for i in range(len(self.voice)):
            plt.plot(np.arange(len(self.voice[i])), self.voice[i]+i*5)
        plt.show() 
Example 45
Project: voice-recognition   Author: golabies   File: signal_fft.py    MIT License 5 votes vote down vote up
def show(self):
        plt.plot(self.freq, np.log10(self.out_put))
        plt.show() 
Example 46
Project: Random-Erasing   Author: zhunzhong07   File: logger.py    Apache License 2.0 5 votes vote down vote up
def plot_overlap(logger, names=None):
    names = logger.names if names == None else names
    numbers = logger.numbers
    for _, name in enumerate(names):
        x = np.arange(len(numbers[name]))
        if name in ['Train Acc.', 'Valid Acc.']:
            plt.plot(x, 100-np.asarray(numbers[name], dtype='float'))
        else:
            plt.plot(x, np.asarray(numbers[name]))
    return [logger.title + '(' + name + ')' for name in names] 
Example 47
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 48
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 49
Project: cplot   Author: sunchaoatmo   File: cstimeserial.py    GNU General Public License v3.0 5 votes vote down vote up
def corplot(data,vname):
  filename=data.plotname+"_"+"".join(vname)
  outputformat="pdf"
  if outputformat=="pdf":
    pp = PdfPages(filename+'.pdf')
  else:
    page=0
  fig = plt.figure()
  gs0 = gridspec.GridSpec(1,1 )
  ax1 = plt.subplot(gs0[0])
  import numpy as np
  for casenumber,case in enumerate(data.plotlist):
    #units_cur=data.time[case][vname].units
    #calendar_cur=data.time[case][vname].calendar
    legname = sim_nicename.get(case,case)
    color1=tableau20[2*(casenumber)] 
    plt.plot(data.plotdata[case][vname][:],label=legname,color=color1,lw=0.8)
    leg=ax1.legend(loc=1,borderaxespad=0.,frameon=False, fontsize=6)

  plt.ylim([0.8,1.0])
  #plt.xlim([0.,150])
  
  if outputformat=="pdf":
    pp.savefig()
  else:
    figurename=filename+str(page)+"."+outputformat
    page+=1
    fig.savefig(figurename,format=outputformat,dpi=300) #,dpi=300)
  fig.clf()
  if outputformat=="pdf":
    pp.close() 
Example 50
Project: deep-learning-note   Author: wdxtub   File: utils.py    MIT License 5 votes vote down vote up
def show_trace_2d(f, results):
    plt.plot(*zip(*results), '-o', color='#ff7f0e')
    x1, x2 = np.meshgrid(np.arange(-5.5, 1.0, 0.1), np.arange(-3.0, 1.0, 0.1))
    plt.contour(x1, x2, f(x1, x2), colors='#1f77b4')
    plt.xlabel('x1')
    plt.ylabel('x2')
    plt.show()