Python matplotlib.pyplot.axes() Examples

The following are 30 code examples for showing how to use matplotlib.pyplot.axes(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .

Example 1
Project: razzy-spinner   Author: rafasashi   File: util.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

    plt.locator_params(axis='y', nbins=3)
    axes = plt.axes()
    axes.yaxis.grid()
    plt.plot(x_values, y_values, 'ro', color='red')
    plt.ylim(ymin=-1.2, ymax=1.2)
    plt.tight_layout(pad=5)
    if x_labels:
        plt.xticks(x_values, x_labels, rotation='vertical')
    if y_labels:
        plt.yticks([-1, 0, 1], y_labels, rotation='horizontal')
    # Pad margins so that markers are not clipped by the axes
    plt.margins(0.2)
    plt.show()

#////////////////////////////////////////////////////////////
#{ Parsing and conversion functions
#//////////////////////////////////////////////////////////// 
Example 2
Project: wechat-analyse   Author: qinyuanpei   File: main.py    License: MIT License 6 votes vote down vote up
def analyseSex(firends):
    sexs = list(map(lambda x:x['Sex'],friends[1:]))
    counts = Counter(sexs).items()
    counts = sorted(counts, key=lambda x:x[0], reverse=False)
    counts = list(map(lambda x:x[1],counts))
    labels = ['Unknow','Male','Female']
    colors = ['red','yellowgreen','lightskyblue']
    plt.figure(figsize=(8,5), dpi=80)
    plt.axes(aspect=1) 
    plt.pie(counts, 
            labels=labels, 
            colors=colors, 
            labeldistance = 1.1, 
            autopct = '%3.1f%%',
            shadow = False, 
            startangle = 90, 
            pctdistance = 0.6 
    )
    plt.legend(loc='upper right',)
    plt.title(u'%s的微信好友性别组成' % friends[0]['NickName'])
    plt.show() 
Example 3
Project: tf-example-models   Author: aakhundov   File: tf_gmm_tools.py    License: Apache License 2.0 6 votes vote down vote up
def _plot_gaussian(mean, covariance, color, zorder=0):
    """Plots the mean and 2-std ellipse of a given Gaussian"""
    plt.plot(mean[0], mean[1], color[0] + ".", zorder=zorder)

    if covariance.ndim == 1:
        covariance = np.diag(covariance)

    radius = np.sqrt(5.991)
    eigvals, eigvecs = np.linalg.eig(covariance)
    axis = np.sqrt(eigvals) * radius
    slope = eigvecs[1][0] / eigvecs[1][1]
    angle = 180.0 * np.arctan(slope) / np.pi

    plt.axes().add_artist(pat.Ellipse(
        mean, 2 * axis[0], 2 * axis[1], angle=angle,
        fill=False, color=color, linewidth=1, zorder=zorder
    )) 
Example 4
Project: tf-example-models   Author: aakhundov   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def _plot_gaussian(mean, covariance, color, zorder=0):
    """Plots the mean and 2-std ellipse of a given Gaussian"""
    plt.plot(mean[0], mean[1], color[0] + ".", zorder=zorder)

    if covariance.ndim == 1:
        covariance = np.diag(covariance)

    radius = np.sqrt(5.991)
    eigvals, eigvecs = np.linalg.eig(covariance)
    axis = np.sqrt(eigvals) * radius
    slope = eigvecs[1][0] / eigvecs[1][1]
    angle = 180.0 * np.arctan(slope) / np.pi

    plt.axes().add_artist(pat.Ellipse(
        mean, 2 * axis[0], 2 * axis[1], angle=angle,
        fill=False, color=color, linewidth=1, zorder=zorder
    )) 
Example 5
Project: tf-example-models   Author: aakhundov   File: tf_gmm.py    License: Apache License 2.0 6 votes vote down vote up
def plot_fitted_data(points, c_means, c_variances):
    """Plots the data and given Gaussian components"""
    plt.plot(points[:, 0], points[:, 1], "b.", zorder=0)
    plt.plot(c_means[:, 0], c_means[:, 1], "r.", zorder=1)

    for i in range(c_means.shape[0]):
        std = np.sqrt(c_variances[i])
        plt.axes().add_artist(pat.Ellipse(
            c_means[i], 2 * std[0], 2 * std[1],
            fill=False, color="red", linewidth=2, zorder=1
        ))

    plt.show()


# PREPARING DATA

# generating DATA_POINTS points from a GMM with COMPONENTS components 
Example 6
Project: feets   Author: quatrope   File: tutorial.py    License: MIT License 6 votes vote down vote up
def ts_anim():
    # create a simple animation
    fig = plt.figure()
    ax = plt.axes(xlim=(0, 100), ylim=(-1, 1))
    Color = [ 1 ,0.498039, 0.313725];
    line, = ax.plot([], [], '*',color = Color)
    plt.xlabel("Time")
    plt.ylabel("Measurement")

    def init():
        line.set_data([], [])
        return line,

    def animate(i):
        x = np.linspace(0, i+1, i+1)
        ts = 5*np.cos(x * 0.02 * np.pi) * np.sin(np.cos(x)  * 0.02 * np.pi)
        line.set_data(x, ts)
        return line,

    return animation.FuncAnimation(fig, animate, init_func=init,
                                   frames=100, interval=200, blit=True) 
Example 7
Project: feets   Author: quatrope   File: examples.py    License: MIT License 6 votes vote down vote up
def basic_animation(frames=100, interval=30):
    """Plot a basic sine wave with oscillating amplitude"""
    fig = plt.figure()
    ax = plt.axes(xlim=(0, 10), ylim=(-2, 2))
    line, = ax.plot([], [], lw=2)

    x = np.linspace(0, 10, 1000)

    def init():
        line.set_data([], [])
        return line,

    def animate(i):
        y = np.cos(i * 0.02 * np.pi) * np.sin(x - i * 0.02 * np.pi)
        line.set_data(x, y)
        return line,

    return animation.FuncAnimation(fig, animate, init_func=init,
                                   frames=frames, interval=interval) 
Example 8
Project: yatsm   Author: ceholden   File: pixel.py    License: MIT License 6 votes vote down vote up
def plot_DOY(dates, y, mpl_cmap):
    """ Create a DOY plot

    Args:
        dates (iterable): sequence of datetime
        y (np.ndarray): variable to plot
        mpl_cmap (colormap): matplotlib colormap
    """
    doy = np.array([d.timetuple().tm_yday for d in dates])
    year = np.array([d.year for d in dates])

    sp = plt.scatter(doy, y, c=year, cmap=mpl_cmap,
                     marker='o', edgecolors='none', s=35)
    plt.colorbar(sp)

    months = mpl.dates.MonthLocator()  # every month
    months_fmrt = mpl.dates.DateFormatter('%b')

    plt.tick_params(axis='x', which='minor', direction='in', pad=-10)
    plt.axes().xaxis.set_minor_locator(months)
    plt.axes().xaxis.set_minor_formatter(months_fmrt)

    plt.xlim(1, 366)
    plt.xlabel('Day of Year') 
Example 9
Project: ibllib   Author: int-brain-lab   File: ephys_qc_raw.py    License: MIT License 6 votes vote down vote up
def _plot_spectra(outpath, typ, savefig=True):
    spec = alf.io.load_object(outpath, '_iblqc_ephysSpectralDensity' + typ.upper())

    sns.set_style("whitegrid")
    plt.figure(figsize=[9, 4.5])
    ax = plt.axes()
    ax.plot(spec['freqs'], 20 * np.log10(spec['power'] + 1e-14),
            linewidth=0.5, color=[0.5, 0.5, 0.5])
    ax.plot(spec['freqs'], 20 * np.log10(np.median(spec['power'] + 1e-14, axis=1)), label='median')
    ax.set_xlabel(r'Frequency (Hz)')
    ax.set_ylabel(r'dB rel to $V^2.$Hz$^{-1}$')
    if typ == 'ap':
        ax.set_ylim([-275, -125])
    elif typ == 'lf':
        ax.set_ylim([-260, -60])
    ax.legend()
    if savefig:
        plt.savefig(outpath / (typ + '_spec.png'), dpi=150) 
Example 10
Project: ibllib   Author: int-brain-lab   File: ephys_qc_raw.py    License: MIT License 6 votes vote down vote up
def _plot_rmsmap(outfil, typ, savefig=True):
    rmsmap = alf.io.load_object(outpath, '_iblqc_ephysTimeRms' + typ.upper())
    plt.figure(figsize=[12, 4.5])
    axim = plt.axes([0.2, 0.1, 0.7, 0.8])
    axrms = plt.axes([0.05, 0.1, 0.15, 0.8])
    axcb = plt.axes([0.92, 0.1, 0.02, 0.8])

    axrms.plot(np.median(rmsmap['rms'], axis=0)[:-1] * 1e6, np.arange(1, rmsmap['rms'].shape[1]))
    axrms.set_ylim(0, rmsmap['rms'].shape[1])

    im = axim.imshow(20 * np.log10(rmsmap['rms'].T + 1e-15), aspect='auto', origin='lower',
                     extent=[rmsmap['timestamps'][0], rmsmap['timestamps'][-1],
                             0, rmsmap['rms'].shape[1]])
    axim.set_xlabel(r'Time (s)')
    axim.set_ylabel(r'Channel Number')
    plt.colorbar(im, cax=axcb)
    if typ == 'ap':
        im.set_clim(-110, -90)
        axrms.set_xlim(100, 0)
    elif typ == 'lf':
        im.set_clim(-100, -60)
        axrms.set_xlim(500, 0)
    axim.set_xlim(0, 4000)
    if savefig:
        plt.savefig(outpath / (typ + '_rms.png'), dpi=150) 
Example 11
Project: pyeo   Author: clcr   File: test1.py    License: GNU General Public License v3.0 6 votes vote down vote up
def blank_axes(ax):
    """
    blank_axes:  blank the extraneous spines and tick marks for an axes

    Input:
    ax:  a matplotlib Axes object

    Output: None
    """

    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.yaxis.set_ticks_position('none')
    ax.xaxis.set_ticks_position('none')
    ax.tick_params(labelbottom='off', labeltop='off', labelleft='off', labelright='off', \
                   bottom='off', top='off', left='off', right='off')


# end blank_axes

#######################################################
# MAIN
####################################################### 
Example 12
Project: bert-as-service   Author: hanxiao   File: example7.py    License: MIT License 6 votes vote down vote up
def vis(embed, vis_alg='PCA', pool_alg='REDUCE_MEAN'):
    plt.close()
    fig = plt.figure()
    plt.rcParams['figure.figsize'] = [21, 7]
    for idx, ebd in enumerate(embed):
        ax = plt.subplot(2, 6, idx + 1)
        vis_x = ebd[:, 0]
        vis_y = ebd[:, 1]
        plt.scatter(vis_x, vis_y, c=subset_label, cmap=ListedColormap(["blue", "green", "yellow", "red"]), marker='.',
                    alpha=0.7, s=2)
        ax.set_title('pool_layer=-%d' % (idx + 1))
    plt.tight_layout()
    plt.subplots_adjust(bottom=0.1, right=0.95, top=0.9)
    cax = plt.axes([0.96, 0.1, 0.01, 0.3])
    cbar = plt.colorbar(cax=cax, ticks=range(num_label))
    cbar.ax.get_yaxis().set_ticks([])
    for j, lab in enumerate(['ent.', 'bus.', 'sci.', 'heal.']):
        cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center', rotation=270)
    fig.suptitle('%s visualization of BERT layers using "bert-as-service" (-pool_strategy=%s)' % (vis_alg, pool_alg),
                 fontsize=14)
    plt.show() 
Example 13
Project: eht-imaging   Author: achael   File: caltable.py    License: GNU General Public License v3.0 6 votes vote down vote up
def plot_dterms(self, sites='all', label=None, legend=True, clist=ehc.SCOLORS,
                    rangex=False, rangey=False, markersize=2 * ehc.MARKERSIZE,
                    show=True, grid=True, export_pdf=""):

        # sites
        if sites in ['all' or 'All'] or sites == []:
            sites = list(self.data.keys())

        if not isinstance(sites, list):
            sites = [sites]

        keys = [self.tkey[site] for site in sites]

        axes = plot_tarr_dterms(self.tarr, keys=keys, label=label, legend=legend, clist=clist,
                                rangex=rangex, rangey=rangey, markersize=markersize,
                                show=show, grid=grid, export_pdf=export_pdf)

        return axes 
Example 14
Project: osim-rl   Author: stanfordnmbl   File: solver.py    License: MIT License 6 votes vote down vote up
def plot_convergence(self, filename=None):
        yy = self.iter_values
        xx = range(len(yy))
        import matplotlib.pyplot as plt
        # Plot
        plt.ioff()
        fig = plt.figure()
        fig.set_size_inches(18.5, 10.5)
        font = {'size': 28}
        plt.title('Value over # evaluations')
        plt.xlabel('X', fontdict=font)
        plt.ylabel('Y', fontdict=font)
        plt.plot(xx, yy)
        plt.axes().set_yscale('log')
        if filename is None:
            filename = 'plots/iter.png'
        plt.savefig(filename, bbox_inches='tight')
        plt.close(fig)
        print('plotting convergence OK.. ' + filename) 
Example 15
Project: ILCC   Author: mfxox   File: utility.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def draw_chessboard_model(marker_size=marker_size):
    gird_coords = generate_grid_coords(x_res=marker_size[0], y_res=marker_size[1])
    grid_ls = [(p[0]).flatten()[:2] for p in gird_coords]
    corner_arr = np.transpose(np.array(grid_ls).reshape(marker_size[0], marker_size[1], 2)[1:, 1:], (1, 0, 2))
    c = np.zeros([corner_arr.shape[0], corner_arr.shape[1], 3]).reshape(
        corner_arr.shape[0] * corner_arr.shape[1], 3).astype(np.float32)
    c[0] = np.array([0, 0, 1])
    c[-1] = np.array([1, 0, 0])
    s = np.zeros(corner_arr[:, :, 0].flatten().shape[0]) + 20
    s[0] = 60
    s[-1] = 60

    plt.scatter(corner_arr[:, :, 0].flatten(), corner_arr[:, :, 1].flatten(), c=c, s=s)

    plt.plot(corner_arr[:, :, 0].flatten(), corner_arr[:, :, 1].flatten())

    plt.xlim(corner_arr[:, :, 0].min(), corner_arr[:, :, 0].max())
    plt.ylim(corner_arr[:, :, 1].min(), corner_arr[:, :, 1].max())
    plt.xlabel("x coordinates [cm]")
    plt.ylabel("y coordinates [cm]")
    # plt.axes().set_aspect('equal', 'datalim')
    plt.axis('equal')
    plt.show() 
Example 16
Project: geomeppy   Author: jamiebull1   File: view_geometry.py    License: MIT License 6 votes vote down vote up
def view_polygons(polygons):
    """Display a collection of polygons for inspection.

    :param polygons: A dict keyed by colour, containing Polygon3D objects to show in that colour.
    """
    # create the figure and add the surfaces
    plt.figure()
    ax = plt.axes(projection="3d")

    collections = _make_collections(polygons, opacity=0.5)

    for c in collections:
        ax.add_collection3d(c)

    # calculate and set the axis limits
    limits = _get_limits(polygons=polygons)
    ax.set_xlim(limits["x"])
    ax.set_ylim(limits["y"])
    ax.set_zlim(limits["z"])

    plt.show() 
Example 17
Project: geomeppy   Author: jamiebull1   File: view_geometry.py    License: MIT License 6 votes vote down vote up
def _get_limits(idf=None, polygons=None):
    """Get limits for the x, y and z axes so the plot is fitted to the axes."""
    if polygons:
        x = [pt[0] for color in polygons for p in polygons[color] for pt in p]
        y = [pt[1] for color in polygons for p in polygons[color] for pt in p]
        z = [pt[2] for color in polygons for p in polygons[color] for pt in p]

    elif idf:
        surfaces = _get_surfaces(idf)

        x = [pt[0] for s in surfaces for pt in getcoords(s)]
        y = [pt[1] for s in surfaces for pt in getcoords(s)]
        z = [pt[2] for s in surfaces for pt in getcoords(s)]
    if all([x, y, z]):
        max_delta = max((max(x) - min(x)), (max(y) - min(y)), (max(z) - min(z)))
        limits = {
            "x": (min(x), min(x) + max_delta),
            "y": (min(y), min(y) + max_delta),
            "z": (min(z), min(y) + max_delta),
        }
    else:
        limits = {"x": (0, 0), "y": (0, 0), "z": (0, 0)}

    return limits 
Example 18
Project: FRETBursts   Author: tritemio   File: burst_plot.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _alex_plot_style(g, colorbar=True):
    """Set plot style and colorbar for an ALEX joint plot.
    """
    g.set_axis_labels(xlabel="E", ylabel="S")
    g.ax_marg_x.grid(True)
    g.ax_marg_y.grid(True)
    g.ax_marg_x.set_xlabel('')
    g.ax_marg_y.set_ylabel('')
    plt.setp(g.ax_marg_y.get_xticklabels(), visible=True)
    plt.setp(g.ax_marg_x.get_yticklabels(), visible=True)
    g.ax_marg_x.locator_params(axis='y', tight=True, nbins=3)
    g.ax_marg_y.locator_params(axis='x', tight=True, nbins=3)
    if colorbar:
        pos = g.ax_joint.get_position().get_points()
        X, Y = pos[:, 0], pos[:, 1]
        cax = plt.axes([1., Y[0], (X[1] - X[0]) * 0.045, Y[1] - Y[0]])
        plt.colorbar(cax=cax) 
Example 19
Project: pylustrator   Author: rgerum   File: helper_functions.py    License: GNU General Public License v3.0 6 votes vote down vote up
def add_axes(dim: Sequence, unit: str = "cm", *args, **kwargs):
    """
    add an axes with dimensions specified in cm
    """
    fig = plt.gcf()
    x, y, w, h = dim
    if unit == "cm":
        x = x / 2.54 / fig.get_size_inches()[0]
        y = y / 2.54 / fig.get_size_inches()[1]
        w = w / 2.54 / fig.get_size_inches()[0]
        h = h / 2.54 / fig.get_size_inches()[1]
    if x < 0:
        x += 1
    if y < 0:
        y += 1
    return plt.axes([x, y, w, h], *args, **kwargs) 
Example 20
Project: neural-network-animation   Author: miloharper   File: test_axes.py    License: MIT License 6 votes vote down vote up
def test_polar_wrap():
    D2R = np.pi / 180.0

    fig = plt.figure()

    plt.subplot(111, polar=True)

    plt.polar([179*D2R, -179*D2R], [0.2, 0.1], "b.-")
    plt.polar([179*D2R,  181*D2R], [0.2, 0.1], "g.-")
    plt.rgrids([0.05, 0.1, 0.15, 0.2, 0.25, 0.3])
    assert len(fig.axes) == 1, 'More than one polar axes created.'
    fig = plt.figure()

    plt.subplot(111, polar=True)
    plt.polar([2*D2R, -2*D2R], [0.2, 0.1], "b.-")
    plt.polar([2*D2R,  358*D2R], [0.2, 0.1], "g.-")
    plt.polar([358*D2R,  2*D2R], [0.2, 0.1], "r.-")
    plt.rgrids([0.05, 0.1, 0.15, 0.2, 0.25, 0.3]) 
Example 21
def main():
    fig = plt.figure()
    ax = plt.axes(projection='3d')

    # points = trajGen3D.get_helix_waypoints(0, 50)

    points = get_full_trajectory()
    # Data for a three-dimensional line
    zline = points[:,-1]
    xline = points[:,0]
    yline = points[:,1]

    ax.plot3D(xline, yline, zline, 'blue')
    plt.show() 
Example 22
Project: python-control   Author: python-control   File: grid.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def nogrid():
    f = plt.gcf()
    ax = plt.axes()

    _final_setup(ax)
    return ax, f 
Example 23
Project: ibllib   Author: int-brain-lab   File: lfp_qc.py    License: MIT License 5 votes vote down vote up
def _plot_spectra(outpath, typ, savefig=True):
    '''
    TODO document this function
    '''

    spec = alf.io.load_object(outpath, '_spikeglx_ephysQcFreq' + typ.upper())

    # hack to ensure a single key name
    if 'power.probe_00' in spec.keys():
        spec['power'] = spec.pop('power.probe_00')
        spec['freq'] = spec.pop('freq.probe_00')
    elif 'power.probe_01' in spec.keys():
        spec['power'] = spec.pop('power.probe_01')
        spec['freq'] = spec.pop('freq.probe_01')

    # plot
    sns.set_style("whitegrid")
    plt.figure(figsize=[9, 4.5])
    ax = plt.axes()
    ax.plot(spec['freq'], 20 * np.log10(spec['power'] + 1e-14),
            linewidth=0.5, color=[0.5, 0.5, 0.5])
    ax.plot(spec['freq'], 20 * np.log10(np.median(spec['power'] + 1e-14, axis=1)), label='median')
    ax.set_xlabel(r'Frequency (Hz)')
    ax.set_ylabel(r'dB rel to $V^2.$Hz$^{-1}$')
    if typ == 'ap':
        ax.set_ylim([-275, -125])
    elif typ == 'lf':
        ax.set_ylim([-260, -60])
    ax.legend()
    ax.set_title(outpath)
    if savefig:
        plt.savefig(outpath / (typ + '_spec.png'), dpi=150)
        print('saved figure to %s' % (outpath / (typ + '_spec.png'))) 
Example 24
Project: magpy   Author: geomagpy   File: mpplot.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, data = None, variables=None, figure=False):

        self.data = data

        self.offset = False
        self.mainnum = 1
        self.flagid = 3
        self.reason = 'why because'
        self.idxarray = []
        self.figure = False
        self.axes = False

        self.orgkeylist = self.data._get_key_headers()
        if not variables: #or variables == ['x','y','z','f'] or variables == ['x','y','z']:
            try:
                self.data = self.analyzeData(self.orgkeylist)
            except:
                logger.warning("figFlagger.__init__: You have to provide variables for this data set")


        keylist = self.data._get_key_headers(numerical=True)
        #print keylist
        if variables:
            keylist = variables
        if len(keylist) > 9:
            keylist = keylist[:8]
        #print keylist
        self.keylist = keylist
        annotatelist = [True if elem in self.orgkeylist else False for elem in keylist] # if elem in ['x','y','z'] else False]

        self.fig = plotStreams([self.data], [keylist], noshow=True, annotate=[annotatelist])

        radio, hzfunc = self.startup(self.fig, self.data)
        radio.on_clicked(hzfunc)

        if figure:
            self.figure = self.fig
            self.axes = self.fig.axes
        else:
            plt.show() 
