newville/wxmplot · plotframe.py
python logo
def scatterplot(self, x, y, **kw):
        """plot after clearing current plot """
        self.panel.scatterplot(x, y, **kw)
Similar code snippets
1.
perimosocordiae/viztricks · extensions.py
Match rating: 58.71% · See similar code snippets
python logo
def jitterplot(data, positions=None, ax=None, vert=True, scale=0.1,
               **scatter_kwargs):
  '''Plots jittered points as a distribution visualizer.

  Scatter plot arguments default to: marker='.', c='k', alpha=0.75
  Also known as a stripplot.
  See also: boxplot, violinplot, beeswarm
  '''
  if ax is None:
    ax = plt.gca()
  if positions is None:
    positions = range(len(data))

  kwargs = dict(marker='.', c='k', alpha=0.75)
  kwargs.update(scatter_kwargs)

  for pos, y in zip(positions, data):
    if scale > 0:
      x = np.random.normal(loc=pos, scale=scale, size=len(y))
    else:
      x = np.zeros_like(y) + pos
    if not vert:
      x, y = y, x
    ax.scatter(x, y, **kwargs)
  return plt.show
2.
djordon/queueing-tool · graph_wrapper.py
Match rating: 57.84% · See similar code snippets
python logo
def draw_graph(self, line_kwargs=None, scatter_kwargs=None, **kwargs):
        """Draws the graph.

        Uses matplotlib, specifically
        :class:`~matplotlib.collections.LineCollection` and
        :meth:`~matplotlib.axes.Axes.scatter`. Gets the default
        keyword arguments for both methods by calling
        :meth:`~.QueueNetworkDiGraph.lines_scatter_args` first.

        Parameters
        ----------
        line_kwargs : dict (optional, default: ``None``)
            Any keyword arguments accepted by
            :class:`~matplotlib.collections.LineCollection`
        scatter_kwargs : dict (optional, default: ``None``)
            Any keyword arguments accepted by
            :meth:`~matplotlib.axes.Axes.scatter`.
        bgcolor : list (optional, keyword only)
            A list with 4 floats representing a RGBA color. Defaults
            to ``[1, 1, 1, 1]``.
        figsize : tuple (optional, keyword only, default: ``(7, 7)``)
            The width and height of the figure in inches.
        kwargs :
            Any keyword arguments used by
            :meth:`~matplotlib.figure.Figure.savefig`.

        Raises
        ------
        ImportError :
            If Matplotlib is not installed then an :exc:`ImportError`
            is raised.

        Notes
        -----
        If the ``fname`` keyword is passed, then the figure is saved
        locally.
        """
        if not HAS_MATPLOTLIB:
            raise ImportError("Matplotlib is required to draw the graph.")

        fig = plt.figure(figsize=kwargs.get('figsize', (7, 7)))
        ax = fig.gca()

        mpl_kwargs = {
            'line_kwargs': line_kwargs,
            'scatter_kwargs': scatter_kwargs,
            'pos': kwargs.get('pos')
        }

        line_kwargs, scatter_kwargs = self.lines_scatter_args(**mpl_kwargs)

        edge_collection = LineCollection(**line_kwargs)
        ax.add_collection(edge_collection)
        ax.scatter(**scatter_kwargs)

        if hasattr(ax, 'set_facecolor'):
            ax.set_facecolor(kwargs.get('bgcolor', [1, 1, 1, 1]))
        else:
            ax.set_axis_bgcolor(kwargs.get('bgcolor', [1, 1, 1, 1]))

        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

        if 'fname' in kwargs:
            # savefig needs a positional argument for some reason
            new_kwargs = {k: v for k, v in kwargs.items() if k in SAVEFIG_KWARGS}
            fig.savefig(kwargs['fname'], **new_kwargs)
        else:
            plt.ion()
            plt.show()
