Initial configuration commit

This commit is contained in:
Alex Selimov 2023-10-24 22:54:55 -04:00
commit 31c8abea59
266 changed files with 780274 additions and 0 deletions

View file

@ -0,0 +1,21 @@
"""
This type stub file was generated by pyright.
"""
import matplotlib as mpl
from .rcmod import *
from .utils import *
from .palettes import *
from .relational import *
from .regression import *
from .categorical import *
from .distributions import *
from .matrix import *
from .miscplot import *
from .axisgrid import *
from .widgets import *
from .colors import crayons, xkcd_rgb
from . import cm
_orig_rc_params = ...
__version__ = ...

275
typings/seaborn/_core.pyi Normal file
View file

@ -0,0 +1,275 @@
"""
This type stub file was generated by pyright.
"""
from ._decorators import share_init_params_with_map
class SemanticMapping:
"""Base class for mapping data values to plot attributes."""
map_type = ...
levels = ...
lookup_table = ...
def __init__(self, plotter) -> None:
...
def map(cls, plotter, *args, **kwargs):
...
def __call__(self, key, *args, **kwargs): # -> list[Unknown]:
"""Get the attribute(s) values for the data key."""
...
@share_init_params_with_map
class HueMapping(SemanticMapping):
"""Mapping that sets artist colors according to data values."""
palette = ...
norm = ...
cmap = ...
def __init__(self, plotter, palette=..., order=..., norm=...) -> None:
"""Map the levels of the `hue` variable to distinct colors.
Parameters
----------
# TODO add generic parameters
"""
...
def infer_map_type(self, palette, norm, input_format, var_type): # -> Literal['categorical', 'numeric']:
"""Determine how to implement the mapping."""
...
def categorical_mapping(self, data, palette, order): # -> tuple[list[Any], dict[Unknown, Unknown] | dict[Any, str | tuple[float, float, float]]]:
"""Determine colors when the hue mapping is categorical."""
...
def numeric_mapping(self, data, palette, norm): # -> tuple[list[Unknown] | list[Any], dict[Unknown, Unknown], Unknown, Unknown | _ColorPalette | list[tuple[float, float, float]] | Any | list[str] | Literal['ch:']]:
"""Determine colors when the hue variable is quantitative."""
...
@share_init_params_with_map
class SizeMapping(SemanticMapping):
"""Mapping that sets artist sizes according to data values."""
norm = ...
def __init__(self, plotter, sizes=..., order=..., norm=...) -> None:
"""Map the levels of the `size` variable to distinct values.
Parameters
----------
# TODO add generic parameters
"""
...
def infer_map_type(self, norm, sizes, var_type): # -> Literal['numeric', 'categorical']:
...
def categorical_mapping(self, data, sizes, order): # -> tuple[list[Any], dict[Unknown, Unknown] | dict[Any, Unknown]]:
...
def numeric_mapping(self, data, sizes, norm): # -> tuple[list[Any], dict[Unknown, Unknown] | dict[Any, Unknown], Unknown]:
...
@share_init_params_with_map
class StyleMapping(SemanticMapping):
"""Mapping that sets artist style according to data values."""
map_type = ...
def __init__(self, plotter, markers=..., dashes=..., order=...) -> None:
"""Map the levels of the `style` variable to distinct values.
Parameters
----------
# TODO add generic parameters
"""
...
class VectorPlotter:
"""Base class for objects underlying *plot functions."""
_semantic_mappings = ...
semantics = ...
wide_structure = ...
flat_structure = ...
_default_size_range = ...
def __init__(self, data=..., variables=...) -> None:
...
@classmethod
def get_semantics(cls, kwargs, semantics=...): # -> dict[Unknown, Unknown]:
"""Subset a dictionary` arguments with known semantic variables."""
...
@property
def has_xy_data(self): # -> bool:
"""Return True at least one of x or y is defined."""
...
@property
def var_levels(self): # -> dict[Unknown, Unknown]:
"""Property interface to ordered list of variables levels.
Each time it's accessed, it updates the var_levels dictionary with the
list of levels in the current semantic mappers. But it also allows the
dictionary to persist, so it can be used to set levels by a key. This is
used to track the list of col/row levels using an attached FacetGrid
object, but it's kind of messy and ideally fixed by improving the
faceting logic so it interfaces better with the modern approach to
tracking plot variables.
"""
...
def assign_variables(self, data=..., variables=...): # -> Self@VectorPlotter:
"""Define plot variables, optionally using lookup from `data`."""
...
def iter_data(self, grouping_vars=..., reverse=..., from_comp_data=...): # -> Generator[tuple[dict[str | Unknown, Any], DataFrame | Series | Unknown] | tuple[dict[Unknown, Unknown], DataFrame | Unknown], Any, None]:
"""Generator for getting subsets of data defined by semantic variables.
Also injects "col" and "row" into grouping semantics.
Parameters
----------
grouping_vars : string or list of strings
Semantic variables that define the subsets of data.
reverse : bool, optional
If True, reverse the order of iteration.
from_comp_data : bool, optional
If True, use self.comp_data rather than self.plot_data
Yields
------
sub_vars : dict
Keys are semantic names, values are the level of that semantic.
sub_data : :class:`pandas.DataFrame`
Subset of ``plot_data`` for this combination of semantic values.
"""
...
@property
def comp_data(self): # -> DataFrame:
"""Dataframe with numeric x and y, after unit conversion and log scaling."""
...
def variable_type(vector, boolean_type=...): # -> str:
"""
Determine whether a vector contains numeric, categorical, or datetime data.
This function differs from the pandas typing API in two ways:
- Python sequences or object-typed PyData objects are considered numeric if
all of their entries are numeric.
- String or mixed-type data are considered categorical even if not
explicitly represented as a :class:`pandas.api.types.CategoricalDtype`.
Parameters
----------
vector : :func:`pandas.Series`, :func:`numpy.ndarray`, or Python sequence
Input data to test.
boolean_type : 'numeric' or 'categorical'
Type to use for vectors containing only 0s and 1s (and NAs).
Returns
-------
var_type : 'numeric', 'categorical', or 'datetime'
Name identifying the type of data in the vector.
"""
...
def infer_orient(x=..., y=..., orient=..., require_numeric=...): # -> Literal['v', 'h']:
"""Determine how the plot should be oriented based on the data.
For historical reasons, the convention is to call a plot "horizontally"
or "vertically" oriented based on the axis representing its dependent
variable. Practically, this is used when determining the axis for
numerical aggregation.
Paramters
---------
x, y : Vector data or None
Positional data vectors for the plot.
orient : string or None
Specified orientation, which must start with "v" or "h" if not None.
require_numeric : bool
If set, raise when the implied dependent variable is not numeric.
Returns
-------
orient : "v" or "h"
Raises
------
ValueError: When `orient` is not None and does not start with "h" or "v"
TypeError: When dependant variable is not numeric, with `require_numeric`
"""
...
def unique_dashes(n): # -> list[Unknown]:
"""Build an arbitrarily long list of unique dash styles for lines.
Parameters
----------
n : int
Number of unique dash specs to generate.
Returns
-------
dashes : list of strings or tuples
Valid arguments for the ``dashes`` parameter on
:class:`matplotlib.lines.Line2D`. The first spec is a solid
line (``""``), the remainder are sequences of long and short
dashes.
"""
...
def unique_markers(n): # -> list[Unknown]:
"""Build an arbitrarily long list of unique marker styles for points.
Parameters
----------
n : int
Number of unique marker specs to generate.
Returns
-------
markers : list of string or tuples
Values for defining :class:`matplotlib.markers.MarkerStyle` objects.
All markers will be filled.
"""
...
def categorical_order(vector, order=...): # -> list[Any]:
"""Return a list of unique data values.
Determine an ordered list of levels in ``values``.
Parameters
----------
vector : list, array, Categorical, or Series
Vector of "categorical" values
order : list-like, optional
Desired order of category levels to override the order determined
from the ``values`` object.
Returns
-------
order : list
Ordered list of category levels not including null values.
"""
...

View file

@ -0,0 +1,8 @@
"""
This type stub file was generated by pyright.
"""
def share_init_params_with_map(cls):
"""Make cls.map a classmethod with same signature as cls.__init__."""
...

View file

@ -0,0 +1,30 @@
"""
This type stub file was generated by pyright.
"""
class DocstringComponents:
regexp = ...
def __init__(self, comp_dict, strip_whitespace=...) -> None:
"""Read entries from a dict, optionally stripping outer whitespace."""
...
def __getattr__(self, attr): # -> Any:
"""Provided dot access to entries."""
...
@classmethod
def from_nested_components(cls, **kwargs): # -> Self@DocstringComponents:
"""Add multiple sub-sets of components."""
...
@classmethod
def from_function_params(cls, func): # -> Self@DocstringComponents:
"""Use the numpydoc parser to extract components from existing func."""
...
_core_params = ...
_core_returns = ...
_seealso_blurbs = ...
_core_docs = ...

View file

@ -0,0 +1,132 @@
"""
This type stub file was generated by pyright.
"""
"""Statistical transformations for visualization.
This module is currently private, but is being written to eventually form part
of the public API.
The classes should behave roughly in the style of scikit-learn.
- All data-independent parameters should be passed to the class constructor.
- Each class should impelment a default transformation that is exposed through
__call__. These are currently written for vector arguements, but I think
consuming a whole `plot_data` DataFrame and return it with transformed
variables would make more sense.
- Some class have data-dependent preprocessing that should be cached and used
multiple times (think defining histogram bins off all data and then counting
observations within each bin multiple times per data subsets). These currently
have unique names, but it would be good to have a common name. Not quite
`fit`, but something similar.
- Alternatively, the transform interface could take some information about grouping
variables and do a groupby internally.
- Some classes should define alternate transforms that might make the most sense
with a different function. For example, KDE usually evaluates the distribution
on a regular grid, but it would be useful for it to transform at the actual
datapoints. Then again, this could be controlled by a parameter at the time of
class instantiation.
"""
class KDE:
"""Univariate and bivariate kernel density estimator."""
def __init__(self, *, bw_method=..., bw_adjust=..., gridsize=..., cut=..., clip=..., cumulative=...) -> None:
"""Initialize the estimator with its parameters.
Parameters
----------
bw_method : string, scalar, or callable, optional
Method for determining the smoothing bandwidth to use; passed to
:class:`scipy.stats.gaussian_kde`.
bw_adjust : number, optional
Factor that multiplicatively scales the value chosen using
``bw_method``. Increasing will make the curve smoother. See Notes.
gridsize : int, optional
Number of points on each dimension of the evaluation grid.
cut : number, optional
Factor, multiplied by the smoothing bandwidth, that determines how
far the evaluation grid extends past the extreme datapoints. When
set to 0, truncate the curve at the data limits.
clip : pair of numbers None, or a pair of such pairs
Do not evaluate the density outside of these limits.
cumulative : bool, optional
If True, estimate a cumulative distribution function.
"""
...
def define_support(self, x1, x2=..., weights=..., cache=...): # -> NDArray[floating[Any]] | tuple[NDArray[floating[Any]], NDArray[floating[Any]]]:
"""Create the evaluation grid for a given data set."""
...
def __call__(self, x1, x2=..., weights=...): # -> tuple[NDArray[Unknown] | Unknown, NDArray[floating[Any]] | tuple[NDArray[floating[Any]], NDArray[floating[Any]]]] | tuple[NDArray[float64] | Unknown, NDArray[floating[Any]] | tuple[NDArray[floating[Any]], NDArray[floating[Any]]]]:
"""Fit and evaluate on univariate or bivariate data."""
...
class Histogram:
"""Univariate and bivariate histogram estimator."""
def __init__(self, stat=..., bins=..., binwidth=..., binrange=..., discrete=..., cumulative=...) -> None:
"""Initialize the estimator with its parameters.
Parameters
----------
stat : {"count", "frequency", "density", "probability"}
Aggregate statistic to compute in each bin.
- ``count`` shows the number of observations
- ``frequency`` shows the number of observations divided by the bin width
- ``density`` normalizes counts so that the area of the histogram is 1
- ``probability`` normalizes counts so that the sum of the bar heights is 1
bins : str, number, vector, or a pair of such values
Generic bin parameter that can be the name of a reference rule,
the number of bins, or the breaks of the bins.
Passed to :func:`numpy.histogram_bin_edges`.
binwidth : number or pair of numbers
Width of each bin, overrides ``bins`` but can be used with
``binrange``.
binrange : pair of numbers or a pair of pairs
Lowest and highest value for bin edges; can be used either
with ``bins`` or ``binwidth``. Defaults to data extremes.
discrete : bool or pair of bools
If True, set ``binwidth`` and ``binrange`` such that bin
edges cover integer values in the dataset.
cumulative : bool
If True, return the cumulative statistic.
"""
...
def define_bin_edges(self, x1, x2=..., weights=..., cache=...): # -> NDArray[Any] | tuple[Unknown, ...]:
"""Given data, return the edges of the histogram bins."""
...
def __call__(self, x1, x2=..., weights=...): # -> tuple[Any | ndarray[Any, Any] | NDArray[float64] | NDArray[Any], Unknown | NDArray[Any] | tuple[Unknown, ...]] | tuple[Unknown, Unknown | NDArray[Any] | tuple[Unknown, ...]]:
"""Count the occurrances in each bin, maybe normalize."""
...
class ECDF:
"""Univariate empirical cumulative distribution estimator."""
def __init__(self, stat=..., complementary=...) -> None:
"""Initialize the class with its paramters
Parameters
----------
stat : {{"proportion", "count"}}
Distribution statistic to compute.
complementary : bool
If True, use the complementary CDF (1 - CDF)
"""
...
def __call__(self, x1, x2=..., weights=...): # -> tuple[Any, Any]:
"""Return proportion or count of observations below each sorted datapoint."""
...

View file

@ -0,0 +1,16 @@
"""
This type stub file was generated by pyright.
"""
LINE_PROPS = ...
COLLECTION_PROPS = ...
BAR_PROPS = ...
def assert_artists_equal(list1, list2, properties): # -> None:
...
def assert_legends_equal(leg1, leg2): # -> None:
...
def assert_plots_equal(ax1, ax2, labels=...): # -> None:
...

View file

@ -0,0 +1,35 @@
"""
This type stub file was generated by pyright.
"""
"""Algorithms to support fitting routines in seaborn plotting functions."""
def bootstrap(*args, **kwargs): # -> NDArray[Unknown]:
"""Resample one or more arrays with replacement and store aggregate values.
Positional arguments are a sequence of arrays to bootstrap along the first
axis and pass to a summary function.
Keyword arguments:
n_boot : int, default 10000
Number of iterations
axis : int, default None
Will pass axis to ``func`` as a keyword argument.
units : array, default None
Array of sampling unit IDs. When used the bootstrap resamples units
and then observations within units instead of individual
datapoints.
func : string or callable, default np.mean
Function to call on the args that are passed in. If string, tries
to use as named method on numpy array.
seed : Generator | SeedSequence | RandomState | int | None
Seed for the random number generator; useful if you want
reproducible resamples.
Returns
-------
boot_dist: array
array of bootstrapped statistic values
"""
...

View file

