Python matplotlib.pyplot.subplots() Examples

The following are code examples for showing how to use matplotlib.pyplot.subplots(). 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: Gnip-Tweet-Evaluation   Author: twitterdev   File: output.py    MIT License 8 votes vote down vote up
def local_timeline_plot(minute_dict, title, output_path_base):
    """ plot timeline of users Tweeting, hour granularity, local time """
    minute = minute_dict.items()
    hour_dict = defaultdict(int)
    for key, value in minute_dict.items():
        hour_dict[key.split(':')[0]] += value
    hour = hour_dict.items()
    times_values = sorted([ (datetime.datetime.strptime(x[0], '%H'), x[1]) for x in hour ], key=lambda x: x[0])
    times = [ x[0] for x in times_values ]
    values = [ x[1] for x in times_values ]
    fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 4))
    ax.plot(times, values)
    ax.set_xlabel("Users' local time", size=14)
    ax.set_ylabel('Tweets per hour', size=16)
    ax.set_title('When users Tweet during the day (based on local time)', size=14)
    ax.xaxis.set_major_formatter(dates.DateFormatter('%H:%M'))
    fig.autofmt_xdate()
    fig.savefig(output_path_base + title + '.png') 
Example 2
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 3
Project: dc_tts   Author: Kyubyong   File: utils.py    Apache License 2.0 6 votes vote down vote up
def plot_alignment(alignment, gs, dir=hp.logdir):
    """Plots the alignment.

    Args:
      alignment: A numpy array with shape of (encoder_steps, decoder_steps)
      gs: (int) global step.
      dir: Output path.
    """
    if not os.path.exists(dir): os.mkdir(dir)

    fig, ax = plt.subplots()
    im = ax.imshow(alignment)

    fig.colorbar(im)
    plt.title('{} Steps'.format(gs))
    plt.savefig('{}/alignment_{}.png'.format(dir, gs), format='png')
    plt.close(fig) 
Example 4
Project: deep-learning-note   Author: wdxtub   File: 8_kmeans_pca.py    MIT License 6 votes vote down vote up
def plot_n_image(X, n):
    """ plot first n images
    n has to be a square number
    """
    pic_size = int(np.sqrt(X.shape[1]))
    grid_size = int(np.sqrt(n))

    first_n_images = X[:n, :]

    fig, ax_array = plt.subplots(nrows=grid_size, ncols=grid_size,
                                    sharey=True, sharex=True, figsize=(8, 8))

    for r in range(grid_size):
        for c in range(grid_size):
            ax_array[r, c].imshow(first_n_images[grid_size * r + c].reshape((pic_size, pic_size)))
            plt.xticks(np.array([]))
            plt.yticks(np.array([])) 
Example 5
Project: keras-anomaly-detection   Author: chen0040   File: h2o_ecg_pulse_detection.py    MIT License 6 votes vote down vote up
def plot_bidimensional(model, test, recon_error, layer, title):
    bidimensional_data = model.deepfeatures(test, layer).cbind(recon_error).as_data_frame()

    cmap = cm.get_cmap('Spectral')

    fig, ax = plt.subplots()
    bidimensional_data.plot(kind='scatter',
                            x='DF.L{}.C1'.format(layer + 1),
                            y='DF.L{}.C2'.format(layer + 1),
                            s=500,
                            c='Reconstruction.MSE',
                            title=title,
                            ax=ax,
                            colormap=cmap)
    layer_column = 'DF.L{}.C'.format(layer + 1)
    columns = [layer_column + '1', layer_column + '2']
    for k, v in bidimensional_data[columns].iterrows():
        ax.annotate(k, v, size=20, verticalalignment='bottom', horizontalalignment='left')
    fig.canvas.draw()
    plt.show() 
Example 6
Project: machine_learning   Author: Gabrielchapo   File: myNN.py    MIT License 6 votes vote down vote up
def fit(self, X, Y, epoch, verbose=0):

        self.input = X
        self.output = Y
        self.err = []

        if epoch <= 0:
            print("Invalid number of epochs")
            return
        for i in range(epoch):
            self.feedforward()
            self.backprop()
            err = error(self.activated[self.layers[self.nb_layers - 1]["name"]], self.output)
            self.err.append(err)
            if verbose == 1:
                print("Epoch:", i + 1, "/", epoch, "=== Loss:", err)
        fig, ax = plt.subplots()
        ax.plot(self.err)
        ax.set(xlabel='epochs', ylabel='loss')
        plt.show() 
Example 7
Project: smach_based_introspection_framework   Author: birlrobotics   File: visualize_dataset.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_list_of_df(save_folder, list_of_df, list_of_labels):
    print 'plot_list_of_df with save_folder %s'%save_folder
    if len(list_of_df) == 0:
        return
    dims = list_of_df[0].columns
    for dim in dims:
        fig, ax = plt.subplots(nrows=1, ncols=1)
        lgds = []

        for idx, df in enumerate(list_of_df):
            label = list_of_labels[idx]
            ax.plot(df[dim], label=label)

        ax.set_title('...'+(save_folder+', '+dim)[-70:])

        handles, labels = ax.get_legend_handles_labels()
        lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))

        fig.savefig(os.path.join(save_folder, dim.replace('.', '>')), format='png', bbox_extra_artists=(lgd,), bbox_inches='tight')

        plt.close(fig)
    pass 
Example 8
Project: smach_based_introspection_framework   Author: birlrobotics   File: redis_based_anomaly_classification.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_resampled_anomaly_df(resampled_anomaly_df):
    import datetime
    realtime_anomaly_plot_dir = os.path.join(realtime_anomaly_plot_folder, str(datetime.datetime.now()))

    if not os.path.isdir(realtime_anomaly_plot_dir):
        os.makedirs(realtime_anomaly_plot_dir)

    for dim in resampled_anomaly_df.columns:
        rospy.loginfo("plotting %s"%dim)
        fig, ax = plt.subplots(nrows=1, ncols=1)
        time_x = resampled_anomaly_df.index-resampled_anomaly_df.index[0]
        ax.plot(
            time_x.tolist(),
            resampled_anomaly_df[dim].tolist(), 
        )
        ax.set_title(dim)
        fig.savefig(os.path.join(realtime_anomaly_plot_dir, (dim+'.png').strip('.')))
        plt.close(fig) 
