atarashansky/self-assembling-manifold · SAM.py
python logo
def scatter(self, projection=None, c=None, cmap='rainbow', linewidth=0.0,
                edgecolor='k', axes=None, colorbar=True, s=10, **kwargs):
        """Display a scatter plot.

        Displays a scatter plot using the SAM projection or another input
        projection with or without annotations.

        Parameters
        ----------

        projection - ndarray of floats, optional, default None
            An N x 2 matrix, where N is the number of data points. If None,
            use an existing SAM projection (default t-SNE). Can take on values
            'umap' or 'tsne' to specify either the SAM UMAP embedding or
            SAM t-SNE embedding.

        c - ndarray or str, optional, default None
            Colors for each cell in the scatter plot. Can be a vector of
            floats or strings for cell annotations. Can also be a key
            for sam.adata.obs (i.e. 'louvain_clusters').

        axes - matplotlib axis, optional, default None
            Plot output to the specified, existing axes. If None, create new
            figure window.

        cmap - string, optional, default 'rainbow'
            The colormap to use for the input color values.

        colorbar - bool, optional default True
            If True, display a colorbar indicating which values / annotations
            correspond to which color in the scatter plot.

        Keyword arguments -
            All other keyword arguments that can be passed into
            matplotlib.pyplot.scatter can be used.
        """

        if (not PLOTTING):
            print("matplotlib not installed!")
        else:
            if(isinstance(projection, str)):
                try:
                    dt = self.adata.obsm[projection]
                except KeyError:
                    print('Please create a projection first using run_umap or'
                          'run_tsne')

            elif(projection is None):
                try:
                    dt = self.adata.obsm['X_umap']
                except KeyError:
                    try:
                        dt = self.adata.obsm['X_tsne']
                    except KeyError:
                        print("Please create either a t-SNE or UMAP projection"
                              "first.")
                        return
            else:
                dt = projection

            if(axes is None):
                plt.figure()
                axes = plt.gca()

            if(c is None):
                plt.scatter(dt[:, 0], dt[:, 1], s=s,
                            linewidth=linewidth, edgecolor=edgecolor, **kwargs)
            else:

                if isinstance(c, str):
                    try:
                        c = self.adata.obs[c].get_values()
                    except KeyError:
                        0  # do nothing

                if((isinstance(c[0], str) or isinstance(c[0], np.str_)) and
                   (isinstance(c, np.ndarray) or isinstance(c, list))):
                    i = ut.convert_annotations(c)
                    ui, ai = np.unique(i, return_index=True)
                    cax = axes.scatter(dt[:,0], dt[:,1], c=i, cmap=cmap, s=s,
                                       linewidth=linewidth,
                                       edgecolor=edgecolor,
                                       **kwargs)

                    if(colorbar):
                        cbar = plt.colorbar(cax, ax=axes, ticks=ui)
                        cbar.ax.set_yticklabels(c[ai])
                else:
                    if not (isinstance(c, np.ndarray) or isinstance(c, list)):
                        colorbar = False
                    i = c

                    cax = axes.scatter(dt[:,0], dt[:,1], c=i, cmap=cmap, s=s,
                                       linewidth=linewidth,
                                       edgecolor=edgecolor,
                                       **kwargs)

                    if(colorbar):
                        plt.colorbar(cax, ax=axes)