@ -0,0 +1,548 @@
"""
This type stub file was generated by pyright.
"""
from ._decorators import _deprecate_positional_args
__all__ = ["FacetGrid", "PairGrid", "JointGrid", "pairplot", "jointplot"]
_param_docs = ...
class Grid:
"""Base class for grids of subplots."""
_margin_titles = ...
_legend_out = ...
def __init__(self) -> None:
...
def set(self, **kwargs): # -> Self@Grid:
"""Set attributes on each subplot Axes."""
...
def savefig(self, *args, **kwargs): # -> None:
"""Save the figure."""
...
def tight_layout(self, *args, **kwargs): # -> None:
"""Call fig.tight_layout within rect that exclude the legend."""
...
def add_legend(self, legend_data=..., title=..., label_order=..., adjust_subtitles=..., **kwargs): # -> Self@Grid:
"""Draw a legend, maybe placing it outside axes and resizing the figure.
Parameters
----------
legend_data : dict
Dictionary mapping label names (or two-element tuples where the
second element is a label name) to matplotlib artist handles. The
default reads from ``self._legend_data``.
title : string
Title for the legend. The default reads from ``self._hue_var``.
label_order : list of labels
The order that the legend entries should appear in. The default
reads from ``self.hue_names``.
adjust_subtitles : bool
If True, modify entries with invisible artists to left-align
the labels and set the font size to that of a title.
kwargs : key, value pairings
Other keyword arguments are passed to the underlying legend methods
on the Figure or Axes object.
Returns
-------
self : Grid instance
Returns self for easy chaining.
"""
...
@property
def legend(self): # -> None:
"""The :class:`matplotlib.legend.Legend` object, if present."""
...
_facet_docs = ...
class FacetGrid(Grid):
"""Multi-plot grid for plotting conditional relationships."""
@_deprecate_positional_args
def __init__(self, data, *, row=..., col=..., hue=..., col_wrap=..., sharex=..., sharey=..., height=..., aspect=..., palette=..., row_order=..., col_order=..., hue_order=..., hue_kws=..., dropna=..., legend_out=..., despine=..., margin_titles=..., xlim=..., ylim=..., subplot_kws=..., gridspec_kws=..., size=...) -> None:
...
def facet_data(self): # -> Generator[tuple[tuple[int, int, int], Unknown], Any, None]:
"""Generator for name indices and data subsets for each facet.
Yields
------
(i, j, k), data_ijk : tuple of ints, DataFrame
The ints provide an index into the {row, col, hue}_names attribute,
and the dataframe contains a subset of the full data corresponding
to each facet. The generator yields subsets that correspond with
the self.axes.flat iterator, or self.axes[i, j] when `col_wrap`
is None.
"""
...
def map(self, func, *args, **kwargs): # -> Self@FacetGrid:
"""Apply a plotting function to each facet's subset of the data.
Parameters
----------
func : callable
A plotting function that takes data and keyword arguments. It
must plot to the currently active matplotlib Axes and take a
`color` keyword argument. If faceting on the `hue` dimension,
it must also take a `label` keyword argument.
args : strings
Column names in self.data that identify variables with data to
plot. The data for each variable is passed to `func` in the
order the variables are specified in the call.
kwargs : keyword arguments
All keyword arguments are passed to the plotting function.
Returns
-------
self : object
Returns self.
"""
...
def map_dataframe(self, func, *args, **kwargs): # -> Self@FacetGrid:
"""Like ``.map`` but passes args as strings and inserts data in kwargs.
This method is suitable for plotting with functions that accept a
long-form DataFrame as a `data` keyword argument and access the
data in that DataFrame using string variable names.
Parameters
----------
func : callable
A plotting function that takes data and keyword arguments. Unlike
the `map` method, a function used here must "understand" Pandas
objects. It also must plot to the currently active matplotlib Axes
and take a `color` keyword argument. If faceting on the `hue`
dimension, it must also take a `label` keyword argument.
args : strings
Column names in self.data that identify variables with data to
plot. The data for each variable is passed to `func` in the
order the variables are specified in the call.
kwargs : keyword arguments
All keyword arguments are passed to the plotting function.
Returns
-------
self : object
Returns self.
"""
...
def facet_axis(self, row_i, col_j, modify_state=...): # -> Any | ndarray[Any, dtype[Any]]:
"""Make the axis identified by these indices active and return it."""
...
def despine(self, **kwargs): # -> Self@FacetGrid:
"""Remove axis spines from the facets."""
...
def set_axis_labels(self, x_var=..., y_var=..., clear_inner=..., **kwargs): # -> Self@FacetGrid:
"""Set axis labels on the left column and bottom row of the grid."""
...
def set_xlabels(self, label=..., clear_inner=..., **kwargs): # -> Self@FacetGrid:
"""Label the x axis on the bottom row of the grid."""
...
def set_ylabels(self, label=..., clear_inner=..., **kwargs): # -> Self@FacetGrid:
"""Label the y axis on the left column of the grid."""
...
def set_xticklabels(self, labels=..., step=..., **kwargs): # -> Self@FacetGrid:
"""Set x axis tick labels of the grid."""
...
def set_yticklabels(self, labels=..., **kwargs): # -> Self@FacetGrid:
"""Set y axis tick labels on the left column of the grid."""
...
def set_titles(self, template=..., row_template=..., col_template=..., **kwargs): # -> Self@FacetGrid:
"""Draw titles either above each facet or on the grid margins.
Parameters
----------
template : string
Template for all titles with the formatting keys {col_var} and
{col_name} (if using a `col` faceting variable) and/or {row_var}
and {row_name} (if using a `row` faceting variable).
row_template:
Template for the row variable when titles are drawn on the grid
margins. Must have {row_var} and {row_name} formatting keys.
col_template:
Template for the row variable when titles are drawn on the grid
margins. Must have {col_var} and {col_name} formatting keys.
Returns
-------
self: object
Returns self.
"""
...
@property
def fig(self): # -> Figure:
"""The :class:`matplotlib.figure.Figure` with the plot."""
...
@property
def axes(self): # -> Any | NDArray[Any]:
"""An array of the :class:`matplotlib.axes.Axes` objects in the grid."""
...
@property
def ax(self): # -> Any:
"""The :class:`matplotlib.axes.Axes` when no faceting variables are assigned."""
...
@property
def axes_dict(self): # -> dict[Any, Any] | dict[tuple[Any, Any], Any]:
"""A mapping of facet names to corresponding :class:`matplotlib.axes.Axes`.
If only one of ``row`` or ``col`` is assigned, each key is a string
representing a level of that variable. If both facet dimensions are
assigned, each key is a ``({row_level}, {col_level})`` tuple.
"""
...
class PairGrid(Grid):
"""Subplot grid for plotting pairwise relationships in a dataset.
This object maps each variable in a dataset onto a column and row in a
grid of multiple axes. Different axes-level plotting functions can be
used to draw bivariate plots in the upper and lower triangles, and the
the marginal distribution of each variable can be shown on the diagonal.
Several different common plots can be generated in a single line using
:func:`pairplot`. Use :class:`PairGrid` when you need more flexibility.
See the :ref:`tutorial <grid_tutorial>` for more information.
"""
@_deprecate_positional_args
def __init__(self, data, *, hue=..., hue_order=..., palette=..., hue_kws=..., vars=..., x_vars=..., y_vars=..., corner=..., diag_sharey=..., height=..., aspect=..., layout_pad=..., despine=..., dropna=..., size=...) -> None:
"""Initialize the plot figure and PairGrid object.
Parameters
----------
data : DataFrame
Tidy (long-form) dataframe where each column is a variable and
each row is an observation.
hue : string (variable name)
Variable in ``data`` to map plot aspects to different colors. This
variable will be excluded from the default x and y variables.
hue_order : list of strings
Order for the levels of the hue variable in the palette
palette : dict or seaborn color palette
Set of colors for mapping the ``hue`` variable. If a dict, keys
should be values in the ``hue`` variable.
hue_kws : dictionary of param -> list of values mapping
Other keyword arguments to insert into the plotting call to let
other plot attributes vary across levels of the hue variable (e.g.
the markers in a scatterplot).
vars : list of variable names
Variables within ``data`` to use, otherwise use every column with
a numeric datatype.
{x, y}_vars : lists of variable names
Variables within ``data`` to use separately for the rows and
columns of the figure; i.e. to make a non-square plot.
corner : bool
If True, don't add axes to the upper (off-diagonal) triangle of the
grid, making this a "corner" plot.
height : scalar
Height (in inches) of each facet.
aspect : scalar
Aspect * height gives the width (in inches) of each facet.
layout_pad : scalar
Padding between axes; passed to ``fig.tight_layout``.
despine : boolean
Remove the top and right spines from the plots.
dropna : boolean
Drop missing values from the data before plotting.
See Also
--------
pairplot : Easily drawing common uses of :class:`PairGrid`.
FacetGrid : Subplot grid for plotting conditional relationships.
Examples
--------
.. include:: ../docstrings/PairGrid.rst
"""
...
def map(self, func, **kwargs): # -> Self@PairGrid:
"""Plot with the same function in every subplot.
Parameters
----------
func : callable plotting function
Must take x, y arrays as positional arguments and draw onto the
"currently active" matplotlib Axes. Also needs to accept kwargs
called ``color`` and ``label``.
"""
...
def map_lower(self, func, **kwargs): # -> Self@PairGrid:
"""Plot with a bivariate function on the lower diagonal subplots.
Parameters
----------
func : callable plotting function
Must take x, y arrays as positional arguments and draw onto the
"currently active" matplotlib Axes. Also needs to accept kwargs
called ``color`` and ``label``.
"""
...
def map_upper(self, func, **kwargs): # -> Self@PairGrid:
"""Plot with a bivariate function on the upper diagonal subplots.
Parameters
----------
func : callable plotting function
Must take x, y arrays as positional arguments and draw onto the
"currently active" matplotlib Axes. Also needs to accept kwargs
called ``color`` and ``label``.
"""
...
def map_offdiag(self, func, **kwargs): # -> Self@PairGrid:
"""Plot with a bivariate function on the off-diagonal subplots.
Parameters
----------
func : callable plotting function
Must take x, y arrays as positional arguments and draw onto the
"currently active" matplotlib Axes. Also needs to accept kwargs
called ``color`` and ``label``.
"""
...
def map_diag(self, func, **kwargs): # -> Self@PairGrid:
"""Plot with a univariate function on each diagonal subplot.
Parameters
----------
func : callable plotting function
Must take an x array as a positional argument and draw onto the
"currently active" matplotlib Axes. Also needs to accept kwargs
called ``color`` and ``label``.
"""
...
class JointGrid:
"""Grid for drawing a bivariate plot with marginal univariate plots.
Many plots can be drawn by using the figure-level interface :func:`jointplot`.
Use this class directly when you need more flexibility.
"""
@_deprecate_positional_args
def __init__(self, *, x=..., y=..., data=..., height=..., ratio=..., space=..., dropna=..., xlim=..., ylim=..., size=..., marginal_ticks=..., hue=..., palette=..., hue_order=..., hue_norm=...) -> None:
...
def plot(self, joint_func, marginal_func, **kwargs): # -> Self@JointGrid:
"""Draw the plot by passing functions for joint and marginal axes.
This method passes the ``kwargs`` dictionary to both functions. If you
need more control, call :meth:`JointGrid.plot_joint` and
:meth:`JointGrid.plot_marginals` directly with specific parameters.
Parameters
----------
joint_func, marginal_func: callables
Functions to draw the bivariate and univariate plots. See methods
referenced above for information about the required characteristics
of these functions.
kwargs
Additional keyword arguments are passed to both functions.
Returns
-------
:class:`JointGrid` instance
Returns ``self`` for easy method chaining.
"""
...
def plot_joint(self, func, **kwargs): # -> Self@JointGrid:
"""Draw a bivariate plot on the joint axes of the grid.
Parameters
----------
func : plotting callable
If a seaborn function, it should accept ``x`` and ``y``. Otherwise,
it must accept ``x`` and ``y`` vectors of data as the first two
positional arguments, and it must plot on the "current" axes.
If ``hue`` was defined in the class constructor, the function must
accept ``hue`` as a parameter.
kwargs
Keyword argument are passed to the plotting function.
Returns
-------
:class:`JointGrid` instance
Returns ``self`` for easy method chaining.
"""
...
def plot_marginals(self, func, **kwargs): # -> Self@JointGrid:
"""Draw univariate plots on each marginal axes.
Parameters
----------
func : plotting callable
If a seaborn function, it should accept ``x`` and ``y`` and plot
when only one of them is defined. Otherwise, it must accept a vector
of data as the first positional argument and determine its orientation
using the ``vertical`` parameter, and it must plot on the "current" axes.
If ``hue`` was defined in the class constructor, it must accept ``hue``
as a parameter.
kwargs
Keyword argument are passed to the plotting function.
Returns
-------
:class:`JointGrid` instance
Returns ``self`` for easy method chaining.
"""
...
def set_axis_labels(self, xlabel=..., ylabel=..., **kwargs): # -> Self@JointGrid:
"""Set axis labels on the bivariate axes.
Parameters
----------
xlabel, ylabel : strings
Label names for the x and y variables.
kwargs : key, value mappings
Other keyword arguments are passed to the following functions:
- :meth:`matplotlib.axes.Axes.set_xlabel`
- :meth:`matplotlib.axes.Axes.set_ylabel`
Returns
-------
:class:`JointGrid` instance
Returns ``self`` for easy method chaining.
"""
...
def savefig(self, *args, **kwargs): # -> None:
"""Save the figure using a "tight" bounding box by default.
Wraps :meth:`matplotlib.figure.Figure.savefig`.
"""
...
@_deprecate_positional_args
def pairplot(data, *, hue=..., hue_order=..., palette=..., vars=..., x_vars=..., y_vars=..., kind=..., diag_kind=..., markers=..., height=..., aspect=..., corner=..., dropna=..., plot_kws=..., diag_kws=..., grid_kws=..., size=...):
"""Plot pairwise relationships in a dataset.
By default, this function will create a grid of Axes such that each numeric
variable in ``data`` will by shared across the y-axes across a single row and
the x-axes across a single column. The diagonal plots are treated
differently: a univariate distribution plot is drawn to show the marginal
distribution of the data in each column.
It is also possible to show a subset of variables or plot different
variables on the rows and columns.
This is a high-level interface for :class:`PairGrid` that is intended to
make it easy to draw a few common styles. You should use :class:`PairGrid`
directly if you need more flexibility.
Parameters
----------
data : `pandas.DataFrame`
Tidy (long-form) dataframe where each column is a variable and
each row is an observation.
hue : name of variable in ``data``
Variable in ``data`` to map plot aspects to different colors.
hue_order : list of strings
Order for the levels of the hue variable in the palette
palette : dict or seaborn color palette
Set of colors for mapping the ``hue`` variable. If a dict, keys
should be values in the ``hue`` variable.
vars : list of variable names
Variables within ``data`` to use, otherwise use every column with
a numeric datatype.
{x, y}_vars : lists of variable names
Variables within ``data`` to use separately for the rows and
columns of the figure; i.e. to make a non-square plot.
kind : {'scatter', 'kde', 'hist', 'reg'}
Kind of plot to make.
diag_kind : {'auto', 'hist', 'kde', None}
Kind of plot for the diagonal subplots. If 'auto', choose based on
whether or not ``hue`` is used.
markers : single matplotlib marker code or list
Either the marker to use for all scatterplot points or a list of markers
with a length the same as the number of levels in the hue variable so that
differently colored points will also have different scatterplot
markers.
height : scalar
Height (in inches) of each facet.
aspect : scalar
Aspect * height gives the width (in inches) of each facet.
corner : bool
If True, don't add axes to the upper (off-diagonal) triangle of the
grid, making this a "corner" plot.
dropna : boolean
Drop missing values from the data before plotting.
{plot, diag, grid}_kws : dicts
Dictionaries of keyword arguments. ``plot_kws`` are passed to the
bivariate plotting function, ``diag_kws`` are passed to the univariate
plotting function, and ``grid_kws`` are passed to the :class:`PairGrid`
constructor.
Returns
-------
grid : :class:`PairGrid`
Returns the underlying :class:`PairGrid` instance for further tweaking.
See Also
--------
PairGrid : Subplot grid for more flexible plotting of pairwise relationships.
JointGrid : Grid for plotting joint and marginal distributions of two variables.
Examples
--------
.. include:: ../docstrings/pairplot.rst
"""
...
@_deprecate_positional_args
def jointplot(*, x=..., y=..., data=..., kind=..., color=..., height=..., ratio=..., space=..., dropna=..., xlim=..., ylim=..., marginal_ticks=..., joint_kws=..., marginal_kws=..., hue=..., palette=..., hue_order=..., hue_norm=..., **kwargs):
...