Example 9
Project: multi-dimensional-topic-model   Author: LaoWang-Lab   File: plot.py    MIT License 6 votes vote down vote up
def plot_fig(json_file, save_fig=False):
    with open(json_file) as f:
        data = json.load(f)
    H, E, M, wot, iter = data['H'], data['E'], data['M'], data['wot'], data['iter']
    fig, axs = plt.subplots(E, H, figsize=(2.5 * E, 3.5 *H), sharex=True)
    fig.suptitle('H:%d E:%d M:%d wot:%d iter:%d' % (H, E, M, wot, iter), fontsize=20, fontweight='bold')
    n_het = np.array(data['topic'])
    y_limits_max = 1.05 * n_het.sum() / (E * H * wot)
    x = np.arange(data['T'])
    for e in range(data['E']):
        for h in range(data['H']):
            # print(len(x), np.shape(n_het), np.shape(axs))
            sns.barplot(x, n_het[h,e,:], palette="Set3", ax=axs[e][h])
            axs[e][h].set_ylabel("counts")
            axs[e][h].set_title("h:%d e:%d" % (h,e))
            axs[e][h].set_ylim([0, y_limits_max])
    plt.tight_layout()
    fig.subplots_adjust(top=0.9)
    if save_fig:
        i = data['iter']
        plt.savefig('%s/iter%03d.png' % (os.path.dirname(json_file), i), dpi=72, format='png')
    else:
        plt.show()
    plt.close() 
Example 10
Project: reportengine   Author: NNPDF   File: actions.py    GNU General Public License v2.0 6 votes vote down vote up
def plot_roc(fit_result, algorithm, dataset,
        fpr_threshold:(float, type(None))=None):
    """Plot the ROC curve for each category. Mark the true positive
    rate at the ``fpr_threshold`` if given"""
    probs = fit_result.predict_proba(dataset.data)
    fig, ax = plt.subplots()
    for i, label in enumerate(dataset.target_names):
        y_pred = probs[:,i]
        y_true = (dataset.target == i)
        fpr, tpr, _ = roc_curve(y_true, y_pred)
        color = f'C{i}'
        ax.plot(fpr, tpr, label=label, color=color)
        if fpr_threshold is not  None:
            pos = np.searchsorted(fpr, fpr_threshold)
            ax.axhline(tpr[pos], linestyle='--', lw=0.5, color=color)

    ax.set_xlabel("False Positive rate")
    ax.set_ylabel("True Positive rate")
    ax.set_title("ROC curve")
    ax.legend()

    return fig 
Example 11
Project: Graphvy   Author: anbarief   File: graphvy.py    MIT License 6 votes vote down vote up
def gen_plot(self, obj):

        if len(self.graph.nodes) > 0:

            self.fig, self.ax = plt.subplots()
            self.ax.set_axis_bgcolor(Window.clearcolor)
            self.ax.axis('square')
            for e in self.graph.edges:
                points = e.line_coordinates
                self.ax.plot([points[0], points[2]], [points[1], points[3]], '-', color = e.color)

            for i in self.graph.nodes:
                x, y = i.coordinates[0], i.coordinates[1]
                circle = Circle(xy = [x, y], radius = 12.5, fc = i.visual_color, ec = "black")
                self.ax.add_patch(circle)
                self.ax.text(x, y, i.visual_text, fontsize = 8)

        
            self.ax.set_xlim([self.graph.nodes_xmin, self.graph.nodes_xmax])
            self.ax.set_ylim([self.graph.nodes_ymin, self.graph.nodes_ymax])
            plt.show(self.fig) 
Example 12
Project: trunklucator   Author: Dumbris   File: plot_perf.py    Apache License 2.0 6 votes vote down vote up
def plot_performance(performance_history):
    fig, ax = plt.subplots(figsize=(8.5, 6), dpi=130)

    ax.plot(performance_history)
    ax.scatter(range(len(performance_history)), performance_history, s=13)

    ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins=5, integer=True))
    ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins=10))
    ax.yaxis.set_major_formatter(mpl.ticker.PercentFormatter(xmax=1))

    ax.set_ylim(bottom=0, top=1)
    ax.grid(True)

    ax.set_title('Incremental classification accuracy')
    ax.set_xlabel('Query iteration')
    ax.set_ylabel('Classification Accuracy')

    image = BytesIO()
    plt.plot()
    plt.savefig(image, format='png')
    plt.cla()
    plt.close(fig)
    return ''' <img src="data:image/png;base64,{}" border="0" /> '''.format(base64.encodebytes(image.getvalue()).decode()) 
Example 13
Project: PheKnowLator   Author: callahantiff   File: KGEmbeddingVisualizer.py    Apache License 2.0 6 votes vote down vote up
def plots_embeddings(colors, names, groups, legend_arg, label_size, tsne_size, title, title_size):

    # set up plot
    fig, ax = plt.subplots(figsize=(15, 10))
    ax.margins(0.05)

    # iterate through groups to layer the plot
    for name, group in groups:
        ax.plot(group.x, group.y, marker='o', linestyle='', ms=6, label=names[name],
                color=colors[name], mec='none', alpha=0.8)

    plt.legend(handles=legend_arg[0], fontsize=legend_arg[1], frameon=False, loc=legend_arg[2], ncol=legend_arg[3])

    ax.tick_params(labelsize=label_size)
    plt.ylim(-(tsne_size + 5), tsne_size)
    plt.xlim(-tsne_size, tsne_size)
    plt.title(title, fontsize=title_size)
    plt.show()
    plt.close() 
Example 14
Project: euclid   Author: njpayne   File: regressors.py    GNU General Public License v2.0 6 votes vote down vote up
def run_linear_regression(training_features, training_labels, test_features, test_labels, passed_parameters = None, headings = ["Linear"]):
    

    #set up linear regressor
    estimator = linear_model.LinearRegression(fit_intercept = True)

    estimator.fit(training_features, training_labels)

    prediction = estimator.predict(X = test_features)
    score = estimator.score(X = test_features, y = test_labels)

    if(training_features.shape[1] == 1):

        fig, ax = plt.subplots()
        ax.scatter(training_labels, prediction)
        ax.plot([training_labels.min(), training_labels.max()], [training_labels.min(), training_labels.max()], 'k--', lw=4)
        ax.set_xlabel('Measured')
        ax.set_ylabel('Predicted')
        pylab.savefig(os.path.join(results_location, "Linear - " + headings[-1] + '.png'))

    return prediction, score 