3.
wavefrontHQ/python-client · chart_source_query.py
Match rating: 56.2% · See similar code snippets
python logo
def scatter_plot_source(self, scatter_plot_source):
        """Sets the scatter_plot_source of this ChartSourceQuery.

        For scatter plots, does this query source the X-axis or the Y-axis  # noqa: E501

        :param scatter_plot_source: The scatter_plot_source of this ChartSourceQuery.  # noqa: E501
        :type: str
        """
        allowed_values = ["X", "Y"]  # noqa: E501
        if scatter_plot_source not in allowed_values:
            raise ValueError(
                "Invalid value for `scatter_plot_source` ({0}), must be one of {1}"  # noqa: E501
                .format(scatter_plot_source, allowed_values)
            )

        self._scatter_plot_source = scatter_plot_source
4.
djordon/queueing-tool · queue_network.py
Match rating: 52.25% · See similar code snippets
python logo
def animate(self, out=None, t=None, line_kwargs=None,
                scatter_kwargs=None, **kwargs):
        """Animates the network as it's simulating.

        The animations can be saved to disk or viewed in interactive
        mode. Closing the window ends the animation if viewed in
        interactive mode. This method calls
        :meth:`~matplotlib.axes.scatter`, and
        :class:`~matplotlib.collections.LineCollection`, and any
        keyword arguments they accept can be passed to them.

        Parameters
        ----------
        out : str (optional)
            The location where the frames for the images will be saved.
            If this parameter is not given, then the animation is shown
            in interactive mode.
        t : float (optional)
            The amount of simulation time to simulate forward. If
            given, and ``out`` is given, ``t`` is used instead of
            ``n``.
        line_kwargs : dict (optional, default: None)
            Any keyword arguments accepted by
            :class:`~matplotlib.collections.LineCollection`.
        scatter_kwargs : dict (optional, default: None)
            Any keyword arguments accepted by
            :meth:`~matplotlib.axes.Axes.scatter`.
        bgcolor : list (optional, keyword only)
            A list with 4 floats representing a RGBA color. The
            default is defined in ``self.colors['bgcolor']``.
        figsize : tuple (optional, keyword only, default: ``(7, 7)``)
            The width and height of the figure in inches.
        **kwargs :
            This method calls
            :class:`~matplotlib.animation.FuncAnimation` and
            optionally :meth:`.matplotlib.animation.FuncAnimation.save`.
            Any keyword that can be passed to these functions are
            passed via ``kwargs``.

        Notes
        -----
        There are several parameters automatically set and passed to
        matplotlib's :meth:`~matplotlib.axes.Axes.scatter`,
        :class:`~matplotlib.collections.LineCollection`, and
        :class:`~matplotlib.animation.FuncAnimation` by default.
        These include:

            * :class:`~matplotlib.animation.FuncAnimation`: Uses the
              defaults for that function. Saving the animation is done
              by passing the 'filename' keyword argument to this method.
              This method also accepts any keyword arguments accepted
              by :meth:`~matplotlib.animation.FuncAnimation.save`.
            * :class:`~matplotlib.collections.LineCollection`: The default
              arguments are taken from
              :meth:`.QueueNetworkDiGraph.lines_scatter_args`.
            * :meth:`~matplotlib.axes.Axes.scatter`: The default
              arguments are taken from
              :meth:`.QueueNetworkDiGraph.lines_scatter_args`.

        Raises
        ------
        QueueingToolError
            Will raise a :exc:`.QueueingToolError` if the
            ``QueueNetwork`` has not been initialized. Call
            :meth:`.initialize` before running.

        Examples
        --------
        This function works similarly to ``QueueNetwork's``
        :meth:`.draw` method.

        >>> import queueing_tool as qt
        >>> g = qt.generate_pagerank_graph(100, seed=13)
        >>> net = qt.QueueNetwork(g, seed=13)
        >>> net.initialize()
        >>> net.animate(figsize=(4, 4)) # doctest: +SKIP

        To stop the animation just close the window. If you want to
        write the animation to disk run something like the following:

        >>> kwargs = {
        ...     'filename': 'test.mp4',
        ...     'frames': 300,
        ...     'fps': 30,
        ...     'writer': 'mencoder',
        ...     'figsize': (4, 4),
        ...     'vertex_size': 15
        ... }
        >>> net.animate(**kwargs) # doctest: +SKIP
        """

        if not self._initialized:
            msg = ("Network has not been initialized. "
                   "Call '.initialize()' first.")
            raise QueueingToolError(msg)

        if not HAS_MATPLOTLIB:
            msg = "Matplotlib is necessary to animate a simulation."
            raise ImportError(msg)

        self._update_all_colors()
        kwargs.setdefault('bgcolor', self.colors['bgcolor'])

        fig = plt.figure(figsize=kwargs.get('figsize', (7, 7)))
        ax = fig.gca()

        mpl_kwargs = {
            'line_kwargs': line_kwargs,
            'scatter_kwargs': scatter_kwargs,
            'pos': kwargs.get('pos')
        }

        line_args, scat_args = self.g.lines_scatter_args(**mpl_kwargs)

        lines = LineCollection(**line_args)
        lines = ax.add_collection(lines)
        scatt = ax.scatter(**scat_args)

        t = np.infty if t is None else t
        now = self._t

        def update(frame_number):
            if t is not None:
                if self._t > now + t:
                    return False
            self._simulate_next_event(slow=True)
            lines.set_color(line_args['colors'])
            scatt.set_edgecolors(scat_args['edgecolors'])
            scatt.set_facecolor(scat_args['c'])

        if hasattr(ax, 'set_facecolor'):
            ax.set_facecolor(kwargs['bgcolor'])
        else:
            ax.set_axis_bgcolor(kwargs['bgcolor'])

        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

        animation_args = {
            'fargs': None,
            'event_source': None,
            'init_func': None,
            'frames': None,
            'blit': False,
            'interval': 10,
            'repeat': None,
            'func': update,
            'repeat_delay': None,
            'fig': fig,
            'save_count': None,
        }
        for key, value in kwargs.items():
            if key in animation_args:
                animation_args[key] = value

        animation = FuncAnimation(**animation_args)
        if 'filename' not in kwargs:
            plt.ioff()
            plt.show()
        else:
            save_args = {
                'filename': None,
                'writer': None,
                'fps': None,
                'dpi': None,
                'codec': None,
                'bitrate': None,
                'extra_args': None,
                'metadata': None,
                'extra_anim': None,
                'savefig_kwargs': None
            }
            for key, value in kwargs.items():
                if key in save_args:
                    save_args[key] = value

            animation.save(**save_args)