View file

@ -0,0 +1,312 @@
"""
This type stub file was generated by pyright.
"""
from ._decorators import _deprecate_positional_args
__all__ = ["catplot", "factorplot", "stripplot", "swarmplot", "boxplot", "violinplot", "boxenplot", "pointplot", "barplot", "countplot"]
class _CategoricalPlotter:
width = ...
default_palette = ...
require_numeric = ...
def establish_variables(self, x=..., y=..., hue=..., data=..., orient=..., order=..., hue_order=..., units=...):
"""Convert input specification into a common representation."""
...
def establish_colors(self, color, palette, saturation): # -> None:
"""Get a list of colors for the main component of the plots."""
...
@property
def hue_offsets(self): # -> Any | NDArray[float64]:
"""A list of center positions for plots when hue nesting is used."""
...
@property
def nested_width(self): # -> float:
"""A float with the width of plot elements when hue nesting is used."""
...
def annotate_axes(self, ax): # -> None:
"""Add descriptive labels to an Axes object."""
...
def add_legend_data(self, ax, color, label): # -> None:
"""Add a dummy patch object so we can get legend data."""
...
class _BoxPlotter(_CategoricalPlotter):
def __init__(self, x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, dodge, fliersize, linewidth) -> None:
...
def draw_boxplot(self, ax, kws): # -> None:
"""Use matplotlib to draw a boxplot on an Axes."""
...
def restyle_boxplot(self, artist_dict, color, props): # -> None:
"""Take a drawn matplotlib boxplot and make it look nice."""
...
def plot(self, ax, boxplot_kws): # -> None:
"""Make the plot."""
...
class _ViolinPlotter(_CategoricalPlotter):
def __init__(self, x, y, hue, data, order, hue_order, bw, cut, scale, scale_hue, gridsize, width, inner, split, dodge, orient, linewidth, color, palette, saturation) -> None:
...
def estimate_densities(self, bw, cut, scale, scale_hue, gridsize): # -> None:
"""Find the support and density for all of the data."""
...
def fit_kde(self, x, bw): # -> tuple[gaussian_kde, Unknown]:
"""Estimate a KDE for a vector of data with flexible bandwidth."""
...
def kde_support(self, x, bw, cut, gridsize):
"""Define a grid of support for the violin."""
...
def scale_area(self, density, max_density, scale_hue): # -> None:
"""Scale the relative area under the KDE curve.
This essentially preserves the "standard" KDE scaling, but the
resulting maximum density will be 1 so that the curve can be
properly multiplied by the violin width.
"""
...
def scale_width(self, density): # -> None:
"""Scale each density curve to the same height."""
...
def scale_count(self, density, counts, scale_hue): # -> None:
"""Scale each density curve by the number of observations."""
...
@property
def dwidth(self):
...
def draw_violins(self, ax): # -> None:
"""Draw the violins onto `ax`."""
...
def draw_single_observation(self, ax, at_group, at_quant, density): # -> None:
"""Draw a line to mark a single observation."""
...
def draw_box_lines(self, ax, data, support, density, center): # -> None:
"""Draw boxplot information at center of the density."""
...
def draw_quartiles(self, ax, data, support, density, center, split=...): # -> None:
"""Draw the quartiles as lines at width of density."""
...
def draw_points(self, ax, data, center): # -> None:
"""Draw individual observations as points at middle of the violin."""
...
def draw_stick_lines(self, ax, data, support, density, center, split=...): # -> None:
"""Draw individual observations as sticks at width of density."""
...
def draw_to_density(self, ax, center, val, support, density, split, **kws): # -> None:
"""Draw a line orthogonal to the value axis at width of density."""
...
def plot(self, ax): # -> None:
"""Make the violin plot."""
...
class _CategoricalScatterPlotter(_CategoricalPlotter):
default_palette = ...
require_numeric = ...
@property
def point_colors(self): # -> list[Unknown]:
"""Return an index into the palette for each scatter point."""
...
def add_legend_data(self, ax): # -> None:
"""Add empty scatterplot artists with labels for the legend."""
...
class _StripPlotter(_CategoricalScatterPlotter):
"""1-d scatterplot with categorical organization."""
def __init__(self, x, y, hue, data, order, hue_order, jitter, dodge, orient, color, palette) -> None:
"""Initialize the plotter."""
...
def draw_stripplot(self, ax, kws): # -> None:
"""Draw the points onto `ax`."""
...
def plot(self, ax, kws): # -> None:
"""Make the plot."""
...
class _SwarmPlotter(_CategoricalScatterPlotter):
def __init__(self, x, y, hue, data, order, hue_order, dodge, orient, color, palette) -> None:
"""Initialize the plotter."""
...
def could_overlap(self, xy_i, swarm, d): # -> NDArray[Unknown]:
"""Return a list of all swarm points that could overlap with target.
Assumes that swarm is a sorted list of all points below xy_i.
"""
...
def position_candidates(self, xy_i, neighbors, d): # -> NDArray[Unknown]:
"""Return a list of (x, y) coordinates that might be valid."""
...
def first_non_overlapping_candidate(self, candidates, neighbors, d):
"""Remove candidates from the list if they overlap with the swarm."""
...
def beeswarm(self, orig_xy, d): # -> NDArray[Unknown]:
"""Adjust x position of points to avoid overlaps."""
...
def add_gutters(self, points, center, width):
"""Stop points from extending beyond their territory."""
...
def swarm_points(self, ax, points, center, width, s, **kws): # -> None:
"""Find new positions on the categorical axis for each point."""
...
def draw_swarmplot(self, ax, kws): # -> None:
"""Plot the data."""
...
def plot(self, ax, kws): # -> None:
"""Make the full plot."""
...
class _CategoricalStatPlotter(_CategoricalPlotter):
require_numeric = ...
@property
def nested_width(self): # -> float:
"""A float with the width of plot elements when hue nesting is used."""
...
def estimate_statistic(self, estimator, ci, n_boot, seed): # -> None:
...
def draw_confints(self, ax, at_group, confint, colors, errwidth=..., capsize=..., **kws): # -> None:
...
class _BarPlotter(_CategoricalStatPlotter):
"""Show point estimates and confidence intervals with bars."""
def __init__(self, x, y, hue, data, order, hue_order, estimator, ci, n_boot, units, seed, orient, color, palette, saturation, errcolor, errwidth, capsize, dodge) -> None:
"""Initialize the plotter."""
...
def draw_bars(self, ax, kws): # -> None:
"""Draw the bars onto `ax`."""
...
def plot(self, ax, bar_kws): # -> None:
"""Make the plot."""
...
class _PointPlotter(_CategoricalStatPlotter):
default_palette = ...
def __init__(self, x, y, hue, data, order, hue_order, estimator, ci, n_boot, units, seed, markers, linestyles, dodge, join, scale, orient, color, palette, errwidth=..., capsize=...) -> None:
"""Initialize the plotter."""
...
@property
def hue_offsets(self): # -> NDArray[float64]:
"""Offsets relative to the center position for each hue level."""
...
def draw_points(self, ax): # -> None:
"""Draw the main data components of the plot."""
...
def plot(self, ax): # -> None:
"""Make the plot."""
...
class _CountPlotter(_BarPlotter):
require_numeric = ...
class _LVPlotter(_CategoricalPlotter):
def __init__(self, x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, dodge, k_depth, linewidth, scale, outlier_prop, trust_alpha, showfliers=...) -> None:
...
def draw_letter_value_plot(self, ax, kws): # -> None:
"""Use matplotlib to draw a letter value plot on an Axes."""
...
def plot(self, ax, boxplot_kws): # -> None:
"""Make the plot."""
...
_categorical_docs = ...
@_deprecate_positional_args
def boxplot(*, x=..., y=..., hue=..., data=..., order=..., hue_order=..., orient=..., color=..., palette=..., saturation=..., width=..., dodge=..., fliersize=..., linewidth=..., whis=..., ax=..., **kwargs): # -> Axes:
...
@_deprecate_positional_args
def violinplot(*, x=..., y=..., hue=..., data=..., order=..., hue_order=..., bw=..., cut=..., scale=..., scale_hue=..., gridsize=..., width=..., inner=..., split=..., dodge=..., orient=..., linewidth=..., color=..., palette=..., saturation=..., ax=..., **kwargs): # -> Axes:
...
@_deprecate_positional_args
def boxenplot(*, x=..., y=..., hue=..., data=..., order=..., hue_order=..., orient=..., color=..., palette=..., saturation=..., width=..., dodge=..., k_depth=..., linewidth=..., scale=..., outlier_prop=..., trust_alpha=..., showfliers=..., ax=..., **kwargs): # -> Axes:
...
@_deprecate_positional_args
def stripplot(*, x=..., y=..., hue=..., data=..., order=..., hue_order=..., jitter=..., dodge=..., orient=..., color=..., palette=..., size=..., edgecolor=..., linewidth=..., ax=..., **kwargs): # -> Axes:
...
@_deprecate_positional_args
def swarmplot(*, x=..., y=..., hue=..., data=..., order=..., hue_order=..., dodge=..., orient=..., color=..., palette=..., size=..., edgecolor=..., linewidth=..., ax=..., **kwargs): # -> Axes:
...
@_deprecate_positional_args
def barplot(*, x=..., y=..., hue=..., data=..., order=..., hue_order=..., estimator=..., ci=..., n_boot=..., units=..., seed=..., orient=..., color=..., palette=..., saturation=..., errcolor=..., errwidth=..., capsize=..., dodge=..., ax=..., **kwargs): # -> Axes:
...
@_deprecate_positional_args
def pointplot(*, x=..., y=..., hue=..., data=..., order=..., hue_order=..., estimator=..., ci=..., n_boot=..., units=..., seed=..., markers=..., linestyles=..., dodge=..., join=..., scale=..., orient=..., color=..., palette=..., errwidth=..., capsize=..., ax=..., **kwargs): # -> Axes:
...
@_deprecate_positional_args
def countplot(*, x=..., y=..., hue=..., data=..., order=..., hue_order=..., orient=..., color=..., palette=..., saturation=..., dodge=..., ax=..., **kwargs): # -> Axes:
...
def factorplot(*args, **kwargs):
"""Deprecated; please use `catplot` instead."""
...
@_deprecate_positional_args
def catplot(*, x=..., y=..., hue=..., data=..., row=..., col=..., col_wrap=..., estimator=..., ci=..., n_boot=..., units=..., seed=..., order=..., hue_order=..., row_order=..., col_order=..., kind=..., height=..., aspect=..., orient=..., color=..., palette=..., legend=..., legend_out=..., sharex=..., sharey=..., margin_titles=..., facet_kws=..., **kwargs):
...

11
typings/seaborn/cm.pyi Normal file
View file

@ -0,0 +1,11 @@
"""
This type stub file was generated by pyright.
"""
_rocket_lut = ...
_mako_lut = ...
_vlag_lut = ...
_icefire_lut = ...
_flare_lut = ...
_crest_lut = ...
_lut_dict = ...

View file

@ -0,0 +1,7 @@
"""
This type stub file was generated by pyright.
"""
from .xkcd_rgb import xkcd_rgb
from .crayons import crayons

View file

@ -0,0 +1,5 @@
"""
This type stub file was generated by pyright.
"""
crayons = ...

View file

@ -0,0 +1,5 @@
"""
This type stub file was generated by pyright.
"""
xkcd_rgb = ...

View file

@ -0,0 +1,98 @@
"""
This type stub file was generated by pyright.
"""
import pytest
def has_verdana(): # -> bool:
"""Helper to verify if Verdana font is present"""
...
@pytest.fixture(scope="session", autouse=True)
def remove_pandas_unit_conversion(): # -> None:
...
@pytest.fixture(autouse=True)
def close_figs(): # -> Generator[None, Any, None]:
...
@pytest.fixture(autouse=True)
def random_seed(): # -> None:
...
@pytest.fixture()
def rng(): # -> RandomState:
...
@pytest.fixture
def wide_df(rng): # -> DataFrame:
...
@pytest.fixture
def wide_array(wide_df): # -> NDArray[Unknown]:
...
@pytest.fixture
def flat_series(rng): # -> Series:
...
@pytest.fixture
def flat_array(flat_series): # -> NDArray[Unknown]:
...
@pytest.fixture
def flat_list(flat_series):
...
@pytest.fixture(params=["series", "array", "list"])
def flat_data(rng, request): # -> Series | ndarray[Unknown, Unknown] | NDArray[Unknown] | list[Unknown] | Any:
...
@pytest.fixture
def wide_list_of_series(rng): # -> list[Series]:
...
@pytest.fixture
def wide_list_of_arrays(wide_list_of_series): # -> list[NDArray[Unknown]]:
...
@pytest.fixture
def wide_list_of_lists(wide_list_of_series): # -> list[Unknown]:
...
@pytest.fixture
def wide_dict_of_series(wide_list_of_series): # -> dict[Unknown, Unknown]:
...
@pytest.fixture
def wide_dict_of_arrays(wide_list_of_series): # -> dict[Unknown, NDArray[Unknown]]:
...
@pytest.fixture
def wide_dict_of_lists(wide_list_of_series): # -> dict[Unknown, Unknown]:
...
@pytest.fixture
def long_df(rng): # -> DataFrame:
...
@pytest.fixture
def long_dict(long_df):
...
@pytest.fixture
def repeated_df(rng): # -> DataFrame:
...
@pytest.fixture
def missing_df(rng, long_df):
...
@pytest.fixture
def object_df(rng, long_df):
...
@pytest.fixture
def null_series(flat_series): # -> Series:
...

