How to use the matplotlib.pyplot.gca function in matplotlib

To help you get started, we’ve selected a few matplotlib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github celebrity-audio-collection / videoprocess / RetinaFace / insightface / RetinaFace_linux / rcnn / core / tester.py View on Github external
import random
    im = image.transform_inverse(im_array, config.PIXEL_MEANS)
    plt.imshow(im)
    for j, name in enumerate(class_names):
        if name == '__background__':
            continue
        color = (random.random(), random.random(), random.random())  # generate a random color
        dets = detections[j]
        for det in dets:
            bbox = det[:4] * scale
            score = det[-1]
            rect = plt.Rectangle((bbox[0], bbox[1]),
                                 bbox[2] - bbox[0],
                                 bbox[3] - bbox[1], fill=False,
                                 edgecolor=color, linewidth=3.5)
            plt.gca().add_patch(rect)
            plt.gca().text(bbox[0], bbox[1] - 2,
                           '{:s} {:.3f}'.format(name, score),
                           bbox=dict(facecolor=color, alpha=0.5), fontsize=12, color='white')
    plt.show()
github nschloe / accupy / test / test_sums.py View on Github external
labels=[
            "sum",
            "numpy.sum",
            "accupy.kahan_sum",
            "accupy.ksum[2]",
            "accupy.ksum[3]",
            "accupy.fsum",
        ],
        colors=plt.rcParams["axes.prop_cycle"].by_key()["color"][:6],
        n_range=n_range,
        title="Sum(random(100, n))",
        xlabel="n",
        logx=True,
        logy=True,
    )
    plt.gca().set_aspect(0.5)
    lgd = plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)
    # plt.show()
    plt.savefig(
        "speed-comparison2.svg",
        transparent=True,
        bbox_extra_artists=(lgd,),
        bbox_inches="tight",
    )
    return
github CGAL / cgal-swig-bindings / examples / python / polygonal_triangulation.py View on Github external
def plot_edge(edge, *args):
            edge_seg = cdt.segment(edge)
            pts = [ edge_seg.source(), edge_seg.target() ]
            xs = [ pts[0].x(), pts[1].x() ]
            ys = [ pts[0].y(), pts[1].y() ]
            plt.plot( xs, ys, *args )

        plt.hold(True)
        for edge in cdt.finite_edges():
            if cdt.is_constrained(edge):
                plot_edge(edge, 'r-')
            else:
                if face_info[edge[0]].in_domain():
                    plot_edge(edge, 'b-')
        rescale_plot(plt.gca())
        plt.show()
github jaredwo / topowx / twx / MontanaTrends.py View on Github external
def anomBarPlot(anom):
    blue = '#2166AC'
    red = '#B2182B'
    
    colors = np.array([red]*anom.size)
    colors[anom < 0] = blue
    
    plt.bar(np.arange(anom.size), anom,color=colors,alpha=.5)
    xlim = plt.xlim((0,118))
    plt.hlines(0, xlim[0], xlim[1], colors='k')
    plt.xlim((0,118))
    yrs = np.arange(1895,2013)
    loc = np.arange(5,118,10)
    plt.xticks(loc,[str(yr) for yr in yrs[loc]],fontsize=17)
    
    ax = plt.gca()
    ax.set_axisbelow(True)
    ax.yaxis.grid(color='gray', linestyle='dashed')
    plt.plot(runningMean(anom),color='k',lw=2)
    #plt.ylim((-2.5,2.5))
    plt.xlabel("Year",fontsize=17)
    plt.ylabel("Anomaly ($^\circ$C)",fontsize=17)
    plt.setp(ax.get_yticklabels(), fontsize=17)
github pykaldi / pykaldi / examples / setups / ltsv-based-vad / compute-vad.py View on Github external
import matplotlib.mlab as mlb

    plt.subplot(3, 1, 1)
    plt.pcolormesh(segment_times, sample_freqs, 10 * np.log10(spec), cmap="jet")
    plt.ylabel("Frequency [Hz]")
    plt.xlabel("Time [sec]")

    plt.subplot(3, 1, 2)
    axes = plt.gca()
    axes.set_xlim([0, duration])
    tmp_axis = np.linspace(0, duration, wav_data.shape[0])
    plt.plot(tmp_axis, wav_data / np.abs(np.max(wav_data)))
    plt.xlabel("Time [sec]")

    plt.subplot(3, 1, 3)
    axes = plt.gca()
    axes.set_xlim([0, duration])
    tmp_axis = np.linspace(0, duration, vad_feat.shape[0])
    plt.plot(tmp_axis, vad_feat)
    plt.xlabel("Time [sec]")

    plt.savefig("plots/" + key, bbox_inches="tight")