Example 15
Project: where   Author: kartverket   File: sisre_report.py    MIT License 6 votes vote down vote up
def _plot_histogram_subplot(data, axis, system):
    """Plot histogram subplots

    Args:
       data (numpy.ndarray):    Data to plot.
       axis (AxesSubplot):      Subplot axes.
       system (str):            GNSS system identifier (e.g. E, G, ...)
    """
    axis.hist(data, normed=True, bins=30)
    axis.set(xlabel="SISRE [m]", ylabel="Frequency")
    axis.set_title(f"{GNSS_NAME[system]}")
    mean = np.mean(data)
    std = np.std(data)
    axis.text(
        0.98,
        0.98,
        f"$mean={mean:5.3f}\ \pm {std:5.3f}$ m",
        horizontalalignment="right",
        verticalalignment="top",
        transform=axis.transAxes,
    ) 
Example 16
Project: kss   Author: Kyubyong   File: utils.py    Apache License 2.0 6 votes vote down vote up
def plot_alignment(alignment, gs, dir=hp.logdir):
    """Plots the alignment.

    Args:
      alignment: A numpy array with shape of (encoder_steps, decoder_steps)
      gs: (int) global step.
      dir: Output path.
    """
    if not os.path.exists(dir): os.mkdir(dir)

    fig, ax = plt.subplots()
    im = ax.imshow(alignment)

    fig.colorbar(im)
    plt.title('{} Steps'.format(gs))
    plt.savefig('{}/alignment_{}.png'.format(dir, gs), format='png') 
Example 17
Project: RFMLS-NEU   Author: neu-spiral   File: sysmonitor.py    MIT License 6 votes vote down vote up
def plot(self, title, vert=False):
        if not self.utils:
            print "Nothing to plot here."
            exit(1)
        if vert:
            fig, ax = plt.subplots(2, 1, figsize=(15, 6))
        else:
            fig, ax = plt.subplots(1, 2, figsize=(15, 6))
        fig.suptitle(title, size=24)
        ax[0].title.set_text('GPU Utilization')
        for i in range(len(self.utils['gpu'][0])):
            ax[0].plot([u[i] for u in self.utils['gpu']], label="gpu:%d"%i)
        ax[0].set_ylim([0, 100])
        ax[1].title.set_text('CPU')
        ax[1].plot(self.utils['cpu'])
        plt.legend(loc='best')
        plt.tight_layout(rect=[0, 0.03, 1, 0.9])
        plt.savefig('./result/%s.png' % title) 
Example 18
Project: rtreelib   Author: sergkr   File: diagram.py    MIT License 6 votes vote down vote up
def plot_rtree(tree: RTreeBase, filename=None, show=True, highlight_node=None, highlight_entry=None):
    """
    Create a cartesian plot (using matplotlib) of the R-Tree nodes/entries. Each node's bounding rectangle
    is plotted as a tan rectangle with dashed edges, and each leaf entry's bounding rectangle is plotted in
    blue. A particular node or entry may be highlighted in the plot by passing in highlight_node and/or
    highlight_entry.
    :param tree: R-Tree instance to plot
    :param filename: If passed in, the plot will be saved to a file
    :param show: If True, show the plot
    :param highlight_node: R-Tree node to highlight
    :param highlight_entry: R-Tree leaf entry to highlight
    """
    fig, ax = plt.subplots(1)
    bbox = tree.root.get_bounding_rect()
    padx, pady = (0.1 * bbox.width, 0.1 * bbox.height)
    ax.set_xlim(left=bbox.min_x - padx, right=bbox.max_x + padx)
    ax.set_ylim(bottom=bbox.min_y - pady, top=bbox.max_y + pady)
    _plot_rtree_leaves(ax, tree, highlight_entry)
    _plot_rtree_nodes(ax, tree, highlight_node)
    if filename:
        plt.savefig(filename, bbox_inches='tight')
    if show:
        plt.show()
    plt.close(fig) 
Example 19
Project: xia2   Author: xia2   File: plot_multiplicity.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, scene, settings=None):
        import matplotlib

        matplotlib.use("Agg")
        from matplotlib import pyplot

        render_2d.__init__(self, scene, settings)

        self._open_circle_points = flex.vec2_double()
        self._open_circle_radii = []
        self._open_circle_colors = []
        self._filled_circle_points = flex.vec2_double()
        self._filled_circle_radii = []
        self._filled_circle_colors = []

        self.fig, self.ax = pyplot.subplots(figsize=self.settings.size_inches)
        self.render(self.ax)
        pyplot.close() 
Example 20
Project: Stock_Market_Forecast   Author: cuevas1208   File: matplot_graphs.py    MIT License 6 votes vote down vote up
def plot_histogram(p, t, dates, name='stock', confidence='???', forecast='???'):
    fig, ax = plt.subplots()

    ax.plot(p, C='g', label='prediction')
    ax.plot(t, C='b', label='ground truth')
    ax.legend()

    # window dimensions
    plt.axis([0, len(dates)/2, np.min(p)-1, np.max(t)+1])

    # x labels
    plt.xticks(range(len(dates)), dates)

    mng = plt.get_current_fig_manager()
    mng.window.state('zoomed')  # works fine on Windows!

    plt.xlabel('forecast for ' + str(forecast) + ' days from the above date')
    plt.ylabel('buy(1), hold(0), sell(-1)')
    plt.title(name + ' model confidence ' + str(confidence))

    plt.show() 
Example 21
Project: CrossLingualDepParser   Author: uclanlp   File: distance.py    GNU General Public License v3.0 6 votes vote down vote up
def draw_heatmap(arr, xs, ys):
    fig, ax = plt.subplots()
    im = ax.imshow(arr)
    #
    ax.set_xticks(np.arange(len(xs)))
    ax.set_yticks(np.arange(len(ys)))
    ax.set_xticklabels(xs)
    ax.set_yticklabels(ys)
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
         rotation_mode="anchor")
    for i in range(len(xs)):
        for j in range(len(ys)):
            text = ax.text(j, i, "%.1f"%(arr[i, j]*100),
                           ha="center", va="center", color="w")
    fig.tight_layout()
    plt.show() 