View file

@ -0,0 +1,209 @@
"""
This type stub file was generated by pyright.
"""
from ._core import VectorPlotter
from ._decorators import _deprecate_positional_args
"""Plotting functions for visualizing distributions."""
__all__ = ["displot", "histplot", "kdeplot", "ecdfplot", "rugplot", "distplot"]
_dist_params = ...
_param_docs = ...
class _DistributionPlotter(VectorPlotter):
semantics = ...
wide_structure = ...
flat_structure = ...
def __init__(self, data=..., variables=...) -> None:
...
@property
def univariate(self): # -> bool:
"""Return True if only x or y are used."""
...
@property
def data_variable(self): # -> str:
"""Return the variable with data for univariate plots."""
...
@property
def has_xy_data(self): # -> bool:
"""Return True at least one of x or y is defined."""
...
def plot_univariate_histogram(self, multiple, element, fill, common_norm, common_bins, shrink, kde, kde_kws, color, legend, line_kws, estimate_kws, **plot_kws):
...
def plot_bivariate_histogram(self, common_bins, common_norm, thresh, pthresh, pmax, color, legend, cbar, cbar_ax, cbar_kws, estimate_kws, **plot_kws):
...
def plot_univariate_density(self, multiple, common_norm, common_grid, fill, legend, estimate_kws, **plot_kws):
...
def plot_bivariate_density(self, common_norm, fill, levels, thresh, color, legend, cbar, cbar_ax, cbar_kws, estimate_kws, **contour_kws):
...
def plot_univariate_ecdf(self, estimate_kws, legend, **plot_kws): # -> None:
...
def plot_rug(self, height, expand_margins, legend, **kws): # -> None:
...
class _DistributionFacetPlotter(_DistributionPlotter):
semantics = ...
def histplot(data=..., *, x=..., y=..., hue=..., weights=..., stat=..., bins=..., binwidth=..., binrange=..., discrete=..., cumulative=..., common_bins=..., common_norm=..., multiple=..., element=..., fill=..., shrink=..., kde=..., kde_kws=..., line_kws=..., thresh=..., pthresh=..., pmax=..., cbar=..., cbar_ax=..., cbar_kws=..., palette=..., hue_order=..., hue_norm=..., color=..., log_scale=..., legend=..., ax=..., **kwargs): # -> Axes:
...
@_deprecate_positional_args
def kdeplot(x=..., *, y=..., shade=..., vertical=..., kernel=..., bw=..., gridsize=..., cut=..., clip=..., legend=..., cumulative=..., shade_lowest=..., cbar=..., cbar_ax=..., cbar_kws=..., ax=..., weights=..., hue=..., palette=..., hue_order=..., hue_norm=..., multiple=..., common_norm=..., common_grid=..., levels=..., thresh=..., bw_method=..., bw_adjust=..., log_scale=..., color=..., fill=..., data=..., data2=..., **kwargs): # -> Axes:
...
def ecdfplot(data=..., *, x=..., y=..., hue=..., weights=..., stat=..., complementary=..., palette=..., hue_order=..., hue_norm=..., log_scale=..., legend=..., ax=..., **kwargs): # -> Axes:
...
@_deprecate_positional_args
def rugplot(x=..., *, height=..., axis=..., ax=..., data=..., y=..., hue=..., palette=..., hue_order=..., hue_norm=..., expand_margins=..., legend=..., a=..., **kwargs): # -> Axes:
...
def displot(data=..., *, x=..., y=..., hue=..., row=..., col=..., weights=..., kind=..., rug=..., rug_kws=..., log_scale=..., legend=..., palette=..., hue_order=..., hue_norm=..., color=..., col_wrap=..., row_order=..., col_order=..., height=..., aspect=..., facet_kws=..., **kwargs): # -> FacetGrid:
...
def distplot(a=..., bins=..., hist=..., kde=..., rug=..., fit=..., hist_kws=..., kde_kws=..., rug_kws=..., fit_kws=..., color=..., vertical=..., norm_hist=..., axlabel=..., label=..., ax=..., x=...):
"""DEPRECATED: Flexibly plot a univariate distribution of observations.
.. warning::
This function is deprecated and will be removed in a future version.
Please adapt your code to use one of two new functions:
- :func:`displot`, a figure-level function with a similar flexibility
over the kind of plot to draw
- :func:`histplot`, an axes-level function for plotting histograms,
including with kernel density smoothing
This function combines the matplotlib ``hist`` function (with automatic
calculation of a good default bin size) with the seaborn :func:`kdeplot`
and :func:`rugplot` functions. It can also fit ``scipy.stats``
distributions and plot the estimated PDF over the data.
Parameters
----------
a : Series, 1d-array, or list.
Observed data. If this is a Series object with a ``name`` attribute,
the name will be used to label the data axis.
bins : argument for matplotlib hist(), or None, optional
Specification of hist bins. If unspecified, as reference rule is used
that tries to find a useful default.
hist : bool, optional
Whether to plot a (normed) histogram.
kde : bool, optional
Whether to plot a gaussian kernel density estimate.
rug : bool, optional
Whether to draw a rugplot on the support axis.
fit : random variable object, optional
An object with `fit` method, returning a tuple that can be passed to a
`pdf` method a positional arguments following a grid of values to
evaluate the pdf on.
hist_kws : dict, optional
Keyword arguments for :meth:`matplotlib.axes.Axes.hist`.
kde_kws : dict, optional
Keyword arguments for :func:`kdeplot`.
rug_kws : dict, optional
Keyword arguments for :func:`rugplot`.
color : matplotlib color, optional
Color to plot everything but the fitted curve in.
vertical : bool, optional
If True, observed values are on y-axis.
norm_hist : bool, optional
If True, the histogram height shows a density rather than a count.
This is implied if a KDE or fitted density is plotted.
axlabel : string, False, or None, optional
Name for the support axis label. If None, will try to get it
from a.name if False, do not set a label.
label : string, optional
Legend label for the relevant component of the plot.
ax : matplotlib axis, optional
If provided, plot on this axis.
Returns
-------
ax : matplotlib Axes
Returns the Axes object with the plot for further tweaking.
See Also
--------
kdeplot : Show a univariate or bivariate distribution with a kernel
density estimate.
rugplot : Draw small vertical lines to show each observation in a
distribution.
Examples
--------
Show a default plot with a kernel density estimate and histogram with bin
size determined automatically with a reference rule:
.. plot::
:context: close-figs
>>> import seaborn as sns, numpy as np
>>> sns.set_theme(); np.random.seed(0)
>>> x = np.random.randn(100)
>>> ax = sns.distplot(x)
Use Pandas objects to get an informative axis label:
.. plot::
:context: close-figs
>>> import pandas as pd
>>> x = pd.Series(x, name="x variable")
>>> ax = sns.distplot(x)
Plot the distribution with a kernel density estimate and rug plot:
.. plot::
:context: close-figs
>>> ax = sns.distplot(x, rug=True, hist=False)
Plot the distribution with a histogram and maximum likelihood gaussian
distribution fit:
.. plot::
:context: close-figs
>>> from scipy.stats import norm
>>> ax = sns.distplot(x, fit=norm, kde=False)
Plot the distribution on the vertical axis:
.. plot::
:context: close-figs
>>> ax = sns.distplot(x, vertical=True)
Change the color of all the plot elements:
.. plot::
:context: close-figs
>>> sns.set_color_codes()
>>> ax = sns.distplot(x, color="y")
Pass specific parameters to the underlying plot functions:
.. plot::
:context: close-figs
>>> ax = sns.distplot(x, rug=True, rug_kws={"color": "g"},
... kde_kws={"color": "k", "lw": 3, "label": "KDE"},
... hist_kws={"histtype": "step", "linewidth": 3,
... "alpha": 1, "color": "g"})
"""
...

4
typings/seaborn/external/__init__.pyi vendored Normal file
View file

@ -0,0 +1,4 @@
"""
This type stub file was generated by pyright.
"""

165
typings/seaborn/external/docscrape.pyi vendored Normal file
View file