Example 25
Project: KAIR   Author: cszn   File: utils_image.py    License: MIT License 5 votes vote down vote up
def surf(Z, cmap='rainbow', figsize=None):
    plt.figure(figsize=figsize)
    ax3 = plt.axes(projection='3d')

    w, h = Z.shape[:2]
    xx = np.arange(0,w,1)
    yy = np.arange(0,h,1)
    X, Y = np.meshgrid(xx, yy)
    ax3.plot_surface(X,Y,Z,cmap=cmap)
    #ax3.contour(X,Y,Z, zdim='z',offset=-2,cmap=cmap)
    plt.show() 
Example 26
Project: roipoly.py   Author: jdoepfert   File: roipoly.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 fig=None, ax=None,
                 roi_names=None,
                 color_cycle=('b', 'g', 'r', 'c', 'm', 'y', 'k')
                 ):
        """

        Parameters
        ----------
        fig: matplotlib figure
            Figure on which to draw the ROIs
        ax: matplotlib axes
           Axes on which to draw the ROIs
        roi_names: list of str
            Optional names for the ROIs to draw.
            The ROIs can later be retrieved by using these names as keys for
            the `self.rois` dictionary. If None, consecutive numbers are used
            as ROI names
        color_cycle: list of str
            List of matplotlib colors for the ROIs
        """

        if fig is None:
            fig = plt.gcf()
        if ax is None:
            ax = fig.gca()

        self.color_cycle = color_cycle
        self.roi_names = roi_names
        self.fig = fig
        self.ax = ax
        self.rois = {}

        self.make_buttons() 