5.
ahwillia/tensortools · visualization.py
Match rating: 52.21% · See similar code snippets
python logo
def plot_factors(U, plots='line', fig=None, axes=None, scatter_kw=dict(),
                 line_kw=dict(), bar_kw=dict(), **kwargs):
    """Plots a KTensor.

    Note: Each keyword option is broadcast to all modes of the KTensor. For
    example, if `U` is a 3rd-order tensor (i.e. `U.ndim == 3`) then
    `plot_factors(U, plots=['line','bar','scatter'])` plots all factors for the
    first mode as a line plot, the second as a bar plot, and the third mode as
    a scatterplot. But, thanks to broadcasting semantics,
    `plot_factors(U, color='line')` produces line plots for each mode.

    Parameters
    ----------
    U : KTensor
        Kruskal tensor to be plotted.

    plots : str or list
        One of {'bar','line','scatter'} to specify the type of plot for each
        factor. The default is 'line'.
    fig : matplotlib Figure object
        If provided, add plots to the specified figure. The figure must have a
        sufficient number of axes objects.
    axes : 2d numpy array of matplotlib Axes objects
        If provided, add plots to the specified figure.
    scatter_kw : dict or sequence of dicts
        Keyword arguments provided to scatterplots. If a single dict is
        provided, these options are broadcasted to all modes.
    line_kw : dict or sequence of dicts
        Keyword arguments provided to line plots. If a single dict is provided,
        these options are broadcasted to all modes.
    bar_kw : dict or sequence of dicts
        Keyword arguments provided to bar plots. If a single dict is provided,
        these options are broadcasted to all modes.
    **kwargs : dict
        Additional keyword parameters are passed to the `subplots(...)`
        function to specify options such as `figsize` and `gridspec_kw`. See
        `matplotlib.pyplot.subplots(...)` documentation for more info.
    """

    # ~~~~~~~~~~~~~
    # PARSE OPTIONS
    # ~~~~~~~~~~~~~
    kwargs.setdefault('figsize', (8, U.rank))

    # parse optional inputs
    plots = _broadcast_arg(U, plots, str, 'plots')
    bar_kw = _broadcast_arg(U, bar_kw, dict, 'bar_kw')
    line_kw = _broadcast_arg(U, line_kw, dict, 'line_kw')
    scatter_kw = _broadcast_arg(U, scatter_kw, dict, 'scatter_kw')

    # default scatterplot options
    for sckw in scatter_kw:
        sckw.setdefault('edgecolor', 'none')
        sckw.setdefault('s', 10)

    # ~~~~~~~~~~~~~~
    # SETUP SUBPLOTS
    # ~~~~~~~~~~~~~~
    if fig is None and axes is None:
        fig, axes = plt.subplots(U.rank, U.ndim, **kwargs)
        # make sure axes is a 2d-array
        if U.rank == 1:
            axes = axes[None, :]

    # if axes are passed in, identify figure
    elif fig is None:
        fig = axes[0, 0].get_figure()

    # if figure is passed, identify axes
    else:
        axes = np.array(fig.get_axes(), dtype=object).reshape(U.rank, U.ndim)

    # main loop, plot each factor
    plot_obj = np.empty((U.rank, U.ndim), dtype=object)
    for r in range(U.rank):
        for i, f in enumerate(U):
            # start plots at 1 instead of zero
            x = np.arange(1, f.shape[0]+1)

            # determine type of plot
            if plots[i] == 'bar':
                plot_obj[r, i] = axes[r, i].bar(x, f[:, r], **bar_kw[i])
                axes[r, i].set_xlim(0, f.shape[0]+1)
            elif plots[i] == 'scatter':
                plot_obj[r, i] = axes[r, i].scatter(x, f[:, r], **scatter_kw[i])
                axes[r, i].set_xlim(0, f.shape[0])
            elif plots[i] == 'line':
                plot_obj[r, i] = axes[r, i].plot(f[:, r], '-', **line_kw[i])
                axes[r, i].set_xlim(0, f.shape[0])
            else:
                raise ValueError('invalid plot type')

            # format axes
            axes[r, i].locator_params(nbins=4)
            axes[r, i].spines['top'].set_visible(False)
            axes[r, i].spines['right'].set_visible(False)
            axes[r, i].xaxis.set_tick_params(direction='out')
            axes[r, i].yaxis.set_tick_params(direction='out')
            axes[r, i].yaxis.set_ticks_position('left')
            axes[r, i].xaxis.set_ticks_position('bottom')

            # remove xticks on all but bottom row
            if r != U.rank-1:
                plt.setp(axes[r, i].get_xticklabels(), visible=False)

    # link y-axes within columns
    for i in range(U.ndim):
        yl = [a.get_ylim() for a in axes[:, i]]
        y0, y1 = min([y[0] for y in yl]), max([y[1] for y in yl])
        [a.set_ylim((y0, y1)) for a in axes[:, i]]

    # format y-ticks
    for r in range(U.rank):
        for i in range(U.ndim):
            # only two labels
            ymin, ymax = np.round(axes[r, i].get_ylim(), 2)
            axes[r, i].set_ylim((ymin, ymax))

            # remove decimals from labels
            if ymin.is_integer():
                ymin = int(ymin)
            if ymax.is_integer():
                ymax = int(ymax)

            # update plot
            axes[r, i].set_yticks([ymin, ymax])

    plt.tight_layout()

    return fig, axes, plot_obj