Example 22
Project: distinctipy   Author: alan-turing-institute   File: examples.py    MIT License 6 votes vote down vote up
def compare_colors(N=36, compare_with='tab20'):
    """
    Compare colour swatches for distinctipy and a given matplotlib colormap for N colours.
    :param N: Number of colours to generate
    :param compare_with: str representing name of a built-in matplotlib colormap
    :return:
    """

    colors_distinctipy = distinctipy.get_colors(N, exclude_colors=[(1, 1, 1), (0, 0, 0)], return_excluded=False)

    cmap = matplotlib.cm.get_cmap(compare_with)
    if type(cmap) is matplotlib.colors.ListedColormap:
        colors_compare = [cmap.colors[i % len(cmap.colors)] for i in range(N)]

    else:
        colors_compare = [cmap(i) for i in np.linspace(0, 1, N)]

    fig, axes = plt.subplots(1, 2, figsize=(12, 5))

    distinctipy.color_swatch(colors_distinctipy, ax=axes[0], title='distinctipy')
    distinctipy.color_swatch(colors_compare, ax=axes[1], title=compare_with)

    plt.show() 
Example 23
Project: graphtimer   Author: Peilonrayz   File: test_plot.py    MIT License 6 votes vote down vote up
def test_peilonrayz_plot():
    fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
    p = Plotter(se_code.Peilonrayz)
    axis = [
        ('Range', {'args_conv': range}),
        ('List', {'args_conv': lambda i: list(range(i))}),
        ('Unoptimised', {'args_conv': se_code.UnoptimisedRange}),
    ]
    for graph, (title, kwargs) in zip(iter(flat(axs)), axis):
        (
            p.repeat(100, 5, list(range(0, 10001, 1000)), **kwargs)
                .min(errors=((-1, 3), (-1, 4)))
                .plot(graph, title=title)
        )
    fig.savefig('static/figs/peilonrayz.png')
    fig.savefig('static/figs/peilonrayz.svg') 
Example 24
Project: cat-bbs   Author: aleju   File: plotting.py    MIT License 5 votes vote down vote up
def __init__(self, titles, increasing, save_to_fp):
        assert len(titles) == len(increasing)
        n_plots = len(titles)
        self.titles = titles
        self.increasing = dict([(title, incr) for title, incr in zip(titles, increasing)])
        self.colors = ["red", "blue", "cyan", "magenta", "orange", "black"]

        self.nb_points_max = 500
        self.save_to_fp = save_to_fp
        self.start_batch_idx = 0
        self.autolimit_y = False
        self.autolimit_y_multiplier = 5

        #self.fig, self.axes = plt.subplots(nrows=2, ncols=2, figsize=(20, 20))
        nrows = max(1, int(math.sqrt(n_plots)))
        ncols = int(math.ceil(n_plots / nrows))
        width = ncols * 10
        height = nrows * 10

        self.fig, self.axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(width, height))

        if nrows == 1 and ncols == 1:
            self.axes = [self.axes]
        else:
            self.axes = self.axes.flat

        title_to_ax = dict()
        for idx, (title, ax) in enumerate(zip(self.titles, self.axes)):
            title_to_ax[title] = ax
        self.title_to_ax = title_to_ax

        self.fig.tight_layout()
        self.fig.subplots_adjust(left=0.05) 
Example 25
Project: fenics-topopt   Author: zfergus   File: gui.py    MIT License 5 votes vote down vote up
def __init__(self, nelx, nely, title=""):
        """Initialize plot and plot the initial design"""
        plt.ion()  # Ensure that redrawing is possible
        self.fig, self.ax = plt.subplots()
        self.im = self.ax.imshow(-np.zeros((nelx, nely)).T, cmap='gray',
            interpolation='none', norm=colors.Normalize(vmin=-1, vmax=0))
        plt.xlabel(title)
        # self.fig.tight_layout()
        self.fig.show()
        self.nelx, self.nely = nelx, nely 
Example 26
Project: fenics-topopt   Author: zfergus   File: gui.py    MIT License 5 votes vote down vote up
def __init__(self, nelx, nely, title=""):
        """Initialize plot and plot the initial design"""
        plt.ion()  # Ensure that redrawing is possible
        self.fig, self.ax = plt.subplots()
        self.im = self.ax.imshow(-np.zeros((nelx, nely)).T, cmap='gray',
            interpolation='none', norm=colors.Normalize(vmin=-1, vmax=0))
        plt.xlabel(title)
        # self.fig.tight_layout()
        self.fig.show()
        self.nelx, self.nely = nelx, nely 
Example 27
Project: Collaborative-Learning-for-Weakly-Supervised-Object-Detection   Author: Sunarker   File: demo.py    MIT License 5 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor='red', linewidth=3.5)
            )
        ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                  fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw() 
Example 28
Project: FasterRCNN_TF_Py3   Author: upojzsb   File: demo.py    MIT License 5 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor='red', linewidth=3.5)
        )
        ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                 fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw() 
Example 29
Project: Py-Utils   Author: LonamiWebs   File: memory.py    MIT License 5 votes vote down vote up
def plot_ways(policy='lru'):
    if np is None or plt is None:
        print('numpy and matplotlib are required for plotting')
        return
    
    fig, ax = plt.subplots()
    refs = '1 65 129 193 1 129 1 65 129 1 1 65 129 129'
    psize = 4
    partc = 16
    
    ways = []
    hits = []
    miss = []
    
    wayc = 1 
    while wayc <= partc:
        c = Cache(psize, partc, wayc, policy)
        c.access_all(refs)
        ways.append(wayc)
        hits.append(c.hits)
        miss.append(c.misses)
        wayc *= 2
        print(c)
    
    ax.plot(ways, hits, 'go-', label='hits', linewidth=1)
    ax.plot(ways, miss, 'ro-', label='misses', linewidth=1)
    
    ax.set_ylabel('Count (using '+policy.upper()+')')
    ax.set_xlabel('Number of ways')
    ax.legend()
    
    ax.set_xscale('log', basex=2)
    plt.show() 
