astrofrog/mpl-scatter-density · scatter_density_axes.py
python logo
def scatter_density(self, x, y, dpi=72, downres_factor=4, color=None, cmap=None,
                        alpha=1.0, norm=None, **kwargs):
        """
        Make a density plot of the (x, y) scatter data.

        Parameters
        ----------
        x, y : iterable
            The data to plot
        dpi : int or `None`
            The number of dots per inch to include in the density map. To use
            the native resolution of the drawing device, set this to None.
        downres_factor : int
            For interactive devices, when panning, the density map will
            automatically be made at a lower resolution and including only a
            subset of the points. The new dpi of the figure when panning will
            then be dpi / downres_factor, and the number of elements in the
            arrays will be reduced by downres_factor**2.
        cmap : `matplotlib.colors.Colormap`
            The colormap to use for the density map.
        color : str or tuple
            The color to use for the density map. This can be any valid
            Matplotlib color. If specified, this takes precedence over the
            colormap.
        alpha : float
            Transparency of the density map
        norm : `matplotlib.colors.Normalize`
            The normalization class for the density map.
        """

        self.set_xlim(np.min(x), np.max(x))
        self.set_ylim(np.min(y), np.max(y))

        scatter = ScatterDensityArtist(self, x, y, dpi=dpi, downres_factor=downres_factor,
                                       color=color, cmap=cmap,
                                       alpha=alpha, norm=norm, **kwargs)
        self.add_artist(scatter)

        return scatter