Example 27
Project: roipoly.py   Author: jdoepfert   File: roipoly.py    License: Apache License 2.0 5 votes vote down vote up
def make_buttons(self):
        ax_add_btn = plt.axes([0.7, 0.02, 0.1, 0.04])
        ax_finish_btn = plt.axes([0.81, 0.02, 0.1, 0.04])
        btn_finish = Button(ax_finish_btn, 'Finish')
        btn_finish.on_clicked(self.finish)
        btn_add = Button(ax_add_btn, 'New ROI')
        btn_add.on_clicked(self.add)
        plt.show(block=True) 
Example 28
Project: crappy   Author: LaboratoireMecaniqueLille   File: grapher.py    License: GNU General Public License v2.0 5 votes vote down vote up
def prepare(self):
    if self.backend:
      plt.switch_backend(self.backend)
    self.f = plt.figure(figsize=self.window_size)
    self.ax = self.f.add_subplot(111)
    self.lines = []
    for _ in self.labels:
      if self.interp:
        self.lines.append(self.ax.plot([], [])[0])
      else:
        self.lines.append(self.ax.step([], [])[0])
    # Keep only 1/factor points on each line
    self.factor = [1 for i in self.labels]
    # Count to drop exactly 1/factor points, no more and no less
    self.counter = [0 for i in self.labels]
    legend = [y for x, y in self.labels]
    plt.legend(legend, bbox_to_anchor=(-0.03, 1.02, 1.06, .102), loc=3,
               ncol=len(legend), mode="expand", borderaxespad=1)
    plt.xlabel(self.labels[0][0])
    plt.ylabel(self.labels[0][1])
    plt.grid()
    self.axclear = plt.axes([.8,.02,.15,.05])
    self.bclear = Button(self.axclear,'Clear')
    self.bclear.on_clicked(self.clear)

    if self.window_pos:
      mng = plt.get_current_fig_manager()
      mng.window.wm_geometry("+%s+%s" % self.window_pos)
    plt.draw()
    plt.pause(.001) 