Example 30
Project: Py-Utils   Author: LonamiWebs   File: memory.py    MIT License 5 votes vote down vote up
def plot_psize():
    if np is None or plt is None:
        print('numpy and matplotlib are required for plotting')
        return
    
    fig, ax = plt.subplots()
    refs = '1 4 8 5 20 17 19 56 9 11 4 43 5 6 9 17 181'
    psize = 1
    partc = 16
    
    xaxe = []
    hits = []
    miss = []
    
    while partc >= 1:
        c = Cache(psize, partc)
        c.access_all(refs)
        xaxe.append(psize)
        hits.append(c.hits)
        miss.append(c.misses)
        psize *= 2
        partc //= 2
        print(c)
    
    ax.plot(xaxe, hits, 'go-', label='hits', linewidth=1)
    ax.plot(xaxe, miss, 'ro-', label='misses', linewidth=1)
    
    ax.set_ylabel('Count')
    ax.set_xlabel('Partition size (total size constant)')
    ax.legend()
    
    ax.set_xscale('log', basex=2)
    plt.show() 
Example 31
Project: fbpconv_tf   Author: panakino   File: util.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_prediction(x_test, y_test, prediction, save=False):
    import matplotlib
    import matplotlib.pyplot as plt
    
    test_size = x_test.shape[0]
    fig, ax = plt.subplots(test_size, 3, figsize=(12,12), sharey=True, sharex=True)
    
    x_test = crop_to_shape(x_test, prediction.shape)
    y_test = crop_to_shape(y_test, prediction.shape)
    
    ax = np.atleast_2d(ax)
    for i in range(test_size):
        cax = ax[i, 0].imshow(x_test[i])
        plt.colorbar(cax, ax=ax[i,0])
        cax = ax[i, 1].imshow(y_test[i, ..., 1])
        plt.colorbar(cax, ax=ax[i,1])
        pred = prediction[i, ..., 1]
        pred -= np.amin(pred)
        pred /= np.amax(pred)
        cax = ax[i, 2].imshow(pred)
        plt.colorbar(cax, ax=ax[i,2])
        if i==0:
            ax[i, 0].set_title("x")
            ax[i, 1].set_title("y")
            ax[i, 2].set_title("pred")
    fig.tight_layout()
    
    if save:
        fig.savefig(save)
    else:
        fig.show()
        plt.show() 
