yjzhang/uncurl_python · vis.py
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
Similar code snippets
1.
SheffieldML/GPy · latent_plots.py
Match rating: 58.01% · See similar code snippets
python logo
def _plot_latent_scatter(canvas, X, visible_dims, labels, marker, num_samples, projection='2d', **kwargs):
    from .. import Tango
    Tango.reset()
    X, labels = subsample_X(X, labels, num_samples)
    scatters = []
    generate_colors = 'color' not in kwargs
    for x, y, z, this_label, _, m in scatter_label_generator(labels, X, visible_dims, marker):
        update_not_existing_kwargs(kwargs, pl().defaults.latent_scatter)
        if generate_colors:
            kwargs['color'] = Tango.nextMedium()
        if projection == '3d':
            scatters.append(pl().scatter(canvas, x, y, Z=z, marker=m, label=this_label, **kwargs))
        else: scatters.append(pl().scatter(canvas, x, y, marker=m, label=this_label, **kwargs))
    return scatters
2.
reiinakano/scikit-plot · plotters.py
Match rating: 56.73% · See similar code snippets
python logo
def plot_pca_2d_projection(clf, X, y, title='PCA 2-D Projection', ax=None,
                           figsize=None, cmap='Spectral',
                           title_fontsize="large", text_fontsize="medium"):
    """Plots the 2-dimensional projection of PCA on a given dataset.

    Args:
        clf: Fitted PCA instance that can ``transform`` given data set into 2
            dimensions.

        X (array-like, shape (n_samples, n_features)):
            Feature set to project, where n_samples is the number of samples
            and n_features is the number of features.

        y (array-like, shape (n_samples) or (n_samples, n_features)):
            Target relative to X for labeling.

        title (string, optional): Title of the generated plot. Defaults to
            "PCA 2-D Projection"

        ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
            plot the curve. If None, the plot is drawn on a new set of axes.

        figsize (2-tuple, optional): Tuple denoting figure size of the plot
            e.g. (6, 6). Defaults to ``None``.

        cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
            Colormap used for plotting the projection. View Matplotlib Colormap
            documentation for available options.
            https://matplotlib.org/users/colormaps.html

        title_fontsize (string or int, optional): Matplotlib-style fontsizes.
            Use e.g. "small", "medium", "large" or integer-values. Defaults to
            "large".

        text_fontsize (string or int, optional): Matplotlib-style fontsizes.
            Use e.g. "small", "medium", "large" or integer-values. Defaults to
            "medium".

    Returns:
        ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
            drawn.

    Example:
        >>> import scikitplot.plotters as skplt
        >>> pca = PCA(random_state=1)
        >>> pca.fit(X)
        >>> skplt.plot_pca_2d_projection(pca, X, y)
        <matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
        >>> plt.show()

        .. image:: _static/examples/plot_pca_2d_projection.png
           :align: center
           :alt: PCA 2D Projection
    """
    transformed_X = clf.transform(X)
    if ax is None:
        fig, ax = plt.subplots(1, 1, figsize=figsize)

    ax.set_title(title, fontsize=title_fontsize)
    classes = np.unique(np.array(y))

    colors = plt.cm.get_cmap(cmap)(np.linspace(0, 1, len(classes)))

    for label, color in zip(classes, colors):
        ax.scatter(transformed_X[y == label, 0], transformed_X[y == label, 1],
                   alpha=0.8, lw=2, label=label, color=color)
    ax.legend(loc='best', shadow=False, scatterpoints=1,
              fontsize=text_fontsize)
    ax.set_xlabel('First Principal Component', fontsize=text_fontsize)
    ax.set_ylabel('Second Principal Component', fontsize=text_fontsize)
    ax.tick_params(labelsize=text_fontsize)

    return ax
3.
SheffieldML/GPy · plot_definitions.py
Match rating: 55.22% · See similar code snippets
python logo
def scatter(self, ax, X, Y, Z=None, color=Tango.colorsHex['mediumBlue'], label=None, marker='o', **kwargs):
        if Z is not None:
            return ax.scatter(X, Y, c=color, zs=Z, label=label, marker=marker, **kwargs)
        return ax.scatter(X, Y, c=color, label=label, marker=marker, **kwargs)
4.
newville/wxmplot · plotframe.py
Match rating: 54.5% · See similar code snippets
python logo
def scatterplot(self, x, y, **kw):
        """plot after clearing current plot """
        self.panel.scatterplot(x, y, **kw)