Similar code snippets
1.
ResidentMario/geoplot · geoplot.py
Match rating: 54.22% · See similar code snippets
python logo
def polyplot(df, projection=None,
             extent=None,
             figsize=(8, 6), ax=None,
             edgecolor='black',
             facecolor='None', **kwargs):
    """
    Trivial polygonal plot.

    Parameters
    ----------
    df : GeoDataFrame
        The data being plotted.
    projection : geoplot.crs object instance, optional
        A geographic projection. For more information refer to `the tutorial page on projections
        <https://nbviewer.jupyter.org/github/ResidentMario/geoplot/blob/master/notebooks/tutorials/Projections.ipynb>`_.
    extent : None or (minx, maxx, miny, maxy), optional
        Used to control plot x-axis and y-axis limits manually.
    figsize : tuple, optional
        An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot.
        Defaults to (8, 6), the ``matplotlib`` default global.
    figsize : tuple, optional
        An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot.
    ax : AxesSubplot or GeoAxesSubplot instance, optional
        A ``matplotlib.axes.AxesSubplot`` or ``cartopy.mpl.geoaxes.GeoAxesSubplot`` instance. Defaults to a new axis.
    kwargs: dict, optional
        Keyword arguments to be passed to the underlying ``matplotlib`` `Polygon patches
        <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_.

    Returns
    -------
    ``AxesSubplot`` or ``GeoAxesSubplot``
        The plot axis

    Examples
    --------

    The polyplot can be used to draw simple, unembellished polygons. A trivial example can be created with just a
    geometry and, optionally, a projection.

    .. code-block:: python

        import geoplot as gplt
        import geoplot.crs as gcrs
        gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea())


    .. image:: ../figures/polyplot/polyplot-initial.png

    However, note that ``polyplot`` is mainly intended to be used in concert with other plot types.

    .. code-block:: python

        ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea())
        gplt.pointplot(collisions[collisions['BOROUGH'].notnull()], projection=gcrs.AlbersEqualArea(),
                       hue='BOROUGH', categorical=True,
                       legend=True, edgecolor='white', linewidth=0.5, legend_kwargs={'loc': 'upper left'},
                       ax=ax)


    .. image:: ../figures/polyplot/polyplot-stacked.png

    Additional keyword arguments are passed to the underlying ``matplotlib`` `Polygon patches
    <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_.

    .. code-block:: python

        ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(),
                           linewidth=0, facecolor='lightgray')


    .. image:: ../figures/polyplot/polyplot-kwargs.png
    """
    # Initialize the figure.
    fig = _init_figure(ax, figsize)

    if projection:
        # Properly set up the projection.
        projection = projection.load(df, {
            'central_longitude': lambda df: np.mean(np.array([p.x for p in df.geometry.centroid])),
            'central_latitude': lambda df: np.mean(np.array([p.y for p in df.geometry.centroid]))
        })

        # Set up the axis.
        if not ax:
            ax = plt.subplot(111, projection=projection)

    else:
        if not ax:
            ax = plt.gca()

    # Clean up patches.
    _lay_out_axes(ax, projection)

    # Immediately return if input geometry is empty.
    if len(df.geometry) == 0:
        return ax

    # Set extent.
    extrema = _get_envelopes_min_maxes(df.geometry.envelope.exterior)
    _set_extent(ax, projection, extent, extrema)

    # Finally we draw the features.
    if projection:
        for geom in df.geometry:
            features = ShapelyFeature([geom], ccrs.PlateCarree())
            ax.add_feature(features, facecolor=facecolor, edgecolor=edgecolor, **kwargs)
    else:
        for geom in df.geometry:
            try:  # Duck test for MultiPolygon.
                for subgeom in geom:
                    feature = descartes.PolygonPatch(subgeom, facecolor=facecolor, edgecolor=edgecolor, **kwargs)
                    ax.add_patch(feature)
            except (TypeError, AssertionError):  # Shapely Polygon.
                feature = descartes.PolygonPatch(geom, facecolor=facecolor, edgecolor=edgecolor, **kwargs)
                ax.add_patch(feature)

    return ax
2.
zkbt/the-friendly-stars · constellation.py
Match rating: 53.76% · See similar code snippets
python logo
def plot(self, sizescale=10, color=None, alpha=0.5, label=None, edgecolor='none', **kw):
        '''
        Plot the ra and dec of the coordinates,
        at a given epoch, scaled by their magnitude.

        (This does *not* create a new empty figure.)

        Parameters
        ----------
        sizescale : (optional) float
            The marker size for scatter for a star at the magnitudelimit.
        color : (optional) any valid color
            The color to plot (but there is a default for this catalog.)
        **kw : dict
            Additional keywords will be passed on to plt.scatter.

        Returns
        -------

        plotted : outputs from the plots
        '''
        # calculate the sizes of the stars (logarithmic with brightness?)
        size = np.maximum(sizescale*(1 + self.magnitudelimit - self.magnitude), 1)

        # make a scatter plot of the RA + Dec
        scatter = plt.scatter(self.ra, self.dec,
                                    s=size,
                                    color=color or self.color,
                                    label=label or '{} ({:.1f})'.format(self.name, self.epoch),
                                    alpha=alpha,
                                    edgecolor=edgecolor,
                                    **kw)

        return scatter