6.
vaexio/vaex · main.py
Match rating: 51.64% · See similar code snippets
python logo
def onOpenScatter(self):
        if self.dataset is not None:
            xname, yname = self.default_columns_2d
            self.plotxy(xname, yname)
7.
DistrictDataLabs/yellowbrick · gallery.py
Match rating: 51.14% · See similar code snippets
python logo
def scatter():
    X, y = load_occupancy()
    oz = ScatterVisualizer(x="light", y="CO2", ax=newfig())
    oz.fit_transform(X, y)
    savefig(oz, "scatter")
8.
pyviz/holoviews · __init__.py
Match rating: 50.44% · See similar code snippets
python logo
def scatter3d(self, kdims=None, vdims=None, groupby=None, **kwargs):
        return self(Scatter3D, kdims, vdims, groupby, **kwargs)
9.
ahwillia/tensortools · visualization.py
Match rating: 48.7% · See similar code snippets
python logo
def plot_objective(ensemble, partition='train', ax=None, jitter=0.1,
                   scatter_kw=dict(), line_kw=dict()):
    """Plots objective function as a function of model rank.

    Parameters
    ----------
    ensemble : Ensemble object
        holds optimization results across a range of model ranks
    partition : string, one of: {'train', 'test'}
        specifies whether to plot the objective function on the training
        data or the held-out test set.
    ax : matplotlib axis (optional)
        axis to plot on (defaults to current axis object)
    jitter : float (optional)
        amount of horizontal jitter added to scatterpoints (default=0.1)
    scatter_kw : dict (optional)
        keyword arguments for styling the scatterpoints
    line_kw : dict (optional)
        keyword arguments for styling the line
    """

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

    if partition == 'train':
        pass
    elif partition == 'test':
        raise NotImplementedError('Cross-validation is on the TODO list.')
    else:
        raise ValueError("partition must be 'train' or 'test'.")

    # compile statistics for plotting
    x, obj, min_obj = [], [], []
    for rank in sorted(ensemble.results):
        # reconstruction errors for rank-r models
        o = ensemble.objectives(rank)
        obj.extend(o)
        x.extend(np.full(len(o), rank))
        min_obj.append(min(o))

    # add horizontal jitter
    ux = np.unique(x)
    x = np.array(x) + (np.random.rand(len(x))-0.5)*jitter

    # make plot
    ax.scatter(x, obj, **scatter_kw)
    ax.plot(ux, min_obj, **line_kw)
    ax.set_xlabel('model rank')
    ax.set_ylabel('objective')

    return ax