@ -0,0 +1,165 @@
"""
This type stub file was generated by pyright.
"""
from collections.abc import Mapping
"""Extract reference documentation from the NumPy source tree.
Copyright (C) 2008 Stefan van der Walt <stefan@mentat.za.net>, Pauli Virtanen <pav@iki.fi>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
def strip_blank_lines(l):
"Remove leading and trailing blank lines from a list of lines"
...
class Reader:
"""A line-based string reader.
"""
def __init__(self, data) -> None:
"""
Parameters
----------
data : str
String with lines separated by '\n'.
"""
...
def __getitem__(self, n):
...
def reset(self): # -> None:
...
def read(self): # -> Literal['']:
...
def seek_next_non_empty_line(self): # -> None:
...
def eof(self): # -> bool:
...
def read_to_condition(self, condition_func): # -> list[Unknown]:
...
def read_to_next_empty_line(self): # -> list[Unknown]:
...
def read_to_next_unindented_line(self): # -> list[Unknown]:
...
def peek(self, n=...): # -> Literal['']:
...
def is_empty(self): # -> bool:
...
class ParseError(Exception):
def __str__(self) -> str:
...
Parameter = ...
class NumpyDocString(Mapping):
"""Parses a numpydoc string to an abstract representation
Instances define a mapping from section title to structured data.
"""
sections = ...
def __init__(self, docstring, config=...) -> None:
...
def __getitem__(self, key):
...
def __setitem__(self, key, val): # -> None:
...
def __iter__(self): # -> Iterator[str]:
...
def __len__(self): # -> int:
...
_role = ...
_funcbacktick = ...
_funcplain = ...
_funcname = ...
_funcnamenext = ...
_funcnamenext = ...
_description = ...
_func_rgx = ...
_line_rgx = ...
empty_description = ...
def __str__(self, func_role=...) -> str:
...
def indent(str, indent=...): # -> LiteralString:
...
def dedent_lines(lines): # -> list[str]:
"""Deindent a list of lines maximally"""
...
def header(text, style=...):
...
class FunctionDoc(NumpyDocString):
def __init__(self, func, role=..., doc=..., config=...) -> None:
...
def get_func(self): # -> tuple[Any | Overload[(__o: object, /) -> None, (__name: str, __bases: tuple[type, ...], __dict: dict[str, Any], **kwds: Any) -> None] | Unknown, Any | str]:
...
def __str__(self) -> str:
...
class ClassDoc(NumpyDocString):
extra_public_methods = ...
def __init__(self, cls, doc=..., modulename=..., func_doc=..., config=...) -> None:
...
@property
def methods(self): # -> list[Unknown] | list[str]:
...
@property
def properties(self): # -> list[Unknown] | list[str]:
...

104
typings/seaborn/external/husl.pyi vendored Normal file
View file

@ -0,0 +1,104 @@
"""
This type stub file was generated by pyright.
"""
__version__ = ...
m = ...
m_inv = ...
refX = ...
refY = ...
refZ = ...
refU = ...
refV = ...
lab_e = ...
lab_k = ...
def husl_to_rgb(h, s, l): # -> list[Unknown | float]:
...
def husl_to_hex(h, s, l): # -> LiteralString:
...
def rgb_to_husl(r, g, b): # -> list[Unknown]:
...
def hex_to_husl(hex): # -> list[Unknown]:
...
def huslp_to_rgb(h, s, l): # -> list[Unknown | float]:
...
def huslp_to_hex(h, s, l): # -> LiteralString:
...
def rgb_to_huslp(r, g, b): # -> list[Unknown]:
...
def hex_to_huslp(hex): # -> list[Unknown]:
...
def lch_to_rgb(l, c, h): # -> list[Unknown | float]:
...
def rgb_to_lch(r, g, b): # -> list[Unknown]:
...
def max_chroma(L, H): # -> float:
...
def max_chroma_pastel(L): # -> float:
...
def dot_product(a, b): # -> int:
...
def f(t): # -> float:
...
def f_inv(t): # -> float:
...
def from_linear(c): # -> float:
...
def to_linear(c): # -> float:
...
def rgb_prepare(triple): # -> list[Unknown]:
...
def hex_to_rgb(hex): # -> list[float]:
...
def rgb_to_hex(triple): # -> LiteralString:
...
def xyz_to_rgb(triple): # -> list[Unknown | float]:
...
def rgb_to_xyz(triple): # -> list[int]:
...
def xyz_to_luv(triple): # -> list[float] | list[Unknown]:
...
def luv_to_xyz(triple): # -> list[float] | list[Unknown]:
...
def luv_to_lch(triple): # -> list[Unknown]:
...
def lch_to_luv(triple): # -> list[Unknown]:
...
def husl_to_lch(triple): # -> list[Unknown]:
...
def lch_to_husl(triple): # -> list[Unknown]:
...
def huslp_to_lch(triple): # -> list[Unknown]:
...
def lch_to_huslp(triple): # -> list[Unknown]:
...

557
typings/seaborn/matrix.pyi Normal file
View file

@ -0,0 +1,557 @@
"""
This type stub file was generated by pyright.
"""
from .axisgrid import Grid
from ._decorators import _deprecate_positional_args
"""Functions to visualize matrices of data."""
__all__ = ["heatmap", "clustermap"]
class _HeatMapper:
"""Draw a heatmap plot of a matrix with nice labels and colormaps."""
def __init__(self, data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, cbar, cbar_kws, xticklabels=..., yticklabels=..., mask=...) -> None:
"""Initialize the plotting object."""
...
def plot(self, ax, cax, kws): # -> None:
"""Draw the heatmap on the provided Axes."""
...
@_deprecate_positional_args
def heatmap(data, *, vmin=..., vmax=..., cmap=..., center=..., robust=..., annot=..., fmt=..., annot_kws=..., linewidths=..., linecolor=..., cbar=..., cbar_kws=..., cbar_ax=..., square=..., xticklabels=..., yticklabels=..., mask=..., ax=..., **kwargs): # -> Axes:
"""Plot rectangular data as a color-encoded matrix.
This is an Axes-level function and will draw the heatmap into the
currently-active Axes if none is provided to the ``ax`` argument. Part of
this Axes space will be taken and used to plot a colormap, unless ``cbar``
is False or a separate Axes is provided to ``cbar_ax``.
Parameters
----------
data : rectangular dataset
2D dataset that can be coerced into an ndarray. If a Pandas DataFrame
is provided, the index/column information will be used to label the
columns and rows.
vmin, vmax : floats, optional
Values to anchor the colormap, otherwise they are inferred from the
data and other keyword arguments.
cmap : matplotlib colormap name or object, or list of colors, optional
The mapping from data values to color space. If not provided, the
default will depend on whether ``center`` is set.
center : float, optional
The value at which to center the colormap when plotting divergant data.
Using this parameter will change the default ``cmap`` if none is
specified.
robust : bool, optional
If True and ``vmin`` or ``vmax`` are absent, the colormap range is
computed with robust quantiles instead of the extreme values.
annot : bool or rectangular dataset, optional
If True, write the data value in each cell. If an array-like with the
same shape as ``data``, then use this to annotate the heatmap instead
of the data. Note that DataFrames will match on position, not index.
fmt : str, optional
String formatting code to use when adding annotations.
annot_kws : dict of key, value mappings, optional
Keyword arguments for :meth:`matplotlib.axes.Axes.text` when ``annot``
is True.
linewidths : float, optional
Width of the lines that will divide each cell.
linecolor : color, optional
Color of the lines that will divide each cell.
cbar : bool, optional
Whether to draw a colorbar.
cbar_kws : dict of key, value mappings, optional
Keyword arguments for :meth:`matplotlib.figure.Figure.colorbar`.
cbar_ax : matplotlib Axes, optional
Axes in which to draw the colorbar, otherwise take space from the
main Axes.
square : bool, optional
If True, set the Axes aspect to "equal" so each cell will be
square-shaped.
xticklabels, yticklabels : "auto", bool, list-like, or int, optional
If True, plot the column names of the dataframe. If False, don't plot
the column names. If list-like, plot these alternate labels as the
xticklabels. If an integer, use the column names but plot only every
n label. If "auto", try to densely plot non-overlapping labels.
mask : bool array or DataFrame, optional
If passed, data will not be shown in cells where ``mask`` is True.
Cells with missing values are automatically masked.
ax : matplotlib Axes, optional
Axes in which to draw the plot, otherwise use the currently-active
Axes.
kwargs : other keyword arguments
All other keyword arguments are passed to
:meth:`matplotlib.axes.Axes.pcolormesh`.
Returns
-------
ax : matplotlib Axes
Axes object with the heatmap.
See Also
--------
clustermap : Plot a matrix using hierachical clustering to arrange the
rows and columns.
Examples
--------
Plot a heatmap for a numpy array:
.. plot::
:context: close-figs
>>> import numpy as np; np.random.seed(0)
>>> import seaborn as sns; sns.set_theme()
>>> uniform_data = np.random.rand(10, 12)
>>> ax = sns.heatmap(uniform_data)
Change the limits of the colormap:
.. plot::
:context: close-figs
>>> ax = sns.heatmap(uniform_data, vmin=0, vmax=1)
Plot a heatmap for data centered on 0 with a diverging colormap:
.. plot::
:context: close-figs
>>> normal_data = np.random.randn(10, 12)
>>> ax = sns.heatmap(normal_data, center=0)
Plot a dataframe with meaningful row and column labels:
.. plot::
:context: close-figs
>>> flights = sns.load_dataset("flights")
>>> flights = flights.pivot("month", "year", "passengers")
>>> ax = sns.heatmap(flights)
Annotate each cell with the numeric value using integer formatting:
.. plot::
:context: close-figs
>>> ax = sns.heatmap(flights, annot=True, fmt="d")
Add lines between each cell:
.. plot::
:context: close-figs
>>> ax = sns.heatmap(flights, linewidths=.5)
Use a different colormap:
.. plot::
:context: close-figs
>>> ax = sns.heatmap(flights, cmap="YlGnBu")
Center the colormap at a specific value:
.. plot::
:context: close-figs
>>> ax = sns.heatmap(flights, center=flights.loc["Jan", 1955])
Plot every other column label and don't plot row labels:
.. plot::
:context: close-figs
>>> data = np.random.randn(50, 20)
>>> ax = sns.heatmap(data, xticklabels=2, yticklabels=False)
Don't draw a colorbar:
.. plot::
:context: close-figs
>>> ax = sns.heatmap(flights, cbar=False)
Use different axes for the colorbar:
.. plot::
:context: close-figs
>>> grid_kws = {"height_ratios": (.9, .05), "hspace": .3}
>>> f, (ax, cbar_ax) = plt.subplots(2, gridspec_kw=grid_kws)
>>> ax = sns.heatmap(flights, ax=ax,
... cbar_ax=cbar_ax,
... cbar_kws={"orientation": "horizontal"})
Use a mask to plot only part of a matrix
.. plot::
:context: close-figs
>>> corr = np.corrcoef(np.random.randn(10, 200))
>>> mask = np.zeros_like(corr)
>>> mask[np.triu_indices_from(mask)] = True
>>> with sns.axes_style("white"):
... f, ax = plt.subplots(figsize=(7, 5))
... ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True)
"""
...
class _DendrogramPlotter:
"""Object for drawing tree of similarities between data rows/columns"""
def __init__(self, data, linkage, metric, method, axis, label, rotate) -> None:
"""Plot a dendrogram of the relationships between the columns of data
Parameters
----------
data : pandas.DataFrame
Rectangular data
"""
...
@property
def calculated_linkage(self):
...
def calculate_dendrogram(self): # -> dict[str, Unknown]:
"""Calculates a dendrogram based on the linkage matrix
Made a separate function, not a property because don't want to
recalculate the dendrogram every time it is accessed.
Returns
-------
dendrogram : dict
Dendrogram dictionary as returned by scipy.cluster.hierarchy
.dendrogram. The important key-value pairing is
"reordered_ind" which indicates the re-ordering of the matrix
"""
...
@property
def reordered_ind(self):
"""Indices of the matrix, reordered by the dendrogram"""
...
def plot(self, ax, tree_kws): # -> Self@_DendrogramPlotter:
"""Plots a dendrogram of the similarities between data on the axes
Parameters
----------
ax : matplotlib.axes.Axes
Axes object upon which the dendrogram is plotted
"""
...
@_deprecate_positional_args
def dendrogram(data, *, linkage=..., axis=..., label=..., metric=..., method=..., rotate=..., tree_kws=..., ax=...): # -> _DendrogramPlotter:
"""Draw a tree diagram of relationships within a matrix
Parameters
----------
data : pandas.DataFrame
Rectangular data
linkage : numpy.array, optional
Linkage matrix
axis : int, optional
Which axis to use to calculate linkage. 0 is rows, 1 is columns.
label : bool, optional
If True, label the dendrogram at leaves with column or row names
metric : str, optional
Distance metric. Anything valid for scipy.spatial.distance.pdist
method : str, optional
Linkage method to use. Anything valid for
scipy.cluster.hierarchy.linkage
rotate : bool, optional
When plotting the matrix, whether to rotate it 90 degrees
counter-clockwise, so the leaves face right
tree_kws : dict, optional
Keyword arguments for the ``matplotlib.collections.LineCollection``
that is used for plotting the lines of the dendrogram tree.
ax : matplotlib axis, optional
Axis to plot on, otherwise uses current axis
Returns
-------
dendrogramplotter : _DendrogramPlotter
A Dendrogram plotter object.
Notes
-----
Access the reordered dendrogram indices with
dendrogramplotter.reordered_ind
"""
...
class ClusterGrid(Grid):
def __init__(self, data, pivot_kws=..., z_score=..., standard_scale=..., figsize=..., row_colors=..., col_colors=..., mask=..., dendrogram_ratio=..., colors_ratio=..., cbar_pos=...) -> None:
"""Grid object for organizing clustered heatmap input on to axes"""
...
def format_data(self, data, pivot_kws, z_score=..., standard_scale=...):
"""Extract variables from data or use directly."""
...
@staticmethod
def z_score(data2d, axis=...):
"""Standarize the mean and variance of the data axis
Parameters
----------
data2d : pandas.DataFrame
Data to normalize
axis : int
Which axis to normalize across. If 0, normalize across rows, if 1,
normalize across columns.
Returns
-------
normalized : pandas.DataFrame
Noramlized data with a mean of 0 and variance of 1 across the
specified axis.
"""
...
@staticmethod
def standard_scale(data2d, axis=...):
"""Divide the data by the difference between the max and min
Parameters
----------
data2d : pandas.DataFrame
Data to normalize
axis : int
Which axis to normalize across. If 0, normalize across rows, if 1,
normalize across columns.
vmin : int
If 0, then subtract the minimum of the data before dividing by
the range.
Returns
-------
standardized : pandas.DataFrame
Noramlized data with a mean of 0 and variance of 1 across the
specified axis.
"""
...
def dim_ratios(self, colors, dendrogram_ratio, colors_ratio): # -> list[Unknown]:
"""Get the proportions of the figure taken up by each axes."""
...
@staticmethod
def color_list_to_matrix_and_cmap(colors, ind, axis=...): # -> tuple[ndarray[Any, dtype[Any]], Unknown]:
"""Turns a list of colors into a numpy matrix and matplotlib colormap
These arguments can now be plotted using heatmap(matrix, cmap)
and the provided colors will be plotted.
Parameters
----------
colors : list of matplotlib colors
Colors to label the rows or columns of a dataframe.
ind : list of ints
Ordering of the rows or columns, to reorder the original colors
by the clustered dendrogram order
axis : int
Which axis this is labeling
Returns
-------
matrix : numpy.array
A numpy array of integer values, where each corresponds to a color
from the originally provided list of colors
cmap : matplotlib.colors.ListedColormap
"""
...
def savefig(self, *args, **kwargs): # -> None:
...
def plot_dendrograms(self, row_cluster, col_cluster, metric, method, row_linkage, col_linkage, tree_kws): # -> None:
...
def plot_colors(self, xind, yind, **kws): # -> None:
"""Plots color labels between the dendrogram and the heatmap
Parameters
----------
heatmap_kws : dict
Keyword arguments heatmap
"""
...
def plot_matrix(self, colorbar_kws, xind, yind, **kws): # -> None:
...
def plot(self, metric, method, colorbar_kws, row_cluster, col_cluster, row_linkage, col_linkage, tree_kws, **kws): # -> Self@ClusterGrid:
...
@_deprecate_positional_args
def clustermap(data, *, pivot_kws=..., method=..., metric=..., z_score=..., standard_scale=..., figsize=..., cbar_kws=..., row_cluster=..., col_cluster=..., row_linkage=..., col_linkage=..., row_colors=..., col_colors=..., mask=..., dendrogram_ratio=..., colors_ratio=..., cbar_pos=..., tree_kws=..., **kwargs): # -> ClusterGrid:
"""
Plot a matrix dataset as a hierarchically-clustered heatmap.
Parameters
----------
data : 2D array-like
Rectangular data for clustering. Cannot contain NAs.
pivot_kws : dict, optional
If `data` is a tidy dataframe, can provide keyword arguments for
pivot to create a rectangular dataframe.
method : str, optional
Linkage method to use for calculating clusters. See
:func:`scipy.cluster.hierarchy.linkage` documentation for more
information.
metric : str, optional
Distance metric to use for the data. See
:func:`scipy.spatial.distance.pdist` documentation for more options.
To use different metrics (or methods) for rows and columns, you may
construct each linkage matrix yourself and provide them as
`{row,col}_linkage`.
z_score : int or None, optional
Either 0 (rows) or 1 (columns). Whether or not to calculate z-scores
for the rows or the columns. Z scores are: z = (x - mean)/std, so
values in each row (column) will get the mean of the row (column)
subtracted, then divided by the standard deviation of the row (column).
This ensures that each row (column) has mean of 0 and variance of 1.
standard_scale : int or None, optional
Either 0 (rows) or 1 (columns). Whether or not to standardize that
dimension, meaning for each row or column, subtract the minimum and
divide each by its maximum.
figsize : tuple of (width, height), optional
Overall size of the figure.
cbar_kws : dict, optional
Keyword arguments to pass to `cbar_kws` in :func:`heatmap`, e.g. to
add a label to the colorbar.
{row,col}_cluster : bool, optional
If ``True``, cluster the {rows, columns}.
{row,col}_linkage : :class:`numpy.ndarray`, optional
Precomputed linkage matrix for the rows or columns. See
:func:`scipy.cluster.hierarchy.linkage` for specific formats.
{row,col}_colors : list-like or pandas DataFrame/Series, optional
List of colors to label for either the rows or columns. Useful to evaluate
whether samples within a group are clustered together. Can use nested lists or
DataFrame for multiple color levels of labeling. If given as a
:class:`pandas.DataFrame` or :class:`pandas.Series`, labels for the colors are
extracted from the DataFrames column names or from the name of the Series.
DataFrame/Series colors are also matched to the data by their index, ensuring
colors are drawn in the correct order.
mask : bool array or DataFrame, optional
If passed, data will not be shown in cells where `mask` is True.
Cells with missing values are automatically masked. Only used for
visualizing, not for calculating.
{dendrogram,colors}_ratio : float, or pair of floats, optional
Proportion of the figure size devoted to the two marginal elements. If
a pair is given, they correspond to (row, col) ratios.
cbar_pos : tuple of (left, bottom, width, height), optional
Position of the colorbar axes in the figure. Setting to ``None`` will
disable the colorbar.
tree_kws : dict, optional
Parameters for the :class:`matplotlib.collections.LineCollection`
that is used to plot the lines of the dendrogram tree.
kwargs : other keyword arguments
All other keyword arguments are passed to :func:`heatmap`.
Returns
-------
:class:`ClusterGrid`
A :class:`ClusterGrid` instance.
See Also
--------
heatmap : Plot rectangular data as a color-encoded matrix.
Notes
-----
The returned object has a ``savefig`` method that should be used if you
want to save the figure object without clipping the dendrograms.
To access the reordered row indices, use:
``clustergrid.dendrogram_row.reordered_ind``
Column indices, use:
``clustergrid.dendrogram_col.reordered_ind``
Examples
--------
Plot a clustered heatmap:
.. plot::
:context: close-figs
>>> import seaborn as sns; sns.set_theme(color_codes=True)
>>> iris = sns.load_dataset("iris")
>>> species = iris.pop("species")
>>> g = sns.clustermap(iris)
Change the size and layout of the figure:
.. plot::
:context: close-figs
>>> g = sns.clustermap(iris,
... figsize=(7, 5),
... row_cluster=False,
... dendrogram_ratio=(.1, .2),
... cbar_pos=(0, .2, .03, .4))
Add colored labels to identify observations:
.. plot::
:context: close-figs
>>> lut = dict(zip(species.unique(), "rbg"))
>>> row_colors = species.map(lut)
>>> g = sns.clustermap(iris, row_colors=row_colors)
Use a different colormap and adjust the limits of the color range:
.. plot::
:context: close-figs
>>> g = sns.clustermap(iris, cmap="mako", vmin=0, vmax=10)
Use a different similarity metric:
.. plot::
:context: close-figs
>>> g = sns.clustermap(iris, metric="correlation")
Use a different clustering method:
.. plot::
:context: close-figs
>>> g = sns.clustermap(iris, method="single")
Standardize the data within the columns:
.. plot::
:context: close-figs
>>> g = sns.clustermap(iris, standard_scale=1)
Normalize the data within the rows:
.. plot::
:context: close-figs
>>> g = sns.clustermap(iris, z_score=0, cmap="vlag")
"""
...

View file

@ -0,0 +1,22 @@
"""
This type stub file was generated by pyright.
"""
__all__ = ["palplot", "dogplot"]
def palplot(pal, size=...): # -> None:
"""Plot the values in a color palette as a horizontal array.
Parameters
----------
pal : sequence of matplotlib colors
colors, i.e. as returned by seaborn.color_palette()
size :
scaling factor for size of plot
"""
...
def dogplot(*_, **__): # -> None:
"""Who's a good boy?"""
...

View file