3.
xoolive/traffic · opensky.py
Match rating: 53.68% · See similar code snippets
python logo
def plot(
        self, ax: GeoAxesSubplot, cmap: str = "inferno", s: int = 5, **kwargs
    ) -> Artist:
        """Plotting function. All arguments are passed to ax.scatter"""
        return ax.scatter(
            self.df.longitude,
            self.df.latitude,
            s=s,
            transform=PlateCarree(),
            c=-self.df.altitude,
            cmap=cmap,
            **kwargs,
        )
4.
zkbt/the-friendly-stars · constellation.py
Match rating: 52.27% · See similar code snippets
python logo
def allskyfinder(self, figsize=(14, 7), **kwargs):
        '''
        Plot an all-sky finder chart. This *does* create a new figure.
        '''

        plt.figure(figsize=figsize)
        scatter = self.plot(**kwargs)
        plt.xlabel(r'Right Ascension ($^\circ$)'); plt.ylabel(r'Declination ($^\circ$)')
        #plt.title('{} in {:.1f}'.format(self.name, epoch))
        plt.xlim(0, 360)
        plt.ylim(-90,90)
        return scatter
5.
markovmodel/PyEMMA · plots2d.py
Match rating: 52.04% · See similar code snippets
python logo
def scatter_contour(
        x, y, z, ncontours=50, colorbar=True, fig=None,
        ax=None, cmap=None, outfile=None):
    """Contour plot on scattered data (x,y,z) and
    plots the positions of the points (x,y) on top.

    Parameters
    ----------
    x : ndarray(T)
        x-coordinates
    y : ndarray(T)
        y-coordinates
    z : ndarray(T)
        z-coordinates
    ncontours : int, optional, default=50
        number of contour levels
    fig : matplotlib Figure object, optional, default=None
        the figure to plot into. When set to None the default
        Figure object will be used
    ax : matplotlib Axes object, optional, default=None
        the axes to plot to. When set to None the default Axes
        object will be used.
    cmap : matplotlib colormap, optional, default=None
        the color map to use. None will use pylab.cm.jet.
    outfile : str, optional, default=None
        output file to write the figure to. When not given,
        the plot will be displayed

    Returns
    -------
    ax : Axes object containing the plot

    """
    _warn(
        'scatter_contour is deprected; use plot_contour instead'
        ' and manually add a scatter plot on top.',
        DeprecationWarning)
    ax = contour(
        x, y, z, ncontours=ncontours, colorbar=colorbar,
        fig=fig, ax=ax, cmap=cmap)
    # scatter points
    ax.scatter(x , y, marker='o', c='b', s=5)
    # show or save
    if outfile is not None:
        ax.get_figure().savefig(outfile)
    return ax
6.
bloomberg/bqplot · pyplot.py
Match rating: 51.54% · See similar code snippets
python logo
def scatter(x, y, **kwargs):
    """Draw a scatter in the current context figure.

    Parameters
    ----------

    x: numpy.ndarray, 1d
        The x-coordinates of the data points.
    y: numpy.ndarray, 1d
        The y-coordinates of the data points.
    options: dict (default: {})
        Options for the scales to be created. If a scale labeled 'x' is
        required for that mark, options['x'] contains optional keyword
        arguments for the constructor of the corresponding scale type.
    axes_options: dict (default: {})
        Options for the axes to be created. If an axis labeled 'x' is required
        for that mark, axes_options['x'] contains optional keyword arguments
        for the constructor of the corresponding axis type.
    """
    kwargs['x'] = x
    kwargs['y'] = y
    return _draw_mark(Scatter, **kwargs)