github FerranAlet / modular-metalearning / modular_metalearning.py View on Github external
def plot_sharing(self):
    if (self.METRICS['Sharing'] is not None and
            np.max(self.METRICS['Sharing'])>1e-4 and
            len(self.METRICS['NumberToWords']) <= 50):
      #Find ordering
      aux = list(enumerate(self.METRICS['NumberToWords']))
      aux.sort(key = lambda x : x[1])
      sorted_order = [_[0] for _ in aux]
      cax = plt.gca().matshow(np.array(
        self.METRICS['Sharing'])[sorted_order,:][:,sorted_order]
        /self.S.usage_normalization)
      plt.gca().set_xticklabels(['']+sorted(self.METRICS['NumberToWords']))
      plt.gca().set_yticklabels(['']+sorted(self.METRICS['NumberToWords']))
      plt.gca().xaxis.set_major_locator(ticker.MultipleLocator(1))
      plt.gca().yaxis.set_major_locator(ticker.MultipleLocator(1))
      if self.store_video:
        plt.savefig(os.path.join(self.plot_name, 'video/sharing-rate_'+
          str(self.step)))
      plt.gcf().colorbar(cax)
      plt.savefig(os.path.join(self.plot_name, 'sharing-rate'))
      plt.clf()
github noripyt / django-cachalot / benchmark.py View on Github external
def plot_detail(self, param):
        for v in self.means.columns.levels[0]:
            plt.figure()
            axes = self.means[v].plot(
                kind='barh', xerr=self.errors[v],
                xlim=self.xlim, figsize=(15, 15), subplots=True, layout=(6, 2),
                sharey=True, legend=False)
            plt.gca().invert_yaxis()
            for row in axes:
                for ax in row:
                    ax.xaxis.grid(True)
                    ax.set_ylabel('')
                    ax.set_xlabel('Time (s)')
            plt.savefig(os.path.join(RESULTS_PATH, '%s_%s.svg' % (param, v)))
github automl / RoBO / examples / example_contextual3.py View on Github external
S[i, :] = res
    return S

def objective2_min(Z):
    """
    Calculates the location (action) of the minimum for a given context
    :param Z: context
    :return: locations of minimums
    """
    return objective2(Z, objective2_min_action(Z))


# Create figure with subplots
fig = plt.figure(figsize=(15, 10))
plt.hold(True)
ax1 = plt.gca()

###########################
# Objective 2: Hartmann 6 #
###########################

real_data = objective2_min(Z=np.random.uniform(size=(10,2))).flatten()

# Defining the bounds and dimensions of the input space
S_lower = np.array([0, 0, 0, 0])
S_upper = np.array([1, 1, 1, 1])

X_lower = np.array([-np.inf, -np.inf, 0, 0, 0, 0])
X_upper = np.array([np.inf, np.inf, 1, 1, 1, 1])

dims_Z = 2
dims_S = 4
github mhallsmoore / qstrader / qstrader / statistics / tearsheet.py View on Github external
def _plot_monthly_returns(self, stats, ax=None, **kwargs):
        """
        Plots a heatmap of the monthly returns.
        """
        returns = stats['returns']
        if ax is None:
            ax = plt.gca()

        monthly_ret = perf.aggregate_returns(returns, 'monthly')
        monthly_ret = monthly_ret.unstack()
        monthly_ret = np.round(monthly_ret, 3)
        monthly_ret.rename(
            columns={1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr',
                     5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug',
                     9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'},
            inplace=True
        )

        sns.heatmap(
            monthly_ret.fillna(0) * 100.0,
            annot=True,
            fmt="0.1f",
            annot_kws={"size": 8},
github Ohjeah / sparsereg / examples / net.py View on Github external
exponents = [1]
operators = {}
sym = sf.SymbolicFeatures(exponents=exponents, operators=operators)
features = sym.fit_transform(x)
ests = [Lasso, STRidge]
attrs = ["alpha", "threshold"]
names = ["Lasso", "STRidge"]
for est, attr, name in zip(ests, attrs, names):
    models = net(est, features, y, attr, filter=True, max_coarsity=5, r_max=1e5)
    m = sorted(models)
    scores = np.array([models[k].score(features, y) for k in m])
    plt.plot(m, scores, "o--", label=name)
plt.legend()
plt.xlabel("# coefficient")
plt.ylabel(r"$R^2$")
plt.gca().invert_xaxis()
plt.show()