Example 29
Project: vnpy_crypto   Author: birforce   File: example_arma.py    License: MIT License 5 votes vote down vote up
def norm_corr(x,y,mode = 'valid'):
    """Returns the correlation between two ndarrays, by calling np.correlate in
'same' mode and normalizing the result by the std of the arrays and by
their lengths. This results in a correlation = 1 for an auto-correlation"""

    return ( np.correlate(x,y,mode) /
             (np.std(x)*np.std(y)*(x.shape[-1])) )



# from matplotlib axes.py
# note: self is axis 
Example 30
Project: vnpy_crypto   Author: birforce   File: test_predict_functional.py    License: MIT License 5 votes vote down vote up
def test_lm_contrast(self):

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

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

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

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

        plt.clf()
        fig = plt.figure()
        ax = plt.axes([0.1, 0.1, 0.67, 0.8])
        plt.plot(fvals, pr, '-', label="Estimate", color='orange', lw=4)
        plt.plot(fvals, 4 - fvals, '-', label="Truth", color='lime', lw=4)
        plt.fill_between(fvals, cb[:, 0], cb[:, 1], color='grey')
        ha, lb = ax.get_legend_handles_labels()
        leg = plt.figlegend(ha, lb, "center right")
        leg.draw_frame(False)
        plt.xlabel("Focus variable", size=15)
        plt.ylabel("Mean contrast", size=15)
        plt.title("Linear model contrast")
        self.close_or_save(fig)