5.
zkbt/the-friendly-stars · constellation.py
Match rating: 53.77% · 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
6.
yjzhang/uncurl_python · vis.py
Match rating: 53.69% · See similar code snippets
python logo
def visualize_poisson_w(w, labels, filename, method='pca', figsize=(18,10), title='', **scatter_options):
    """
    Saves a scatter plot of a visualization of W, the result from Poisson SE.
    """
    if method == 'pca':
        pca = PCA(2)
        r_dim_red = pca.fit_transform(w.T).T
    elif method == 'tsne':
        pass
    else:
        print("Method is not available. use 'pca' (default) or 'tsne'.")
        return
    visualize_dim_red(r_dim_red, labels, filename, figsize, title, **scatter_options)
7.
reiinakano/scikit-plot · decomposition.py
Match rating: 53.55% · See similar code snippets
python logo
def plot_pca_2d_projection(clf, X, y, title='PCA 2-D Projection',
                           biplot=False, feature_labels=None,
                           ax=None, figsize=None, cmap='Spectral',
                           title_fontsize="large", text_fontsize="medium"):
    """Plots the 2-dimensional projection of PCA on a given dataset.

    Args:
        clf: Fitted PCA instance that can ``transform`` given data set into 2
            dimensions.

        X (array-like, shape (n_samples, n_features)):
            Feature set to project, where n_samples is the number of samples
            and n_features is the number of features.

        y (array-like, shape (n_samples) or (n_samples, n_features)):
            Target relative to X for labeling.

        title (string, optional): Title of the generated plot. Defaults to
            "PCA 2-D Projection"

        biplot (bool, optional): If True, the function will generate and plot
        	biplots. If false, the biplots are not generated.

        feature_labels (array-like, shape (n_classes), optional): List of labels
        	that represent each feature of X. Its index position must also be
        	relative to the features. If ``None`` is given, then labels will be
        	automatically generated for each feature.
        	e.g. "variable1", "variable2", "variable3" ...

        ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
            plot the curve. If None, the plot is drawn on a new set of axes.

        figsize (2-tuple, optional): Tuple denoting figure size of the plot
            e.g. (6, 6). Defaults to ``None``.

        cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
            Colormap used for plotting the projection. View Matplotlib Colormap
            documentation for available options.
            https://matplotlib.org/users/colormaps.html

        title_fontsize (string or int, optional): Matplotlib-style fontsizes.
            Use e.g. "small", "medium", "large" or integer-values. Defaults to
            "large".

        text_fontsize (string or int, optional): Matplotlib-style fontsizes.
            Use e.g. "small", "medium", "large" or integer-values. Defaults to
            "medium".

    Returns:
        ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
            drawn.

    Example:
        >>> import scikitplot as skplt
        >>> pca = PCA(random_state=1)
        >>> pca.fit(X)
        >>> skplt.decomposition.plot_pca_2d_projection(pca, X, y)
        <matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
        >>> plt.show()

        .. image:: _static/examples/plot_pca_2d_projection.png
           :align: center
           :alt: PCA 2D Projection
    """
    transformed_X = clf.transform(X)
    if ax is None:
        fig, ax = plt.subplots(1, 1, figsize=figsize)

    ax.set_title(title, fontsize=title_fontsize)
    classes = np.unique(np.array(y))

    colors = plt.cm.get_cmap(cmap)(np.linspace(0, 1, len(classes)))

    for label, color in zip(classes, colors):
        ax.scatter(transformed_X[y == label, 0], transformed_X[y == label, 1],
                   alpha=0.8, lw=2, label=label, color=color)

    if biplot:
        xs = transformed_X[:, 0]
        ys = transformed_X[:, 1]
        vectors = np.transpose(clf.components_[:2, :])
        vectors_scaled = vectors * [xs.max(), ys.max()]
        for i in range(vectors.shape[0]):
            ax.annotate("", xy=(vectors_scaled[i, 0], vectors_scaled[i, 1]),
                        xycoords='data', xytext=(0, 0), textcoords='data',
                        arrowprops={'arrowstyle': '-|>', 'ec': 'r'})

            ax.text(vectors_scaled[i, 0] * 1.05, vectors_scaled[i, 1] * 1.05,
                    feature_labels[i] if feature_labels else "Variable" + str(i),
                    color='b', fontsize=text_fontsize)

    ax.legend(loc='best', shadow=False, scatterpoints=1,
              fontsize=text_fontsize)
    ax.set_xlabel('First Principal Component', fontsize=text_fontsize)
    ax.set_ylabel('Second Principal Component', fontsize=text_fontsize)
    ax.tick_params(labelsize=text_fontsize)

    return ax
8.
pyecharts/pyecharts · scatter_example.py
Match rating: 53.26% · 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
9.
zkbt/the-friendly-stars · constellation.py
Match rating: 53.17% · 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
10.
lappis-unb/salic-ml · plotter.py
Match rating: 52.78% · See similar code snippets
python logo
def set_plot_style(x_label, y_label, title):
        plt.xlabel(x_label)
        plt.ylabel(y_label)
        plt.title(title)