7.
Match rating: 51.26% · See similar code snippets
python logo
def sentiment_scatter(sms=sms):
    plt.figure(figsize=(10, 7.5))
    ax = plt.subplot(1, 1, 1)
    ax = sms.plot.scatter(x='topic4', y='line', ax=ax, color='g', marker='+', alpha=.6)
    ax = sms.plot.scatter(x='topic4', y='sgd', ax=ax, color='r', marker='x', alpha=.4)
    ax = sms.plot.scatter(x='topic4', y='vader', ax=ax, color='k', marker='.', alpha=.3)
    ax = sms.plot.scatter(x='topic4', y='sgd', ax=ax, color='c', marker='s', alpha=.6)
    ax = sms.plot.scatter(x='topic4', y='pca_lda_spaminess', ax=ax, color='b', marker='o', alpha=.6)
    plt.ylabel('Sentiment')
    plt.xlabel('Topic 4')
    plt.legend(['LinearRegressor', 'SGDRegressor', 'Vader', 'OneNeuronRegresor', 'PCA->LDA->spaminess'])
    plt.tight_layout()
    plt.show()
8.
tBuLi/symfit · interactive_guess.py
Match rating: 50.98% · See similar code snippets
python logo
def plot_data(self, proj, ax):
        """
        Creates and plots a scatter plot of the original data.
        """
        x, y = proj
        ax.scatter(self.ig.independent_data[x],
                   self.ig.dependent_data[y], c='b')
9.
pandas-dev/pandas · _core.py
Match rating: 50.83% · See similar code snippets
python logo
def scatter_plot(data, x, y, by=None, ax=None, figsize=None, grid=False,
                 **kwargs):
    """
    Make a scatter plot from two DataFrame columns

    Parameters
    ----------
    data : DataFrame
    x : Column name for the x-axis values
    y : Column name for the y-axis values
    ax : Matplotlib axis object
    figsize : A tuple (width, height) in inches
    grid : Setting this to True will show the grid
    kwargs : other plotting keyword arguments
        To be passed to scatter function

    Returns
    -------
    matplotlib.Figure
    """
    import matplotlib.pyplot as plt

    kwargs.setdefault('edgecolors', 'none')

    def plot_group(group, ax):
        xvals = group[x].values
        yvals = group[y].values
        ax.scatter(xvals, yvals, **kwargs)
        ax.grid(grid)

    if by is not None:
        fig = _grouped_plot(plot_group, data, by=by, figsize=figsize, ax=ax)
    else:
        if ax is None:
            fig = plt.figure()
            ax = fig.add_subplot(111)
        else:
            fig = ax.get_figure()
        plot_group(data, ax)
        ax.set_ylabel(pprint_thing(y))
        ax.set_xlabel(pprint_thing(x))

        ax.grid(grid)

    return fig
10.
mattjj/pybasicbayes · gaussian.py
Match rating: 50.52% · See similar code snippets
python logo
def plot(self,ax=None,data=None,indices=None,color='b',
             plot_params=True,label='',alpha=1.,
             update=False,draw=True):
        import matplotlib.pyplot as plt
        from pybasicbayes.util.plot import project_data, \
                plot_gaussian_projection, plot_gaussian_2D
        ax = ax if ax else plt.gca()
        D = self.D
        if data is not None:
            data = flattendata(data)

        if data is not None:
            if D > 2:
                plot_basis = np.random.RandomState(seed=0).randn(2,D)
                data = project_data(data,plot_basis)
            if update and self._scatterplot is not None:
                self._scatterplot.set_offsets(data)
                self._scatterplot.set_color(color)
            else:
                self._scatterplot = ax.scatter(
                    data[:,0],data[:,1],marker='.',color=color)

        if plot_params:
            if D > 2:
                plot_basis = np.random.RandomState(seed=0).randn(2,D)
                self._parameterplot = \
                    plot_gaussian_projection(
                        self.mu,self.sigma,plot_basis,
                        color=color,label=label,alpha=min(1-1e-3,alpha),
                        ax=ax, artists=self._parameterplot if update else None)
            else:
                self._parameterplot = \
                    plot_gaussian_2D(
                        self.mu,self.sigma,color=color,label=label,
                        alpha=min(1-1e-3,alpha), ax=ax,
                        artists=self._parameterplot if update else None)

        if draw:
            plt.draw()

        return [self._scatterplot] + list(self._parameterplot)