@ -0,0 +1,706 @@
"""
This type stub file was generated by pyright.
"""
__all__ = ["color_palette", "hls_palette", "husl_palette", "mpl_palette", "dark_palette", "light_palette", "diverging_palette", "blend_palette", "xkcd_palette", "crayon_palette", "cubehelix_palette", "set_color_codes"]
SEABORN_PALETTES = ...
MPL_QUAL_PALS = ...
QUAL_PALETTE_SIZES = ...
QUAL_PALETTES = ...
class _ColorPalette(list):
"""Set the color palette in a with statement, otherwise be a list."""
def __enter__(self): # -> Self@_ColorPalette:
"""Open the context."""
...
def __exit__(self, *args): # -> None:
"""Close the context."""
...
def as_hex(self): # -> _ColorPalette:
"""Return a color palette with hex codes instead of RGB values."""
...
def color_palette(palette=..., n_colors=..., desat=..., as_cmap=...): # -> _ColorPalette | list[tuple[float, float, float]] | Any | list[str]:
"""Return a list of colors or continuous colormap defining a palette.
Possible ``palette`` values include:
- Name of a seaborn palette (deep, muted, bright, pastel, dark, colorblind)
- Name of matplotlib colormap
- 'husl' or 'hls'
- 'ch:<cubehelix arguments>'
- 'light:<color>', 'dark:<color>', 'blend:<color>,<color>',
- A sequence of colors in any format matplotlib accepts
Calling this function with ``palette=None`` will return the current
matplotlib color cycle.
This function can also be used in a ``with`` statement to temporarily
set the color cycle for a plot or set of plots.
See the :ref:`tutorial <palette_tutorial>` for more information.
Parameters
----------
palette: None, string, or sequence, optional
Name of palette or None to return current palette. If a sequence, input
colors are used but possibly cycled and desaturated.
n_colors : int, optional
Number of colors in the palette. If ``None``, the default will depend
on how ``palette`` is specified. Named palettes default to 6 colors,
but grabbing the current palette or passing in a list of colors will
not change the number of colors unless this is specified. Asking for
more colors than exist in the palette will cause it to cycle. Ignored
when ``as_cmap`` is True.
desat : float, optional
Proportion to desaturate each color by.
as_cmap : bool
If True, return a :class:`matplotlib.colors.Colormap`.
Returns
-------
list of RGB tuples or :class:`matplotlib.colors.Colormap`
See Also
--------
set_palette : Set the default color cycle for all plots.
set_color_codes : Reassign color codes like ``"b"``, ``"g"``, etc. to
colors from one of the seaborn palettes.
Examples
--------
.. include:: ../docstrings/color_palette.rst
"""
...
def hls_palette(n_colors=..., h=..., l=..., s=..., as_cmap=...): # -> _ColorPalette:
"""Get a set of evenly spaced colors in HLS hue space.
h, l, and s should be between 0 and 1
Parameters
----------
n_colors : int
number of colors in the palette
h : float
first hue
l : float
lightness
s : float
saturation
Returns
-------
list of RGB tuples or :class:`matplotlib.colors.Colormap`
See Also
--------
husl_palette : Make a palette using evenly spaced hues in the HUSL system.
Examples
--------
Create a palette of 10 colors with the default parameters:
.. plot::
:context: close-figs
>>> import seaborn as sns; sns.set_theme()
>>> sns.palplot(sns.hls_palette(10))
Create a palette of 10 colors that begins at a different hue value:
.. plot::
:context: close-figs
>>> sns.palplot(sns.hls_palette(10, h=.5))
Create a palette of 10 colors that are darker than the default:
.. plot::
:context: close-figs
>>> sns.palplot(sns.hls_palette(10, l=.4))
Create a palette of 10 colors that are less saturated than the default:
.. plot::
:context: close-figs
>>> sns.palplot(sns.hls_palette(10, s=.4))
"""
...
def husl_palette(n_colors=..., h=..., s=..., l=..., as_cmap=...): # -> _ColorPalette:
"""Get a set of evenly spaced colors in HUSL hue space.
h, s, and l should be between 0 and 1
Parameters
----------
n_colors : int
number of colors in the palette
h : float
first hue
s : float
saturation
l : float
lightness
Returns
-------
list of RGB tuples or :class:`matplotlib.colors.Colormap`
See Also
--------
hls_palette : Make a palette using evently spaced circular hues in the
HSL system.
Examples
--------
Create a palette of 10 colors with the default parameters:
.. plot::
:context: close-figs
>>> import seaborn as sns; sns.set_theme()
>>> sns.palplot(sns.husl_palette(10))
Create a palette of 10 colors that begins at a different hue value:
.. plot::
:context: close-figs
>>> sns.palplot(sns.husl_palette(10, h=.5))
Create a palette of 10 colors that are darker than the default:
.. plot::
:context: close-figs
>>> sns.palplot(sns.husl_palette(10, l=.4))
Create a palette of 10 colors that are less saturated than the default:
.. plot::
:context: close-figs
>>> sns.palplot(sns.husl_palette(10, s=.4))
"""
...
def mpl_palette(name, n_colors=..., as_cmap=...): # -> _ColorPalette:
"""Return discrete colors from a matplotlib palette.
Note that this handles the qualitative colorbrewer palettes
properly, although if you ask for more colors than a particular
qualitative palette can provide you will get fewer than you are
expecting. In contrast, asking for qualitative color brewer palettes
using :func:`color_palette` will return the expected number of colors,
but they will cycle.
If you are using the IPython notebook, you can also use the function
:func:`choose_colorbrewer_palette` to interactively select palettes.
Parameters
----------
name : string
Name of the palette. This should be a named matplotlib colormap.
n_colors : int
Number of discrete colors in the palette.
Returns
-------
list of RGB tuples or :class:`matplotlib.colors.Colormap`
Examples
--------
Create a qualitative colorbrewer palette with 8 colors:
.. plot::
:context: close-figs
>>> import seaborn as sns; sns.set_theme()
>>> sns.palplot(sns.mpl_palette("Set2", 8))
Create a sequential colorbrewer palette:
.. plot::
:context: close-figs
>>> sns.palplot(sns.mpl_palette("Blues"))
Create a diverging palette:
.. plot::
:context: close-figs
>>> sns.palplot(sns.mpl_palette("seismic", 8))
Create a "dark" sequential palette:
.. plot::
:context: close-figs
>>> sns.palplot(sns.mpl_palette("GnBu_d"))
"""
...
def dark_palette(color, n_colors=..., reverse=..., as_cmap=..., input=...): # -> _ColorPalette:
"""Make a sequential palette that blends from dark to ``color``.
This kind of palette is good for data that range between relatively
uninteresting low values and interesting high values.
The ``color`` parameter can be specified in a number of ways, including
all options for defining a color in matplotlib and several additional
color spaces that are handled by seaborn. You can also use the database
of named colors from the XKCD color survey.
If you are using the IPython notebook, you can also choose this palette
interactively with the :func:`choose_dark_palette` function.
Parameters
----------
color : base color for high values
hex, rgb-tuple, or html color name
n_colors : int, optional
number of colors in the palette
reverse : bool, optional
if True, reverse the direction of the blend
as_cmap : bool, optional
If True, return a :class:`matplotlib.colors.Colormap`.
input : {'rgb', 'hls', 'husl', xkcd'}
Color space to interpret the input color. The first three options
apply to tuple inputs and the latter applies to string inputs.
Returns
-------
list of RGB tuples or :class:`matplotlib.colors.Colormap`
See Also
--------
light_palette : Create a sequential palette with bright low values.
diverging_palette : Create a diverging palette with two colors.
Examples
--------
Generate a palette from an HTML color:
.. plot::
:context: close-figs
>>> import seaborn as sns; sns.set_theme()
>>> sns.palplot(sns.dark_palette("purple"))
Generate a palette that decreases in lightness:
.. plot::
:context: close-figs
>>> sns.palplot(sns.dark_palette("seagreen", reverse=True))
Generate a palette from an HUSL-space seed:
.. plot::
:context: close-figs
>>> sns.palplot(sns.dark_palette((260, 75, 60), input="husl"))
Generate a colormap object:
.. plot::
:context: close-figs
>>> from numpy import arange
>>> x = arange(25).reshape(5, 5)
>>> cmap = sns.dark_palette("#2ecc71", as_cmap=True)
>>> ax = sns.heatmap(x, cmap=cmap)
"""
...
def light_palette(color, n_colors=..., reverse=..., as_cmap=..., input=...): # -> _ColorPalette:
"""Make a sequential palette that blends from light to ``color``.
This kind of palette is good for data that range between relatively
uninteresting low values and interesting high values.
The ``color`` parameter can be specified in a number of ways, including
all options for defining a color in matplotlib and several additional
color spaces that are handled by seaborn. You can also use the database
of named colors from the XKCD color survey.
If you are using the IPython notebook, you can also choose this palette
interactively with the :func:`choose_light_palette` function.
Parameters
----------
color : base color for high values
hex code, html color name, or tuple in ``input`` space.
n_colors : int, optional
number of colors in the palette
reverse : bool, optional
if True, reverse the direction of the blend
as_cmap : bool, optional
If True, return a :class:`matplotlib.colors.Colormap`.
input : {'rgb', 'hls', 'husl', xkcd'}
Color space to interpret the input color. The first three options
apply to tuple inputs and the latter applies to string inputs.
Returns
-------
list of RGB tuples or :class:`matplotlib.colors.Colormap`
See Also
--------
dark_palette : Create a sequential palette with dark low values.
diverging_palette : Create a diverging palette with two colors.
Examples
--------
Generate a palette from an HTML color:
.. plot::
:context: close-figs
>>> import seaborn as sns; sns.set_theme()
>>> sns.palplot(sns.light_palette("purple"))
Generate a palette that increases in lightness:
.. plot::
:context: close-figs
>>> sns.palplot(sns.light_palette("seagreen", reverse=True))
Generate a palette from an HUSL-space seed:
.. plot::
:context: close-figs
>>> sns.palplot(sns.light_palette((260, 75, 60), input="husl"))
Generate a colormap object:
.. plot::
:context: close-figs
>>> from numpy import arange
>>> x = arange(25).reshape(5, 5)
>>> cmap = sns.light_palette("#2ecc71", as_cmap=True)
>>> ax = sns.heatmap(x, cmap=cmap)
"""
...
def diverging_palette(h_neg, h_pos, s=..., l=..., sep=..., n=..., center=..., as_cmap=...): # -> _ColorPalette:
"""Make a diverging palette between two HUSL colors.
If you are using the IPython notebook, you can also choose this palette
interactively with the :func:`choose_diverging_palette` function.
Parameters
----------
h_neg, h_pos : float in [0, 359]
Anchor hues for negative and positive extents of the map.
s : float in [0, 100], optional
Anchor saturation for both extents of the map.
l : float in [0, 100], optional
Anchor lightness for both extents of the map.
sep : int, optional
Size of the intermediate region.
n : int, optional
Number of colors in the palette (if not returning a cmap)
center : {"light", "dark"}, optional
Whether the center of the palette is light or dark
as_cmap : bool, optional
If True, return a :class:`matplotlib.colors.Colormap`.
Returns
-------
list of RGB tuples or :class:`matplotlib.colors.Colormap`
See Also
--------
dark_palette : Create a sequential palette with dark values.
light_palette : Create a sequential palette with light values.
Examples
--------
Generate a blue-white-red palette:
.. plot::
:context: close-figs
>>> import seaborn as sns; sns.set_theme()
>>> sns.palplot(sns.diverging_palette(240, 10, n=9))
Generate a brighter green-white-purple palette:
.. plot::
:context: close-figs
>>> sns.palplot(sns.diverging_palette(150, 275, s=80, l=55, n=9))
Generate a blue-black-red palette:
.. plot::
:context: close-figs
>>> sns.palplot(sns.diverging_palette(250, 15, s=75, l=40,
... n=9, center="dark"))
Generate a colormap object:
.. plot::
:context: close-figs
>>> from numpy import arange
>>> x = arange(25).reshape(5, 5)
>>> cmap = sns.diverging_palette(220, 20, as_cmap=True)
>>> ax = sns.heatmap(x, cmap=cmap)
"""
...
def blend_palette(colors, n_colors=..., as_cmap=..., input=...): # -> _ColorPalette:
"""Make a palette that blends between a list of colors.
Parameters
----------
colors : sequence of colors in various formats interpreted by ``input``
hex code, html color name, or tuple in ``input`` space.
n_colors : int, optional
Number of colors in the palette.
as_cmap : bool, optional
If True, return a :class:`matplotlib.colors.Colormap`.
Returns
-------
list of RGB tuples or :class:`matplotlib.colors.Colormap`
"""
...
def xkcd_palette(colors): # -> _ColorPalette | list[tuple[float, float, float]] | Any | list[str]:
"""Make a palette with color names from the xkcd color survey.
See xkcd for the full list of colors: https://xkcd.com/color/rgb/
This is just a simple wrapper around the ``seaborn.xkcd_rgb`` dictionary.
Parameters
----------
colors : list of strings
List of keys in the ``seaborn.xkcd_rgb`` dictionary.
Returns
-------
palette : seaborn color palette
Returns the list of colors as RGB tuples in an object that behaves like
other seaborn color palettes.
See Also
--------
crayon_palette : Make a palette with Crayola crayon colors.
"""
...
def crayon_palette(colors): # -> _ColorPalette | list[tuple[float, float, float]] | Any | list[str]:
"""Make a palette with color names from Crayola crayons.
Colors are taken from here:
https://en.wikipedia.org/wiki/List_of_Crayola_crayon_colors
This is just a simple wrapper around the ``seaborn.crayons`` dictionary.
Parameters
----------
colors : list of strings
List of keys in the ``seaborn.crayons`` dictionary.
Returns
-------
palette : seaborn color palette
Returns the list of colors as rgb tuples in an object that behaves like
other seaborn color palettes.
See Also
--------
xkcd_palette : Make a palette with named colors from the XKCD color survey.
"""
...
def cubehelix_palette(n_colors=..., start=..., rot=..., gamma=..., hue=..., light=..., dark=..., reverse=..., as_cmap=...): # -> _ColorPalette:
"""Make a sequential palette from the cubehelix system.
This produces a colormap with linearly-decreasing (or increasing)
brightness. That means that information will be preserved if printed to
black and white or viewed by someone who is colorblind. "cubehelix" is
also available as a matplotlib-based palette, but this function gives the
user more control over the look of the palette and has a different set of
defaults.
In addition to using this function, it is also possible to generate a
cubehelix palette generally in seaborn using a string-shorthand; see the
example below.
Parameters
----------
n_colors : int
Number of colors in the palette.
start : float, 0 <= start <= 3
The hue at the start of the helix.
rot : float
Rotations around the hue wheel over the range of the palette.
gamma : float 0 <= gamma
Gamma factor to emphasize darker (gamma < 1) or lighter (gamma > 1)
colors.
hue : float, 0 <= hue <= 1
Saturation of the colors.
dark : float 0 <= dark <= 1
Intensity of the darkest color in the palette.
light : float 0 <= light <= 1
Intensity of the lightest color in the palette.
reverse : bool
If True, the palette will go from dark to light.
as_cmap : bool
If True, return a :class:`matplotlib.colors.Colormap`.
Returns
-------
list of RGB tuples or :class:`matplotlib.colors.Colormap`
See Also
--------
choose_cubehelix_palette : Launch an interactive widget to select cubehelix
palette parameters.
dark_palette : Create a sequential palette with dark low values.
light_palette : Create a sequential palette with bright low values.
References
----------
Green, D. A. (2011). "A colour scheme for the display of astronomical
intensity images". Bulletin of the Astromical Society of India, Vol. 39,
p. 289-295.
Examples
--------
Generate the default palette:
.. plot::
:context: close-figs
>>> import seaborn as sns; sns.set_theme()
>>> sns.palplot(sns.cubehelix_palette())
Rotate backwards from the same starting location:
.. plot::
:context: close-figs
>>> sns.palplot(sns.cubehelix_palette(rot=-.4))
Use a different starting point and shorter rotation:
.. plot::
:context: close-figs
>>> sns.palplot(sns.cubehelix_palette(start=2.8, rot=.1))
Reverse the direction of the lightness ramp:
.. plot::
:context: close-figs
>>> sns.palplot(sns.cubehelix_palette(reverse=True))
Generate a colormap object:
.. plot::
:context: close-figs
>>> from numpy import arange
>>> x = arange(25).reshape(5, 5)
>>> cmap = sns.cubehelix_palette(as_cmap=True)
>>> ax = sns.heatmap(x, cmap=cmap)
Use the full lightness range:
.. plot::
:context: close-figs
>>> cmap = sns.cubehelix_palette(dark=0, light=1, as_cmap=True)
>>> ax = sns.heatmap(x, cmap=cmap)
Use through the :func:`color_palette` interface:
.. plot::
:context: close-figs
>>> sns.palplot(sns.color_palette("ch:2,r=.2,l=.6"))
"""
...
def set_color_codes(palette=...): # -> None:
"""Change how matplotlib color shorthands are interpreted.
Calling this will change how shorthand codes like "b" or "g"
are interpreted by matplotlib in subsequent plots.
Parameters
----------
palette : {deep, muted, pastel, dark, bright, colorblind}
Named seaborn palette to use as the source of colors.
See Also
--------
set : Color codes can be set through the high-level seaborn style
manager.
set_palette : Color codes can also be set through the function that
sets the matplotlib color cycle.
Examples
--------
Map matplotlib color codes to the default seaborn palette.
.. plot::
:context: close-figs
>>> import matplotlib.pyplot as plt
>>> import seaborn as sns; sns.set_theme()
>>> sns.set_color_codes()
>>> _ = plt.plot([0, 1], color="r")
Use a different seaborn palette.
.. plot::
:context: close-figs
>>> sns.set_color_codes("dark")
>>> _ = plt.plot([0, 1], color="g")
>>> _ = plt.plot([0, 2], color="m")
"""
...