Example 32
Project: neural-fingerprinting   Author: StephanZheng   File: fp_eval.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_pr_auc(pr_results, args, plot=False, plot_name=""):
    xys = [(0.0, 1.0, 0.)]
    labels = []
    for tau, result in pr_results.items():
        xys += [(pr_results[tau]["recall"], pr_results[tau]["prec"], tau)]
        labels += [tau]

    xys.sort(key=lambda x: x[0])
    xs = [i[0] for i in xys]
    ys = [i[1] for i in xys]

    # print("pr")
    # for i in sorted(xys, key=lambda x: x[-1]): print(i)

    # print("recall", xs)
    # print("precis", ys)
    _auc = auc(xs, ys)

    if plot:
        fig, ax = plt.subplots(nrows=1, ncols=1)
        ax.plot(xs, ys, 'go-',)

        for label, x, y in zip(labels, xs, ys):
            ax.annotate(
                label,
                xy=(x, y), xytext=(-20, 20),
                textcoords='offset points', ha='right', va='bottom',
                bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
                arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

        path = os.path.join(args.log_dir, "pr-{}.svg".format(plot_name))
        print("Storing PR plot in", path)
        fig.savefig(path)
        plt.close(fig)

    return _auc 
Example 33
Project: neural-fingerprinting   Author: StephanZheng   File: fp_eval.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_roc_auc(pr_results, args, plot=False, plot_name=""):
    xys = [(0.0, 0.0, 0.0)]
    labels = []
    for tau, result in pr_results.items():
        xys += [(pr_results[tau]["fpr"], pr_results[tau]["tpr"], tau)]
        labels += [tau]

    xys.sort(key=lambda x: x[0])
    xs = [i[0] for i in xys]
    ys = [i[1] for i in xys]

    # print("roc")
    # for i in sorted(xys, key=lambda x: x[-1]): print(i)

    # print("fpr", xs)
    # print("tpr", ys)
    _auc = auc(xs, ys)

    if plot:
        fig, ax = plt.subplots(nrows=1, ncols=1)
        ax.plot(xs, ys, 'go-',)

        for label, x, y in zip(labels, xs, ys):
            ax.annotate(
                label,
                xy=(x, y), xytext=(-20, 20),
                textcoords='offset points', ha='right', va='bottom',
                bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
                arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

        path = os.path.join(args.log_dir, "roc-{}.svg".format(plot_name))
        print("Storing ROC plot in", path)
        fig.savefig(path)
        plt.close(fig)

    return _auc 
Example 34
Project: skylab   Author: coenders   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def skymap(plt, vals, **kwargs):
    fig, ax = plt.subplots(subplot_kw=dict(projection="aitoff"))

    gridsize = 1000

    x = np.linspace(np.pi, -np.pi, 2 * gridsize)
    y = np.linspace(np.pi, 0., gridsize)

    X, Y = np.meshgrid(x, y)

    r = hp.rotator.Rotator(rot=(-180., 0., 0.))

    YY, XX = r(Y.ravel(), X.ravel())

    pix = hp.ang2pix(hp.npix2nside(len(vals)), YY, XX)

    Z = np.reshape(vals[pix], X.shape)

    lon = x[::-1]
    lat = np.pi /2.  - y

    cb = kwargs.pop("colorbar", dict())
    cb.setdefault("orientation", "horizontal")
    cb.setdefault("fraction", 0.075)

    title = cb.pop("title", None)

    p = ax.pcolormesh(lon, lat, Z, **kwargs)

    cbar = fig.colorbar(p, **cb)

    cbar.solids.set_edgecolor("face")
    cbar.update_ticks()
    if title is not None:
        cbar.set_label(title)

    ax.xaxis.set_ticks([])

    return fig, ax 
Example 35
Project: deep-learning-note   Author: wdxtub   File: 5_softmax_regression_raw.py    MIT License 5 votes vote down vote up
def show_fashion_mnist(images, labels):
    _, figs = plt.subplots(1, len(images), figsize=(12, 12))
    for f, img, lbl in zip(figs, images, labels):
        f.imshow(img.view((28, 28)).numpy())
        f.set_title(lbl)
        f.axes.get_xaxis().set_visible(False)
        f.axes.get_yaxis().set_visible(False)
    plt.show()


# 定义 softmax 
Example 36
Project: deep-learning-note   Author: wdxtub   File: utils.py    MIT License 5 votes vote down vote up
def show_images(imgs, num_rows, num_cols, scale=2):
    figsize = (num_cols * scale, num_rows * scale)
    _, axes = plt.subplots(num_rows, num_cols, figsize=figsize)
    for i in range(num_rows):
        for j in range(num_cols):
            axes[i][j].imshow(imgs[i * num_cols + j])
            axes[i][j].axes.get_xaxis().set_visible(False)
            axes[i][j].axes.get_yaxis().set_visible(False)
    plt.show()
    return axes 
Example 37
Project: GST-Tacotron   Author: KinglittleQ   File: utils.py    MIT License 5 votes vote down vote up
def plot_alignment(alignment, gs):
    """Plots the alignment
    alignments: A list of (numpy) matrix of shape (encoder_steps, decoder_steps)
    gs : (int) global step
    """
    fig, ax = plt.subplots()
    im = ax.imshow(alignment)

    # cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
    fig.colorbar(im)
    plt.title('{} Steps'.format(gs))
    plt.savefig('{}/alignment_{}k.png'.format(hp.logdir, gs // 1000), format='png') 
Example 38
Project: ReinforcementLearningBookExamples   Author: Shawn-Guo-CN   File: 2GridWorld_Ch3.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_image(title, image):
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0,0,1,1])

    nrows, ncols = image.shape
    width, height = 1.0 / ncols, 1.0 / nrows

    # Add cells
    for (i,j), val in np.ndenumerate(image):
        # Index either the first or second item of bkg_colors based on
        # a checker board pattern
        idx = [j % 2, (j + 1) % 2][i % 2]
        color = 'white'

        tb.add_cell(i, j, width, height, text=val,
                    loc='center', facecolor=color)

    # Row Labels...
    for i, label in enumerate(range(len(image))):
        tb.add_cell(i, -1, width, height, text=label+1, loc='right',
                    edgecolor='none', facecolor='none')
    # Column Labels...
    for j, label in enumerate(range(len(image))):
        tb.add_cell(-1, j, width, height/2, text=label+1, loc='center',
                           edgecolor='none', facecolor='none')
    ax.add_table(tb)
    plt.suptitle(title)
    plt.show() 
Example 39
Project: beta3_IRT   Author: yc14600   File: plots.py    MIT License 5 votes vote down vote up
def plot_probabilities(X, probabilities, titles, suptitle):
    norm = plt.Normalize(0, 1)
    n = len(titles)

    nrows = int(np.ceil(n / 2))

    sns.set_context('paper')
    cmap = sns.cubehelix_palette(rot=-.5,light=1.5,dark=-.5,as_cmap=True)

    f, axarr = plt.subplots(nrows, min(n,2))
    if n < 2:
        axarr.scatter(X[:, 0], X[:, 1], c=probabilities[0],
                            cmap=cmap, norm=norm, edgecolor='k',s=60)
        axarr.set_title(titles[0])
        #f.set_size_inches(8, 8)
    else:

        i = j = 0
        for idx, t in enumerate(titles):
            axarr[i, j].scatter(X[:, 0], X[:, 1], c=probabilities[idx],
                                cmap=cmap, norm=norm, edgecolor='k')
            axarr[i, j].set_title(t)
            j += 1
            if j == 2:
                j = 0
                i += 1
        if n % 2 != 0:
            axarr[-1, -1].axis('off')
        f.set_size_inches(10, 30)

    f.suptitle(suptitle)    
    f.subplots_adjust(hspace=0.7)
    return f 
Example 40
Project: CAFA_assessment_tool   Author: ashleyzhou972   File: PrettyIO.py    GNU General Public License v3.0 5 votes vote down vote up
def print_enrichment_chart(file_handle, vals, title):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        print("Error while printing. To use this functionality you need to have matplotlib installed.", file=sys.stderr)
    else:
        fig, ax1 = plt.subplots()
        
        xs = list(range(len(vals)))
        ys =  vals
        
        ax1.plot(xs, ys)
        
        bar_ys = [int(ys[0] > 0)]
        for i in range(1, len(ys)):
            bar_ys.append(int(ys[i] > ys[i - 1]))
        bar_ys = [bar_ys]
        
        pos = ax1.axes.get_position()
        
        ax0 = fig.add_axes([pos.x0, pos.y1, pos.width, 0.1])
        
        ax0.imshow(bar_ys, cmap=plt.cm.Blues, interpolation='nearest')
        ax0.axes.get_yaxis().set_visible(False)
        ax0.axes.get_xaxis().set_visible(False)
        ax0.set_title(title)
        
        plt.savefig(file_handle, bbox_inches=0)
        plt.close() 
Example 41
Project: DiscEvolution   Author: rbooth200   File: makeMovie_chem.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, r, t, epsilon, C, O):
        self.r = r
        self.t = t
        self.eps = epsilon
        self.C = C
        self.O = O

        # Set up the initial figures
        self._f, self._subs = plt.subplots(3,1,sharex=True)
        
        rmin = 0.3
        rmax = r.max()

        # Dust to gas ratio:
        s = self._subs[0]
        self._leps, = s.loglog([],[], 'k')
        s.set_xlim(rmin, rmax)
        s.set_ylim(1e-4, 1e-1)
        s.set_ylabel('$\epsilon$')
                   
        # Carbon / Oxygen abundance
        s = self._subs[1]
        self._lC,    = s.loglog([],[], 'k',  label='C')
        self._lO,    = s.loglog([],[], 'c',  label='O')
        self._lCg,   = s.loglog([],[], 'k:', label='C (grain)')
        self._lOg,   = s.loglog([],[], 'c:', label='O (grain)')
        
        s.legend(ncol=2)

        s.set_xlim(rmin, rmax)
        s.set_ylim(0.1, 50)
        s.set_ylabel('$[X]_\mathrm{solar}$')

        # C/O ratio
        s = self._subs[2]
        self._lCO,  = s.semilogx([],[], 'k')
        self._lCOg, = s.semilogx([],[], 'k:')
        s.set_xlim(rmin, rmax)
        s.set_ylim(0, 3)
        s.set_ylabel('$[C/O]_\mathrm{solar}$')
        s.set_xlabel('$R\,[\mathrm{au}]$') 
Example 42
Project: DiscEvolution   Author: rbooth200   File: makeMovie_chem_slide.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, r, t, epsilon, C, O):
        self.r = r
        self.t = t
        self.eps = epsilon
        self.C = C
        self.O = O

        # Set up the initial figures
        self._f, self._subs = plt.subplots(3,1,sharex=True)
        
        rmin = 0.3
        rmax = r.max()

        # Dust to gas ratio:
        s = self._subs[0]
        self._leps, = s.loglog([],[], 'k')
        s.set_xlim(rmin, rmax)
        s.set_ylim(1e-4, 1e-1)
        s.set_ylabel('$\epsilon$')
                   
        # Carbon / Oxygen abundance
        s = self._subs[1]
        self._lC,    = s.loglog([],[], 'k',  label='C')
        self._lO,    = s.loglog([],[], 'c',  label='O')
        self._lCg,   = s.loglog([],[], 'k:', label='C (grain)')
        self._lOg,   = s.loglog([],[], 'c:', label='O (grain)')
        
        s.legend(ncol=2)

        s.set_xlim(rmin, rmax)
        s.set_ylim(0.1, 50)
        s.set_ylabel('$[X]_\mathrm{solar}$')

        # C/O ratio
        s = self._subs[2]
        self._lCO,  = s.semilogx([],[], 'k')
        self._lCOg, = s.semilogx([],[], 'k:')
        s.set_xlim(rmin, rmax)
        s.set_ylim(0, 3)
        s.set_ylabel('$[C/O]_\mathrm{solar}$')
        s.set_xlabel('$R\,[\mathrm{au}]$') 