Similar code snippets
1.
SiLab-Bonn/pyBAR · plotting.py
Match rating: 54.27% · See similar code snippets
python logo
def create_pixel_scatter_plot(ax, hist, title=None, x_axis_title=None, y_axis_title=None, y_min=None, y_max=None):
    scatter_y_mean = np.ma.mean(hist, axis=0)
    scatter_y = hist.flatten('F')
    if not scatter_y_mean.all() is np.ma.masked and not scatter_y.all() is np.ma.masked:
        ax.scatter(range(80 * 336), scatter_y, marker='o', s=0.8, rasterized=True)
        p1, = ax.plot(range(336 // 2, 80 * 336 + 336 // 2, 336), scatter_y_mean, 'o')
        ax.plot(range(336 // 2, 80 * 336 + 336 // 2, 336), scatter_y_mean, linewidth=2.0)
        ax.legend([p1], ["column mean"], prop={'size': 6})
    ax.set_xlim((0, 26880))
    if y_min is None:
        y_min = 0.0
    if y_max is None:
        if hist.all() is np.ma.masked or np.allclose(0, hist):  # check if masked array is fully masked
            y_max = 1.0
        else:
            y_max = max(1.0, hist.max())
    ax.set_ylim(ymin=y_min)
    ax.set_ylim(ymax=y_max)
    if title is not None:
        ax.title(title)
    if x_axis_title is not None:
        ax.set_xlabel(x_axis_title)
    if y_axis_title is not None:
        ax.set_ylabel(y_axis_title)
2.
mattjj/pybasicbayes · mixture.py
Match rating: 52.25% · See similar code snippets
python logo
def plot(self,color=None,legend=False,alpha=None,update=False,draw=True):
        import matplotlib.pyplot as plt
        from matplotlib import cm
        artists = []

        ### get colors
        cmap = cm.get_cmap()
        if color is None:
            label_colors = dict((idx,cmap(v))
                for idx, v in enumerate(np.linspace(0,1,self.N,endpoint=True)))
        else:
            label_colors = dict((idx,color) for idx in range(self.N))

        ### plot data scatter
        for l in self.labels_list:
            colorseq = [label_colors[label] for label in l.z]
            if update and hasattr(l,'_data_scatter'):
                l._data_scatter.set_offsets(l.data[:,:2])
                l._data_scatter.set_color(colorseq)
            else:
                l._data_scatter = plt.scatter(l.data[:,0],l.data[:,1],c=colorseq,s=5)
            artists.append(l._data_scatter)

        ### plot parameters
        axis = plt.axis()
        for label, (c, w) in enumerate(zip(self.components,self.weights.weights)):
            artists.extend(
                c.plot(
                    color=label_colors[label],
                    label='%d' % label,
                    alpha=min(0.25,1.-(1.-w)**2)/0.25 if alpha is None else alpha,
                    update=update,draw=False))
        plt.axis(axis)

        ### add legend
        if legend and color is None:
            plt.legend(
                [plt.Rectangle((0,0),1,1,fc=c)
                    for i,c in label_colors.items() if i in used_labels],
                [i for i in label_colors if i in used_labels],
                loc='best', ncol=2)

        if draw: plt.draw()
        return artists
3.
jor-/util · with_petsc4py.py
Match rating: 52.22% · See similar code snippets
python logo
def mult(self, context, x, y):
        logger.debug('Multiplying petsc matrix with vector without explicit matrix.')

        ## copy x to local vec
        scatter, x_local = petsc.Scatter.toAll(x)
        scatter.scatterBegin(x, x_local)
        scatter.scatterEnd(x, x_local)
        scatter.destroy()


        ## set y values
        y_ownership_range = y.getOwnershipRange()
        y_size_local = y_ownership_range[1] - y_ownership_range[0]
        y_size_global = y.getSize()

        for i_local in range(y_size_local):
            i_global = y_ownership_range[0] + i_local

            ## compute value
            value = 0
            for j_global in range(y_size_global):
                value += self.entry_function(i_global, j_global) * x_local.getValue(j_global)

            y.setValue(i_global, value)
        y.assemblyBegin()
        y.assemblyEnd()

        ## destroy local copy
        x_local.destroy()
4.
yjzhang/uncurl_python · vis.py
Match rating: 51.94% · See similar code snippets
python logo
def visualize_dim_red(r, labels, filename=None, figsize=(18,10), title='', legend=True, label_map=None, label_scale=False, label_color_map=None, **scatter_options):
    """
    Saves a scatter plot of a (2,n) matrix r, where each column is a cell.

    Args:
        r (array): (2,n) matrix
        labels (array): (n,) array of ints/strings or floats. Can be None.
        filename (string): string to save the output graph. If None, then this just displays the plot.
        figsize (tuple): Default: (18, 10)
        title (string): graph title
        legend (bool): Default: True
        label_map (dict): map of labels to label names. Default: None
        label_scale (bool): True if labels is should be treated as floats. Default: False
        label_color_map (array): (n,) array or list of colors for each label.
    """
    fig = plt.figure(figsize=figsize)
    plt.cla()
    if not label_scale:
        for i in set(labels):
            label = i
            if label_map is not None:
                label = label_map[i]
            if label_color_map is not None:
                c = label_color_map[i]
                plt.scatter(r[0, labels==i], r[1, labels==i], label=label, c=c, **scatter_options)
            else:
                plt.scatter(r[0, labels==i], r[1, labels==i], label=label, **scatter_options)
    else:
        if labels is None:
            plt.scatter(r[0,:], r[1,:], **scatter_options)
        else:
            plt.scatter(r[0,:], r[1,:], c=labels/labels.max(), **scatter_options)
    plt.title(title)
    if legend:
        plt.legend()
    if filename is not None:
        plt.savefig(filename, dpi=100)
        plt.close()
    return fig
5.
pyecharts/pyecharts · scatter_example.py
Match rating: 51.5% · See similar code snippets
python logo
def scatter_visualmap_color() -> Scatter:
    c = (
        Scatter()
        .add_xaxis(Faker.choose())
        .add_yaxis("商家A", Faker.values())
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Scatter-VisualMap(Color)"),
            visualmap_opts=opts.VisualMapOpts(max_=150),
        )
    )
    return c
6.
HIPS/autograd · ica.py
Match rating: 51.26% · See similar code snippets
python logo
def color_scatter(ax, xs, ys):
    colors = cm.rainbow(np.linspace(0, 1, len(ys)))
    for x, y, c in zip(xs, ys, colors):
        ax.scatter(x, y, color=c)
7.
vaexio/vaex · layers.py
Match rating: 50.23% · See similar code snippets
python logo
def plot_scatter(self, axes_list):
        for ax in axes_list:
            # TODO: support multiple axes with the axis index
            x = self.dataset.evaluate(self.x)
            y = self.dataset.evaluate(self.y)
            ax.scatter(x, y, alpha=self.state.alpha, color=self.color)
            row = self.dataset.get_current_row()
            if row is not None:
                ax.scatter([x[row]], [y[row]], alpha=self.state.alpha, color=self.color_alt)
8.
KrishnaswamyLab/PHATE · plot.py
Match rating: 49.52% · See similar code snippets
python logo
def rotate_scatter3d(data,
                     filename=None,
                     elev=30,
                     rotation_speed=30,
                     fps=10,
                     ax=None,
                     figsize=None,
                     dpi=None,
                     ipython_html="jshtml",
                     **kwargs):
    """Create a rotating 3D scatter plot

    Builds upon `matplotlib.pyplot.scatter` with nice defaults
    and handles categorical colors / legends better.

    Parameters
    ----------
    data : array-like, `phate.PHATE` or `scanpy.AnnData`
        Input data. Only the first three dimensions are used.
    filename : str, optional (default: None)
        If not None, saves a .gif or .mp4 with the output
    elev : float, optional (default: 30)
        Elevation of viewpoint from horizontal, in degrees
    rotation_speed : float, optional (default: 30)
        Speed of axis rotation, in degrees per second
    fps : int, optional (default: 10)
        Frames per second. Increase this for a smoother animation
    ax : `matplotlib.Axes` or None, optional (default: None)
        axis on which to plot. If None, an axis is created
    figsize : tuple, optional (default: None)
        Tuple of floats for creation of new `matplotlib` figure. Only used if
        `ax` is None.
    dpi : number, optional (default: None)
        Controls the dots per inch for the movie frames. This combined with
        the figure's size in inches controls the size of the movie.
        If None, defaults to rcParams["savefig.dpi"]
    ipython_html : {'html5', 'jshtml'}
        which html writer to use if using a Jupyter Notebook
    **kwargs : keyword arguments
        See :~func:`phate.plot.scatter3d`.

    Returns
    -------
    ani : `matplotlib.animation.FuncAnimation`
        animation object

    Examples
    --------
    >>> import phate
    >>> import matplotlib.pyplot as plt
    >>> tree_data, tree_clusters = phate.tree.gen_dla(n_dim=100, n_branch=20,
    ...                                               branch_length=100)
    >>> tree_data.shape
    (2000, 100)
    >>> phate_operator = phate.PHATE(n_components=3, k=5, a=20, t=150)
    >>> tree_phate = phate_operator.fit_transform(tree_data)
    >>> tree_phate.shape
    (2000, 2)
    >>> phate.plot.rotate_scatter3d(tree_phate, c=tree_clusters)
    """
    warnings.warn("`phate.plot.rotate_scatter3d` is deprecated. "
                  "Use `scprep.plot.rotate_scatter3d` instead.",
                  FutureWarning)
    return scprep.plot.rotate_scatter3d(data,
                                        filename=filename,
                                        elev=elev,
                                        rotation_speed=rotation_speed,
                                        fps=fps,
                                        ax=ax,
                                        figsize=figsize,
                                        dpi=dpi,
                                        ipython_html=ipython_html,
                                        **kwargs)
9.
gem/oq-engine · mapping.py
Match rating: 48.54% · See similar code snippets
python logo
def add_colour_scaled_points(self, longitude, latitude, data, shape='s',
                                 alpha=1.0, size=20, norm=None, overlay=False):
        """
        Overlays a set of points on a map with a fixed size but colour scaled
        according to the data

        :param np.ndarray longitude:
            Longitude
        :param np.ndarray latitude:
            Latitude
        :param np.ndarray data:
            Data for plotting
        :param str shape:
            Marker style
        :param float alpha:
            Sets the transparency of the marker (0 for transparent, 1 opaque)
        :param int size:
            Marker size
        :param norm:
            Normalisation as instance of :class: matplotlib.colors.Normalize
        """
        if not norm:
            norm = Normalize(vmin=np.min(data), vmax=np.max(data))
        x, y, = self.m(longitude, latitude)
        mappable = self.m.scatter(x, y,
                                  marker=shape,
                                  s=size,
                                  c=data,
                                  norm=norm,
                                  alpha=alpha,
                                  linewidths=0.0,
                                  zorder=4)
        self.m.colorbar(mappable=mappable, fig=self.fig, ax=self.ax)
        if not overlay:
            plt.show()
10.
taborlab/FlowCal · plot.py
Match rating: 47.74% · See similar code snippets
python logo
def scatter3d_and_projections(data_list,
                              channels=[0,1,2],
                              xscale='logicle',
                              yscale='logicle',
                              zscale='logicle',
                              xlabel=None,
                              ylabel=None,
                              zlabel=None,
                              xlim=None,
                              ylim=None,
                              zlim=None,
                              color=None,
                              figsize=None,
                              savefig=None,
                              **kwargs):
    """
    Plot a 3D scatter plot and 2D projections from FCSData objects.

    `scatter3d_and_projections` creates a 3D scatter plot and three 2D
    projected scatter plots in four different axes for each FCSData object
    in `data_list`, in the same figure.

    Parameters
    ----------
    data_list : FCSData object, or list of FCSData objects
        Flow cytometry data to plot.
    channels : list of int, list of str
        Three channels to use for the plot.
    savefig : str, optional
        The name of the file to save the figure to. If None, do not save.

    Other parameters
    ----------------
    xscale : str, optional
        Scale of the x axis, either ``linear``, ``log``, or ``logicle``.
    yscale : str, optional
        Scale of the y axis, either ``linear``, ``log``, or ``logicle``.
    zscale : str, optional
        Scale of the z axis, either ``linear``, ``log``, or ``logicle``.
    xlabel : str, optional
        Label to use on the x axis. If None, attempts to extract channel
        name from last data object.
    ylabel : str, optional
        Label to use on the y axis. If None, attempts to extract channel
        name from last data object.
    zlabel : str, optional
        Label to use on the z axis. If None, attempts to extract channel
        name from last data object.
    xlim : tuple, optional
        Limits for the x axis. If None, attempts to extract limits from the
        range of the last data object.
    ylim : tuple, optional
        Limits for the y axis. If None, attempts to extract limits from the
        range of the last data object.
    zlim : tuple, optional
        Limits for the z axis. If None, attempts to extract limits from the
        range of the last data object.
    color : matplotlib color or list of matplotlib colors, optional
        Color for the scatter plot. It can be a list with the same length
        as `data_list`. If `color` is not specified, elements from
        `data_list` are plotted with colors taken from the module-level
        variable `cmap_default`.
    figsize : tuple, optional
        Figure size. If None, use matplotlib's default.
    kwargs : dict, optional
        Additional parameters passed directly to matploblib's ``scatter``.

    Notes
    -----
    `scatter3d_and_projections` uses matplotlib's ``scatter``, with the 3D
    scatter plot using a 3D projection. Additional keyword arguments
    provided to `scatter3d_and_projections` are passed directly to
    ``scatter``.

    """
    # Check appropriate number of channels
    if len(channels) != 3:
        raise ValueError('three channels need to be specified')

    # Create figure
    plt.figure(figsize=figsize)

    # Axis 1: channel 0 vs channel 2
    plt.subplot(221)
    scatter2d(data_list,
              channels=[channels[0], channels[2]],
              xscale=xscale,
              yscale=zscale,
              xlabel=xlabel,
              ylabel=zlabel,
              xlim=xlim,
              ylim=zlim,
              color=color,
              **kwargs)

    # Axis 2: 3d plot
    ax_3d = plt.gcf().add_subplot(222, projection='3d')
    scatter3d(data_list,
              channels=channels,
              xscale=xscale,
              yscale=yscale,
              zscale=zscale,
              xlabel=xlabel,
              ylabel=ylabel,
              zlabel=zlabel,
              xlim=xlim,
              ylim=ylim,
              zlim=zlim,
              color=color,
              **kwargs)

    # Axis 3: channel 0 vs channel 1
    plt.subplot(223)
    scatter2d(data_list,
              channels=[channels[0], channels[1]],
              xscale=xscale,
              yscale=yscale,
              xlabel=xlabel,
              ylabel=ylabel,
              xlim=xlim,
              ylim=ylim,
              color=color,
              **kwargs)

    # Axis 4: channel 2 vs channel 1
    plt.subplot(224)
    scatter2d(data_list,
              channels=[channels[2], channels[1]],
              xscale=zscale,
              yscale=yscale,
              xlabel=zlabel,
              ylabel=ylabel,
              xlim=zlim,
              ylim=ylim,
              color=color,
              **kwargs)

    # Save if necessary
    if savefig is not None:
        plt.tight_layout()
        plt.savefig(savefig, dpi=savefig_dpi)
        plt.close()