265
typings/seaborn/rcmod.pyi Normal file
View file

@ -0,0 +1,265 @@
"""
This type stub file was generated by pyright.
"""
import matplotlib as mpl
from distutils.version import LooseVersion
"""Control plot style and scaling using the matplotlib rcParams interface."""
__all__ = ["set_theme", "set", "reset_defaults", "reset_orig", "axes_style", "set_style", "plotting_context", "set_context", "set_palette"]
_style_keys = ...
_context_keys = ...
if LooseVersion(mpl.__version__) >= "3.0":
...
def set_theme(context=..., style=..., palette=..., font=..., font_scale=..., color_codes=..., rc=...): # -> None:
"""Set multiple theme parameters in one step.
Each set of parameters can be set directly or temporarily, see the
referenced functions below for more information.
Parameters
----------
context : string or dict
Plotting context parameters, see :func:`plotting_context`.
style : string or dict
Axes style parameters, see :func:`axes_style`.
palette : string or sequence
Color palette, see :func:`color_palette`.
font : string
Font family, see matplotlib font manager.
font_scale : float, optional
Separate scaling factor to independently scale the size of the
font elements.
color_codes : bool
If ``True`` and ``palette`` is a seaborn palette, remap the shorthand
color codes (e.g. "b", "g", "r", etc.) to the colors from this palette.
rc : dict or None
Dictionary of rc parameter mappings to override the above.
"""
...
def set(*args, **kwargs): # -> None:
"""Alias for :func:`set_theme`, which is the preferred interface."""
...
def reset_defaults(): # -> None:
"""Restore all RC params to default settings."""
...
def reset_orig(): # -> None:
"""Restore all RC params to original settings (respects custom rc)."""
...
def axes_style(style=..., rc=...): # -> _AxesStyle:
"""Return a parameter dict for the aesthetic style of the plots.
This affects things like the color of the axes, whether a grid is
enabled by default, and other aesthetic elements.
This function returns an object that can be used in a ``with`` statement
to temporarily change the style parameters.
Parameters
----------
style : dict, None, or one of {darkgrid, whitegrid, dark, white, ticks}
A dictionary of parameters or the name of a preconfigured set.
rc : dict, optional
Parameter mappings to override the values in the preset seaborn
style dictionaries. This only updates parameters that are
considered part of the style definition.
Examples
--------
>>> st = axes_style("whitegrid")
>>> set_style("ticks", {"xtick.major.size": 8, "ytick.major.size": 8})
>>> import matplotlib.pyplot as plt
>>> with axes_style("white"):
... f, ax = plt.subplots()
... ax.plot(x, y) # doctest: +SKIP
See Also
--------
set_style : set the matplotlib parameters for a seaborn theme
plotting_context : return a parameter dict to to scale plot elements
color_palette : define the color palette for a plot
"""
...
def set_style(style=..., rc=...): # -> None:
"""Set the aesthetic style of the plots.
This affects things like the color of the axes, whether a grid is
enabled by default, and other aesthetic elements.
Parameters
----------
style : dict, None, or one of {darkgrid, whitegrid, dark, white, ticks}
A dictionary of parameters or the name of a preconfigured set.
rc : dict, optional
Parameter mappings to override the values in the preset seaborn
style dictionaries. This only updates parameters that are
considered part of the style definition.
Examples
--------
>>> set_style("whitegrid")
>>> set_style("ticks", {"xtick.major.size": 8, "ytick.major.size": 8})
See Also
--------
axes_style : return a dict of parameters or use in a ``with`` statement
to temporarily set the style.
set_context : set parameters to scale plot elements
set_palette : set the default color palette for figures
"""
...
def plotting_context(context=..., font_scale=..., rc=...): # -> _PlottingContext:
"""Return a parameter dict to scale elements of the figure.
This affects things like the size of the labels, lines, and other
elements of the plot, but not the overall style. The base context
is "notebook", and the other contexts are "paper", "talk", and "poster",
which are version of the notebook parameters scaled by .8, 1.3, and 1.6,
respectively.
This function returns an object that can be used in a ``with`` statement
to temporarily change the context parameters.
Parameters
----------
context : dict, None, or one of {paper, notebook, talk, poster}
A dictionary of parameters or the name of a preconfigured set.
font_scale : float, optional
Separate scaling factor to independently scale the size of the
font elements.
rc : dict, optional
Parameter mappings to override the values in the preset seaborn
context dictionaries. This only updates parameters that are
considered part of the context definition.
Examples
--------
>>> c = plotting_context("poster")
>>> c = plotting_context("notebook", font_scale=1.5)
>>> c = plotting_context("talk", rc={"lines.linewidth": 2})
>>> import matplotlib.pyplot as plt
>>> with plotting_context("paper"):
... f, ax = plt.subplots()
... ax.plot(x, y) # doctest: +SKIP
See Also
--------
set_context : set the matplotlib parameters to scale plot elements
axes_style : return a dict of parameters defining a figure style
color_palette : define the color palette for a plot
"""
...
def set_context(context=..., font_scale=..., rc=...): # -> None:
"""Set the plotting context parameters.
This affects things like the size of the labels, lines, and other
elements of the plot, but not the overall style. The base context
is "notebook", and the other contexts are "paper", "talk", and "poster",
which are version of the notebook parameters scaled by .8, 1.3, and 1.6,
respectively.
Parameters
----------
context : dict, None, or one of {paper, notebook, talk, poster}
A dictionary of parameters or the name of a preconfigured set.
font_scale : float, optional
Separate scaling factor to independently scale the size of the
font elements.
rc : dict, optional
Parameter mappings to override the values in the preset seaborn
context dictionaries. This only updates parameters that are
considered part of the context definition.
Examples
--------
>>> set_context("paper")
>>> set_context("talk", font_scale=1.4)
>>> set_context("talk", rc={"lines.linewidth": 2})
See Also
--------
plotting_context : return a dictionary of rc parameters, or use in
a ``with`` statement to temporarily set the context.
set_style : set the default parameters for figure style
set_palette : set the default color palette for figures
"""
...
class _RCAesthetics(dict):
def __enter__(self): # -> None:
...
def __exit__(self, exc_type, exc_value, exc_tb): # -> None:
...
def __call__(self, func): # -> _Wrapped[..., Unknown, (*args: Unknown, **kwargs: Unknown), Unknown]:
...
class _AxesStyle(_RCAesthetics):
"""Light wrapper on a dict to set style temporarily."""
_keys = ...
_set = ...
class _PlottingContext(_RCAesthetics):
"""Light wrapper on a dict to set context temporarily."""
_keys = ...
_set = ...
def set_palette(palette, n_colors=..., desat=..., color_codes=...): # -> None:
"""Set the matplotlib color cycle using a seaborn palette.
Parameters
----------
palette : seaborn color paltte | matplotlib colormap | hls | husl
Palette definition. Should be something that :func:`color_palette`
can process.
n_colors : int
Number of colors in the cycle. The default number of colors will depend
on the format of ``palette``, see the :func:`color_palette`
documentation for more information.
desat : float
Proportion to desaturate each color by.
color_codes : bool
If ``True`` and ``palette`` is a seaborn palette, remap the shorthand
color codes (e.g. "b", "g", "r", etc.) to the colors from this palette.
Examples
--------
>>> set_palette("Reds")
>>> set_palette("Set1", 8, .75)
See Also
--------
color_palette : build a color palette or set the color cycle temporarily
in a ``with`` statement.
set_context : set parameters to scale plot elements
set_style : set the default parameters for figure style
"""
...

View file

@ -0,0 +1,158 @@
"""
This type stub file was generated by pyright.
"""
from ._decorators import _deprecate_positional_args
"""Plotting functions for linear models (broadly construed)."""
_has_statsmodels = ...
__all__ = ["lmplot", "regplot", "residplot"]
class _LinearPlotter:
"""Base class for plotting relational data in tidy format.
To get anything useful done you'll have to inherit from this, but setup
code that can be abstracted out should be put here.
"""
def establish_variables(self, data, **kws): # -> None:
"""Extract variables from data or use directly."""
...
def dropna(self, *vars): # -> None:
"""Remove observations with missing data."""
...
def plot(self, ax):
...
class _RegressionPlotter(_LinearPlotter):
"""Plotter for numeric independent variables with regression model.
This does the computations and drawing for the `regplot` function, and
is thus also used indirectly by `lmplot`.
"""
def __init__(self, x, y, data=..., x_estimator=..., x_bins=..., x_ci=..., scatter=..., fit_reg=..., ci=..., n_boot=..., units=..., seed=..., order=..., logistic=..., lowess=..., robust=..., logx=..., x_partial=..., y_partial=..., truncate=..., dropna=..., x_jitter=..., y_jitter=..., color=..., label=...) -> None:
...
@property
def scatter_data(self): # -> tuple[ndarray[Any, dtype[Unknown]] | NDArray[floating[Any]], ndarray[Any, dtype[Unknown]] | NDArray[floating[Any]]]:
"""Data where each observation is a point."""
...
@property
def estimate_data(self): # -> tuple[list[Any], list[Unknown], list[Unknown]]:
"""Data with a point estimate and CI for each discrete x value."""
...
def fit_regression(self, ax=..., x_range=..., grid=...): # -> tuple[Unknown, Unknown | NDArray[float64] | Any, Unknown | None]:
"""Fit the regression model."""
...
def fit_fast(self, grid): # -> tuple[Any, None] | tuple[Any, Any]:
"""Low-level regression and prediction using linear algebra."""
...
def fit_poly(self, grid, order): # -> tuple[Unknown, None] | tuple[Unknown, NDArray[Unknown]]:
"""Regression using numpy polyfit for higher-order trends."""
...
def fit_statsmodels(self, grid, model, **kwargs): # -> tuple[Unknown | NDArray[float64], None] | tuple[Unknown | NDArray[float64], NDArray[Unknown]]:
"""More general regression function using statsmodels objects."""
...
def fit_lowess(self): # -> tuple[Unknown, Unknown]:
"""Fit a locally-weighted regression, which returns its own grid."""
...
def fit_logx(self, grid): # -> tuple[Any, None] | tuple[Any, Any]:
"""Fit the model in log-space."""
...
def bin_predictor(self, bins): # -> tuple[Any, Any]:
"""Discretize a predictor by assigning value to closest bin."""
...
def regress_out(self, a, b): # -> ndarray[Any, dtype[Unknown]]:
"""Regress b from a keeping a's original mean."""
...
def plot(self, ax, scatter_kws, line_kws): # -> None:
"""Draw the full plot."""
...
def scatterplot(self, ax, kws): # -> None:
"""Draw the data."""
...
def lineplot(self, ax, kws): # -> None:
"""Draw the model."""
...
_regression_docs = ...
@_deprecate_positional_args
def lmplot(*, x=..., y=..., data=..., hue=..., col=..., row=..., palette=..., col_wrap=..., height=..., aspect=..., markers=..., sharex=..., sharey=..., hue_order=..., col_order=..., row_order=..., legend=..., legend_out=..., x_estimator=..., x_bins=..., x_ci=..., scatter=..., fit_reg=..., ci=..., n_boot=..., units=..., seed=..., order=..., logistic=..., lowess=..., robust=..., logx=..., x_partial=..., y_partial=..., truncate=..., x_jitter=..., y_jitter=..., scatter_kws=..., line_kws=..., size=...): # -> FacetGrid:
...
@_deprecate_positional_args
def regplot(*, x=..., y=..., data=..., x_estimator=..., x_bins=..., x_ci=..., scatter=..., fit_reg=..., ci=..., n_boot=..., units=..., seed=..., order=..., logistic=..., lowess=..., robust=..., logx=..., x_partial=..., y_partial=..., truncate=..., dropna=..., x_jitter=..., y_jitter=..., label=..., color=..., marker=..., scatter_kws=..., line_kws=..., ax=...): # -> Axes:
...
@_deprecate_positional_args
def residplot(*, x=..., y=..., data=..., lowess=..., x_partial=..., y_partial=..., order=..., robust=..., dropna=..., label=..., color=..., scatter_kws=..., line_kws=..., ax=...): # -> Axes:
"""Plot the residuals of a linear regression.
This function will regress y on x (possibly as a robust or polynomial
regression) and then draw a scatterplot of the residuals. You can
optionally fit a lowess smoother to the residual plot, which can
help in determining if there is structure to the residuals.
Parameters
----------
x : vector or string
Data or column name in `data` for the predictor variable.
y : vector or string
Data or column name in `data` for the response variable.
data : DataFrame, optional
DataFrame to use if `x` and `y` are column names.
lowess : boolean, optional
Fit a lowess smoother to the residual scatterplot.
{x, y}_partial : matrix or string(s) , optional
Matrix with same first dimension as `x`, or column name(s) in `data`.
These variables are treated as confounding and are removed from
the `x` or `y` variables before plotting.
order : int, optional
Order of the polynomial to fit when calculating the residuals.
robust : boolean, optional
Fit a robust linear regression when calculating the residuals.
dropna : boolean, optional
If True, ignore observations with missing data when fitting and
plotting.
label : string, optional
Label that will be used in any plot legends.
color : matplotlib color, optional
Color to use for all elements of the plot.
{scatter, line}_kws : dictionaries, optional
Additional keyword arguments passed to scatter() and plot() for drawing
the components of the plot.
ax : matplotlib axis, optional
Plot into this axis, otherwise grab the current axis or make a new
one if not existing.
Returns
-------
ax: matplotlib axes
Axes with the regression plot.
See Also
--------
regplot : Plot a simple linear regression model.
jointplot : Draw a :func:`residplot` with univariate marginal distributions
(when used with ``kind="resid"``).
"""
...