Example 43
Project: reportengine   Author: NNPDF   File: actions.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_2d(scatterdata):
    """Generate scatter plot of the values of xaxis vs yaxis"""
    x,y,category = scatterdata
    fig, ax = plt.subplots()
    ax.scatter(x,y, c=category, cmap=plt.cm.coolwarm)
    return fig 
Example 44
Project: iqoption-bot   Author: rrfaria   File: pyrenko.py    MIT License 5 votes vote down vote up
def plot_renko(self, col_up = 'g', col_down = 'r'):
        #fig, ax = plt.subplots(1, figsize=(20, 10))
        self.ax.clear()
        self.ax.set_title('Renko chart: ' + self.chart_title)
        self.ax.set_xlabel('Renko bars')
        self.ax.set_ylabel('Price')

        # Calculate the limits of axes
        self.ax.set_xlim(0.0,
                    len(self.renko_prices) + 1.0)
        self.ax.set_ylim(np.min(self.renko_prices) - 3.0 * self.brick_size,
                    np.max(self.renko_prices) + 3.0 * self.brick_size)

        # exponential
        ema = talib.EMA(np.array(self.renko_prices,dtype='f8'),timeperiod=self.ema_period)
        self.ax.plot(ema, color='#5957ce', lw=1, label='EMA ('+ str(self.ema_period) + ')')

        # Plot each renko bar
        for i in range(1, len(self.renko_prices)):
            # Set basic params for patch rectangle
            col = col_up if self.renko_directions[i] == 1 else col_down
            x = i
            y = self.renko_prices[i] - self.brick_size if self.renko_directions[i] == 1 else self.renko_prices[i]
            height = self.brick_size

            # Draw bar with params
            self.ax.add_patch(
                patches.Rectangle(
                    (x, y),   # (x,y)
                    1.0,     # width
                    self.brick_size, # height
                    facecolor = col
                )
            )

        #plt.show()
        plt.pause(self.chart_iterval) 
Example 45
Project: End-to-end-ASR-Pytorch   Author: Alexander-H-Liu   File: util.py    MIT License 5 votes vote down vote up
def _save_canvas(data, meta=None):
    fig, ax = plt.subplots(figsize=(16, 8))
    if meta is None:
        ax.imshow(data, aspect="auto", origin="lower")
    else:
        ax.bar(meta[0], data[0], tick_label=meta[1], fc=(0, 0, 1, 0.5))
        ax.bar(meta[0], data[1], tick_label=meta[1], fc=(1, 0, 0, 0.5))
    fig.canvas.draw()
    # Note : torch tb add_image takes color as [0,1]
    data = np.array(fig.canvas.renderer._renderer)[:, :, :-1]/255.0
    plt.close(fig)
    return data

# Reference : https://stackoverflow.com/questions/579310/formatting-long-numbers-as-strings-in-python 
Example 46
Project: where   Author: kartverket   File: sisre_report.py    MIT License 5 votes vote down vote up
def _plot_histogram_sisre(fid, figure_dir, dset):
    """Plot histogram based on SISRE dataset field

    Args:
       fid (_io.TextIOWrapper):  File object.
       figure_dir (PosixPath):   Figure directory
       dset (Dataset):           A dataset containing the data.
    """
    import math

    # TODO: How to handle for example 3 subplots?
    nrows = math.ceil(len(dset.unique("system")) / 2)
    ncols = 2 if len(dset.unique("system")) > 1 else 1
    fig, axes = plt.subplots(nrows=nrows, ncols=ncols, sharex=True, sharey=True, squeeze=False)
    for sys, ax in zip(dset.unique("system"), axes.flatten()):
        idx = dset.filter(system=sys)
        _plot_histogram_subplot(dset.sisre[idx], ax, sys)
    plt.savefig(figure_dir / f"plot_histogram_sisre.{FIGURE_FORMAT}", dpi=FIGURE_DPI)
    plt.clf()  # clear the current figure

    fid.write(f"![Histrogram of SISRE results]({figure_dir}/plot_histogram_sisre.{FIGURE_FORMAT})\n")
    fid.write("\n\\clearpage\n\n")