10.
SheffieldML/GPy · latent_plots.py
Match rating: 48.52% · See similar code snippets
python logo
def plot_latent_inducing(self,
                        which_indices=None,
                        legend=False,
                        plot_limits=None,
                        marker=None,
                        projection='2d',
                        **kwargs):
    """
    Plot a scatter plot of the inducing inputs.

    :param [int] which_indices: which input dimensions to plot against each other
    :param bool legend: whether to plot the legend on the figure
    :param plot_limits: the plot limits for the plot
    :type plot_limits: (xmin, xmax, ymin, ymax) or ((xmin, xmax), (ymin, ymax))
    :param str marker: marker to use [default is custom arrow like]
    :param kwargs: the kwargs for the scatter plots
    :param str projection: for now 2d or 3d projection (other projections can be implemented, see developer documentation)
    """
    canvas, projection, kwargs, sig_dims = _new_canvas(self, projection, kwargs, which_indices)

    if legend: label = 'inducing'
    else: label = None
    if marker is not None:
        kwargs['marker'] = marker
    update_not_existing_kwargs(kwargs, pl().defaults.inducing_2d)  # @UndefinedVariable
    from .data_plots import _plot_inducing
    scatters = _plot_inducing(self, canvas, sig_dims[:2], projection, label, **kwargs)
    return pl().add_to_canvas(canvas, dict(scatter=scatters), legend=legend)