View file

@ -0,0 +1,59 @@
"""
This type stub file was generated by pyright.
"""
from ._core import VectorPlotter
from ._decorators import _deprecate_positional_args
__all__ = ["relplot", "scatterplot", "lineplot"]
_relational_narrative = ...
_relational_docs = ...
_param_docs = ...
class _RelationalPlotter(VectorPlotter):
wide_structure = ...
sort = ...
def add_legend_data(self, ax):
"""Add labeled artists to represent the different plot semantics."""
...
class _LinePlotter(_RelationalPlotter):
_legend_attributes = ...
_legend_func = ...
def __init__(self, *, data=..., variables=..., estimator=..., ci=..., n_boot=..., seed=..., sort=..., err_style=..., err_kws=..., legend=...) -> None:
...
def aggregate(self, vals, grouper, units=...): # -> tuple[Unknown, Unknown, None] | tuple[Unknown, Unknown, Series | DataFrame | Unknown | None]:
"""Compute an estimate and confidence interval using grouper."""
...
def plot(self, ax, kws): # -> None:
"""Draw the plot onto an axes, passing matplotlib kwargs."""
...
class _ScatterPlotter(_RelationalPlotter):
_legend_attributes = ...
_legend_func = ...
def __init__(self, *, data=..., variables=..., x_bins=..., y_bins=..., estimator=..., ci=..., n_boot=..., alpha=..., x_jitter=..., y_jitter=..., legend=...) -> None:
...
def plot(self, ax, kws): # -> None:
...
@_deprecate_positional_args
def lineplot(*, x=..., y=..., hue=..., size=..., style=..., data=..., palette=..., hue_order=..., hue_norm=..., sizes=..., size_order=..., size_norm=..., dashes=..., markers=..., style_order=..., units=..., estimator=..., ci=..., n_boot=..., seed=..., sort=..., err_style=..., err_kws=..., legend=..., ax=..., **kwargs): # -> Axes:
...
@_deprecate_positional_args
def scatterplot(*, x=..., y=..., hue=..., style=..., size=..., data=..., palette=..., hue_order=..., hue_norm=..., sizes=..., size_order=..., size_norm=..., markers=..., style_order=..., x_bins=..., y_bins=..., units=..., estimator=..., ci=..., n_boot=..., alpha=..., x_jitter=..., y_jitter=..., legend=..., ax=..., **kwargs): # -> Axes:
...
@_deprecate_positional_args
def relplot(*, x=..., y=..., hue=..., size=..., style=..., data=..., row=..., col=..., col_wrap=..., row_order=..., col_order=..., palette=..., hue_order=..., hue_norm=..., sizes=..., size_order=..., size_norm=..., markers=..., dashes=..., style_order=..., legend=..., kind=..., height=..., aspect=..., facet_kws=..., units=..., **kwargs): # -> FacetGrid:
...

View file

@ -0,0 +1,4 @@
"""
This type stub file was generated by pyright.
"""

344
typings/seaborn/utils.pyi Normal file
View file

@ -0,0 +1,344 @@
"""
This type stub file was generated by pyright.
"""
"""Utility functions, mostly for internal use."""
__all__ = ["desaturate", "saturate", "set_hls_values", "despine", "get_dataset_names", "get_data_home", "load_dataset"]
def sort_df(df, *args, **kwargs):
"""Wrapper to handle different pandas sorting API pre/post 0.17."""
...
def ci_to_errsize(cis, heights): # -> NDArray[Unknown]:
"""Convert intervals to error arguments relative to plot heights.
Parameters
----------
cis: 2 x n sequence
sequence of confidence interval limits
heights : n sequence
sequence of plot heights
Returns
-------
errsize : 2 x n array
sequence of error size relative to height values in correct
format as argument for plt.bar
"""
...
def pmf_hist(a, bins=...): # -> tuple[ndarray[Any, dtype[Any]], Any, Any]:
"""Return arguments to plt.bar for pmf-like histogram of an array.
DEPRECATED: will be removed in a future version.
Parameters
----------
a: array-like
array to make histogram of
bins: int
number of bins
Returns
-------
x: array
left x position of bars
h: array
height of bars
w: float
width of bars
"""
...
def desaturate(color, prop): # -> tuple[float, float, float]:
"""Decrease the saturation channel of a color by some percent.
Parameters
----------
color : matplotlib color
hex, rgb-tuple, or html color name
prop : float
saturation channel of color will be multiplied by this value
Returns
-------
new_color : rgb tuple
desaturated color code in RGB tuple representation
"""
...
def saturate(color): # -> tuple[float, float, float]:
"""Return a fully saturated color with the same hue.
Parameters
----------
color : matplotlib color
hex, rgb-tuple, or html color name
Returns
-------
new_color : rgb tuple
saturated color code in RGB tuple representation
"""
...
def set_hls_values(color, h=..., l=..., s=...): # -> tuple[float, float, float]:
"""Independently manipulate the h, l, or s channels of a color.
Parameters
----------
color : matplotlib color
hex, rgb-tuple, or html color name
h, l, s : floats between 0 and 1, or None
new values for each channel in hls space
Returns
-------
new_color : rgb tuple
new color code in RGB tuple representation
"""
...
def axlabel(xlabel, ylabel, **kwargs): # -> None:
"""Grab current axis and label it.
DEPRECATED: will be removed in a future version.
"""
...
def remove_na(vector):
"""Helper method for removing null values from data vectors.
Parameters
----------
vector : vector object
Must implement boolean masking with [] subscript syntax.
Returns
-------
clean_clean : same type as ``vector``
Vector of data with null values removed. May be a copy or a view.
"""
...
def get_color_cycle(): # -> Any | list[str]:
"""Return the list of colors in the current matplotlib color cycle
Parameters
----------
None
Returns
-------
colors : list
List of matplotlib colors in the current cycle, or dark gray if
the current color cycle is empty.
"""
...
def despine(fig=..., ax=..., top=..., right=..., left=..., bottom=..., offset=..., trim=...): # -> None:
"""Remove the top and right spines from plot(s).
fig : matplotlib figure, optional
Figure to despine all axes of, defaults to the current figure.
ax : matplotlib axes, optional
Specific axes object to despine. Ignored if fig is provided.
top, right, left, bottom : boolean, optional
If True, remove that spine.
offset : int or dict, optional
Absolute distance, in points, spines should be moved away
from the axes (negative values move spines inward). A single value
applies to all spines; a dict can be used to set offset values per
side.
trim : bool, optional
If True, limit spines to the smallest and largest major tick
on each non-despined axis.
Returns
-------
None
"""
...
def percentiles(a, pcts, axis=...): # -> ndarray[Any, dtype[Unknown]]:
"""Like scoreatpercentile but can take and return array of percentiles.
DEPRECATED: will be removed in a future version.
Parameters
----------
a : array
data
pcts : sequence of percentile values
percentile or percentiles to find score at
axis : int or None
if not None, computes scores over this axis
Returns
-------
scores: array
array of scores at requested percentiles
first dimension is length of object passed to ``pcts``
"""
...
def ci(a, which=..., axis=...):
"""Return a percentile range from an array of values."""
...
def sig_stars(p): # -> Literal['***', '**', '*', '.', '']:
"""Return a R-style significance string corresponding to p values.
DEPRECATED: will be removed in a future version.
"""
...
def iqr(a): # -> float | NDArray[floating[Any]] | Any | NDArray[Any]:
"""Calculate the IQR for an array of numbers.
DEPRECATED: will be removed in a future version.
"""
...
def get_dataset_names(): # -> list[Any]:
"""Report available example datasets, useful for reporting issues.
Requires an internet connection.
"""
...
def get_data_home(data_home=...): # -> str:
"""Return a path to the cache directory for example datasets.
This directory is then used by :func:`load_dataset`.
If the ``data_home`` argument is not specified, it tries to read from the
``SEABORN_DATA`` environment variable and defaults to ``~/seaborn-data``.
"""
...
def load_dataset(name, cache=..., data_home=..., **kws):
"""Load an example dataset from the online repository (requires internet).
This function provides quick access to a small number of example datasets
that are useful for documenting seaborn or generating reproducible examples
for bug reports. It is not necessary for normal usage.
Note that some of the datasets have a small amount of preprocessing applied
to define a proper ordering for categorical variables.
Use :func:`get_dataset_names` to see a list of available datasets.
Parameters
----------
name : str
Name of the dataset (``{name}.csv`` on
https://github.com/mwaskom/seaborn-data).
cache : boolean, optional
If True, try to load from the local cache first, and save to the cache
if a download is required.
data_home : string, optional
The directory in which to cache data; see :func:`get_data_home`.
kws : keys and values, optional
Additional keyword arguments are passed to passed through to
:func:`pandas.read_csv`.
Returns
-------
df : :class:`pandas.DataFrame`
Tabular data, possibly with some preprocessing applied.
"""
...
def axis_ticklabels_overlap(labels): # -> Literal[False]:
"""Return a boolean for whether the list of ticklabels have overlaps.
Parameters
----------
labels : list of matplotlib ticklabels
Returns
-------
overlap : boolean
True if any of the labels overlap.
"""
...
def axes_ticklabels_overlap(ax): # -> tuple[Unknown | Literal[False], Unknown | Literal[False]]:
"""Return booleans for whether the x and y ticklabels on an Axes overlap.
Parameters
----------
ax : matplotlib Axes
Returns
-------
x_overlap, y_overlap : booleans
True when the labels on that axis overlap.
"""
...
def locator_to_legend_entries(locator, limits, dtype): # -> tuple[list[Unknown], list[Unknown]]:
"""Return levels and formatted levels for brief numeric legends."""
class dummy_axis:
...
def relative_luminance(color): # -> Any:
"""Calculate the relative luminance of a color according to W3C standards
Parameters
----------
color : matplotlib color or sequence of matplotlib colors
Hex code, rgb-tuple, or html color name.
Returns
-------
luminance : float(s) between 0 and 1
"""
...
def to_utf8(obj): # -> str:
"""Return a string representing a Python object.
Strings (i.e. type ``str``) are returned unchanged.
Byte strings (i.e. type ``bytes``) are returned as UTF-8-decoded strings.
For other objects, the method ``__str__()`` is called, and the result is
returned as a string.
Parameters
----------
obj : object
Any Python object
Returns
-------
s : str
UTF-8-decoded string representation of ``obj``
"""
...
def adjust_legend_subtitles(legend): # -> None:
"""Make invisible-handle "subtitles" entries look more like titles."""
...

165
typings/seaborn/widgets.pyi Normal file
View file

@ -0,0 +1,165 @@
"""
This type stub file was generated by pyright.
"""
__all__ = ["choose_colorbrewer_palette", "choose_cubehelix_palette", "choose_dark_palette", "choose_light_palette", "choose_diverging_palette"]
def choose_colorbrewer_palette(data_type, as_cmap=...): # -> LinearSegmentedColormap | list[Unknown]:
"""Select a palette from the ColorBrewer set.
These palettes are built into matplotlib and can be used by name in
many seaborn functions, or by passing the object returned by this function.
Parameters
----------
data_type : {'sequential', 'diverging', 'qualitative'}
This describes the kind of data you want to visualize. See the seaborn
color palette docs for more information about how to choose this value.
Note that you can pass substrings (e.g. 'q' for 'qualitative.
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
dark_palette : Create a sequential palette with dark low values.
light_palette : Create a sequential palette with bright low values.
diverging_palette : Create a diverging palette from selected colors.
cubehelix_palette : Create a sequential palette or colormap using the
cubehelix system.
"""
...
def choose_dark_palette(input=..., as_cmap=...): # -> LinearSegmentedColormap | list[Unknown]:
"""Launch an interactive widget to create a dark sequential palette.
This corresponds with the :func:`dark_palette` function. This kind
of palette is good for data that range between relatively uninteresting
low values and interesting high values.
Requires IPython 2+ and must be used in the notebook.
Parameters
----------
input : {'husl', 'hls', 'rgb'}
Color space for defining the seed value. Note that the default is
different than the default input for :func:`dark_palette`.
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
dark_palette : Create a sequential palette with dark low values.
light_palette : Create a sequential palette with bright low values.
cubehelix_palette : Create a sequential palette or colormap using the
cubehelix system.
"""
...
def choose_light_palette(input=..., as_cmap=...): # -> LinearSegmentedColormap | list[Unknown]:
"""Launch an interactive widget to create a light sequential palette.
This corresponds with the :func:`light_palette` function. This kind
of palette is good for data that range between relatively uninteresting
low values and interesting high values.
Requires IPython 2+ and must be used in the notebook.
Parameters
----------
input : {'husl', 'hls', 'rgb'}
Color space for defining the seed value. Note that the default is
different than the default input for :func:`light_palette`.
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
light_palette : Create a sequential palette with bright low values.
dark_palette : Create a sequential palette with dark low values.
cubehelix_palette : Create a sequential palette or colormap using the
cubehelix system.
"""
...
def choose_diverging_palette(as_cmap=...): # -> LinearSegmentedColormap | list[Unknown]:
"""Launch an interactive widget to choose a diverging color palette.
This corresponds with the :func:`diverging_palette` function. This kind
of palette is good for data that range between interesting low values
and interesting high values with a meaningful midpoint. (For example,
change scores relative to some baseline value).
Requires IPython 2+ and must be used in the notebook.
Parameters
----------
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
diverging_palette : Create a diverging color palette or colormap.
choose_colorbrewer_palette : Interactively choose palettes from the
colorbrewer set, including diverging palettes.
"""
...
def choose_cubehelix_palette(as_cmap=...): # -> LinearSegmentedColormap | list[Unknown]:
"""Launch an interactive widget to create a sequential cubehelix palette.
This corresponds with the :func:`cubehelix_palette` function. This kind
of palette is good for data that range between relatively uninteresting
low values and interesting high values. The cubehelix system allows the
palette to have more hue variance across the range, which can be helpful
for distinguishing a wider range of values.
Requires IPython 2+ and must be used in the notebook.
Parameters
----------
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
cubehelix_palette : Create a sequential palette or colormap using the
cubehelix system.
"""
...