#
# SCATTER PLOTS
# 
Example 47
Project: where   Author: kartverket   File: sisre_report.py    MIT License 5 votes vote down vote up
def _plot_scatter_subplots(xdata, subplots, figure_path, xlabel="", title=""):
    """Generate scatter subplot
    Args:
       xdata (numpy.ndarray):       X-axis data to plot.
       subplots (tuple):            Tuple like (ylabel, color, ydata), whereby:
                                        ylabel (str):           Y-axis label
                                        color (str):            Color of scatter plot
                                        ydata (numpy.ndarray):  Y-axis data
       figure_path (PosixPath):     Figure path.
       xlabel (str):                X-axis label.
       title (str):                 Title of subplot.
    """
    marker = "."  # point marker type

    fig, axes = plt.subplots(len(subplots), 1, sharex=True, sharey=True, figsize=(6, 8))
    # fig.set_figheight(8)  # inches
    fig.suptitle(f"{title}", y=1.0)
    for idx, ax in enumerate(axes):
        ax.set(ylabel=subplots[idx].ylabel)
        ax.set_xlim([min(xdata), max(xdata)])  # otherwise time scale of x-axis is not correct -> Why?
        text = f"mean $= {np.mean(subplots[idx].ydata):.2f} \pm {np.std(subplots[idx].ydata):.2f}$ m"
        ax.text(0.98, 0.98, text, horizontalalignment="right", verticalalignment="top", transform=ax.transAxes)
        ax.scatter(xdata, subplots[idx].ydata, marker=marker, color=subplots[idx].color)
        ax.set(xlabel=xlabel)

    fig.autofmt_xdate()  # rotates and right aligns the x labels, and moves the bottom of the
    # axes up to make room for them
    plt.tight_layout()
    plt.savefig(figure_path, dpi=FIGURE_DPI)
    plt.clf()  # clear the current figure 
Example 48
Project: where   Author: kartverket   File: sisre_report.py    MIT License 5 votes vote down vote up
def _plot_scatter_orbit_and_clock_differences(fid, figure_dir, dset):
    """Scatter subplot of orbit and clock differences between broadcast and precise orbit and clock products

    Args:
       fid (_io.TextIOWrapper):  File object.
       figure_dir (PosixPath):   Figure directory
       dset (Dataset):           A dataset containing the data.
    """
    for sys in dset.unique("system"):
        idx = dset.filter(system=sys)
        figure_path = (
            figure_dir / f"plot_scatter_subplot_orbit_clock_differences_{GNSS_NAME[sys].lower()}.{FIGURE_FORMAT}"
        )

        # Define configuration of subplots
        subplots = (
            SubplotConfig("Δalong-track [m]", "paleturquoise", dset.orb_diff.itrs[:, 0][idx]),
            SubplotConfig("Δcross-track [m]", "deepskyblue", dset.orb_diff.itrs[:, 1][idx]),
            SubplotConfig("Δradial [m]", "royalblue", dset.orb_diff.itrs[:, 2][idx]),
            SubplotConfig("Δclock [m]", "tomato", dset.clk_diff_with_dt_mean[idx]),
        )

        _plot_scatter_subplots(
            dset.time.gps.datetime[idx], subplots, figure_path, xlabel="Time [GPS]", title=f"{GNSS_NAME[sys]}"
        )

        fid.write(
            f"![Difference between precise and broadcast orbits given in along-track, cross-track and radial direction and satellite clock corrections for all satellites.]({figure_path})\n"
        )
        fid.write("\n\\clearpage\n\n") 
Example 49
Project: PyTeCK   Author: pr-omethe-us   File: detect_peaks.py    MIT License 5 votes vote down vote up
def _plot(x, mph, mpd, threshold, edge, valley, ax, ind):
    """Plot results of the detect_peaks function, see its help.
    """

    try:
        import matplotlib.pyplot as plt
    except ImportError:
        print('matplotlib is not available.')
    else:
        if ax is None:
            _, ax = plt.subplots(1, 1, figsize=(8, 4))

        ax.plot(x, 'b', lw=1)
        if ind.size:
            label = 'valley' if valley else 'peak'
            label = label + 's' if ind.size > 1 else label
            ax.plot(ind, x[ind], '+', mfc=None, mec='r', mew=2, ms=8,
                    label='%d %s' % (ind.size, label))
            ax.legend(loc='best', framealpha=.5, numpoints=1)
        ax.set_xlim(-.02*x.size, x.size*1.02-1)
        ymin, ymax = x[np.isfinite(x)].min(), x[np.isfinite(x)].max()
        yrange = ymax - ymin if ymax > ymin else 1
        ax.set_ylim(ymin - 0.1*yrange, ymax + 0.1*yrange)
        ax.set_xlabel('Data #', fontsize=14)
        ax.set_ylabel('Amplitude', fontsize=14)
        mode = 'Valley detection' if valley else 'Peak detection'
        ax.set_title("%s (mph=%s, mpd=%d, threshold=%s, edge='%s')"
                     % (mode, str(mph), mpd, str(threshold), edge))
        # plt.grid()
        plt.show() 
Example 50
Project: team-stonks   Author: ucfai   File: StockData.py    GNU General Public License v3.0 5 votes vote down vote up
def plot(self, symbol):
		# read data from csv
		frame = pd.read_csv(os.getcwd() + '/data/stock-data/' + symbol + '.csv')

		# open columns
		ohlc = frame.loc[:,['Date', 'Open', 'High', 'Low', 'Close']]

		# get columns that are note ohlc
		cols = []
		for col in frame.columns:
			if col not in ['Date', 'Open', 'High', 'Low', 'Close']:
				cols.append(col)
				print(col)

		# transform dates so they play nicely with matplotlib
		ohlc['Date'] = pd.to_datetime(ohlc['Date']).apply(mpl_dates.date2num).astype('float')

		plt.style.use('ggplot')
		fig, ax = plt.subplots(1, sharex=True)

		candlestick_ohlc(ax, ohlc.values, width=0.6, colorup='green', colordown='red', alpha=0.8)
		ax.set_xlabel('Date')
		ax.set_ylabel('Price')
		fig.suptitle(symbol)

		date_format = mpl_dates.DateFormatter('%d-%m-%Y')
		ax.xaxis.set_major_formatter(date_format)
		fig.autofmt_xdate()
		fig.tight_layout()

		# plot moving averages
		ax.plot(ohlc['Date'], frame['5EMA'], color='blue', label='5EMA')

		# plot Volume
		#plt.subplot(111, sharex=ax)
		#axVol.set_ylabel('Volume', color='blue')
		#plt.plot(ohlc['Date'], frame['Volume'], color='blue')


		plt.show()