code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def __init__(
self,
stat="count",
bins="auto",
binwidth=None,
binrange=None,
discrete=False,
cumulative=False,
):
"""Initialize the estimator with its parameters.
Parameters
----------
stat : str
Aggregate statistic... | Initialize the estimator with its parameters.
Parameters
----------
stat : str
Aggregate statistic to compute in each bin.
- `count`: show the number of observations in each bin
- `frequency`: show the number of observations divided by the bin width
... | __init__ | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def _define_bin_edges(self, x, weights, bins, binwidth, binrange, discrete):
"""Inner function that takes bin parameters as arguments."""
if binrange is None:
start, stop = x.min(), x.max()
else:
start, stop = binrange
if discrete:
bin_edges = np.aran... | Inner function that takes bin parameters as arguments. | _define_bin_edges | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def define_bin_params(self, x1, x2=None, weights=None, cache=True):
"""Given data, return numpy.histogram parameters to define bins."""
if x2 is None:
bin_edges = self._define_bin_edges(
x1, weights, self.bins, self.binwidth, self.binrange, self.discrete,
)
... | Given data, return numpy.histogram parameters to define bins. | define_bin_params | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def _eval_bivariate(self, x1, x2, weights):
"""Inner function for histogram of two variables."""
bin_kws = self.bin_kws
if bin_kws is None:
bin_kws = self.define_bin_params(x1, x2, cache=False)
density = self.stat == "density"
hist, *bin_edges = np.histogram2d(
... | Inner function for histogram of two variables. | _eval_bivariate | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def _eval_univariate(self, x, weights):
"""Inner function for histogram of one variable."""
bin_kws = self.bin_kws
if bin_kws is None:
bin_kws = self.define_bin_params(x, weights=weights, cache=False)
density = self.stat == "density"
hist, bin_edges = np.histogram(
... | Inner function for histogram of one variable. | _eval_univariate | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def __call__(self, x1, x2=None, weights=None):
"""Count the occurrences in each bin, maybe normalize."""
if x2 is None:
return self._eval_univariate(x1, weights)
else:
return self._eval_bivariate(x1, x2, weights) | Count the occurrences in each bin, maybe normalize. | __call__ | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def __init__(self, stat="proportion", complementary=False):
"""Initialize the class with its parameters
Parameters
----------
stat : {{"proportion", "percent", "count"}}
Distribution statistic to compute.
complementary : bool
If True, use the complementar... | Initialize the class with its parameters
Parameters
----------
stat : {{"proportion", "percent", "count"}}
Distribution statistic to compute.
complementary : bool
If True, use the complementary CDF (1 - CDF)
| __init__ | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def _eval_univariate(self, x, weights):
"""Inner function for ECDF of one variable."""
sorter = x.argsort()
x = x[sorter]
weights = weights[sorter]
y = weights.cumsum()
if self.stat in ["percent", "proportion"]:
y = y / y.max()
if self.stat == "percen... | Inner function for ECDF of one variable. | _eval_univariate | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def __call__(self, x1, x2=None, weights=None):
"""Return proportion or count of observations below each sorted datapoint."""
x1 = np.asarray(x1)
if weights is None:
weights = np.ones_like(x1)
else:
weights = np.asarray(weights)
if x2 is None:
... | Return proportion or count of observations below each sorted datapoint. | __call__ | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def __init__(self, estimator, errorbar=None, **boot_kws):
"""
Data aggregator that produces an estimate and error bar interval.
Parameters
----------
estimator : callable or string
Function (or method name) that maps a vector to a scalar.
errorbar : string, (... |
Data aggregator that produces an estimate and error bar interval.
Parameters
----------
estimator : callable or string
Function (or method name) that maps a vector to a scalar.
errorbar : string, (string, number) tuple, or callable
Name of errorbar metho... | __init__ | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def __call__(self, data, var):
"""Aggregate over `var` column of `data` with estimate and error interval."""
vals = data[var]
if callable(self.estimator):
# You would think we could pass to vals.agg, and yet:
# https://github.com/mwaskom/seaborn/issues/2943
es... | Aggregate over `var` column of `data` with estimate and error interval. | __call__ | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def __init__(self, estimator, errorbar=None, **boot_kws):
"""
Data aggregator that produces a weighted estimate and error bar interval.
Parameters
----------
estimator : string
Function (or method name) that maps a vector to a scalar. Currently
supports o... |
Data aggregator that produces a weighted estimate and error bar interval.
Parameters
----------
estimator : string
Function (or method name) that maps a vector to a scalar. Currently
supports only "mean".
errorbar : string or (string, number) tuple
... | __init__ | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def __init__(self, k_depth, outlier_prop, trust_alpha):
"""
Compute percentiles of a distribution using various tail stopping rules.
Parameters
----------
k_depth: "tukey", "proportion", "trustworthy", or "full"
Stopping rule for choosing tail percentiled to show:
... |
Compute percentiles of a distribution using various tail stopping rules.
Parameters
----------
k_depth: "tukey", "proportion", "trustworthy", or "full"
Stopping rule for choosing tail percentiled to show:
- tukey: Show a similar number of outliers as in a conve... | __init__ | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def _percentile_interval(data, width):
"""Return a percentile interval from data of a given width."""
edge = (100 - width) / 2
percentiles = edge, 100 - edge
return np.nanpercentile(data, percentiles) | Return a percentile interval from data of a given width. | _percentile_interval | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def _validate_errorbar_arg(arg):
"""Check type and value of errorbar argument and assign default level."""
DEFAULT_LEVELS = {
"ci": 95,
"pi": 95,
"se": 1,
"sd": 1,
}
usage = "`errorbar` must be a callable, string, or (string, number) tuple"
if arg is None:
r... | Check type and value of errorbar argument and assign default level. | _validate_errorbar_arg | python | mwaskom/seaborn | seaborn/_statistics.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py | BSD-3-Clause |
def _get_win_folder_from_registry(csidl_name):
"""This is a fallback technique at best. I'm not sure if using the
registry for this guarantees us the correct answer for all CSIDL_*
names.
"""
import winreg as _winreg
shell_folder_name = {
"CSIDL_APPDATA": "AppData",
"CSIDL_COMMO... | This is a fallback technique at best. I'm not sure if using the
registry for this guarantees us the correct answer for all CSIDL_*
names.
| _get_win_folder_from_registry | python | mwaskom/seaborn | seaborn/external/appdirs.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/external/appdirs.py | BSD-3-Clause |
def strip_blank_lines(l):
"Remove leading and trailing blank lines from a list of lines"
while l and not l[0].strip():
del l[0]
while l and not l[-1].strip():
del l[-1]
return l | Remove leading and trailing blank lines from a list of lines | strip_blank_lines | python | mwaskom/seaborn | seaborn/external/docscrape.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/external/docscrape.py | BSD-3-Clause |
def __init__(self, data):
"""
Parameters
----------
data : str
String with lines separated by '\n'.
"""
if isinstance(data, list):
self._str = data
else:
self._str = data.split('\n') # store string as list of lines
sel... |
Parameters
----------
data : str
String with lines separated by '
'.
| __init__ | python | mwaskom/seaborn | seaborn/external/docscrape.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/external/docscrape.py | BSD-3-Clause |
def _parse_see_also(self, content):
"""
func_name : Descriptive text
continued text
another_func_name : Descriptive text
func_name1, func_name2, :meth:`func_name`, func_name3
"""
items = []
def parse_item_name(text):
"""Match ':role:`nam... |
func_name : Descriptive text
continued text
another_func_name : Descriptive text
func_name1, func_name2, :meth:`func_name`, func_name3
| _parse_see_also | python | mwaskom/seaborn | seaborn/external/docscrape.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/external/docscrape.py | BSD-3-Clause |
def _parse_summary(self):
"""Grab signature (if given) and summary"""
if self._is_at_section():
return
# If several signatures present, take the last one
while True:
summary = self._doc.read_to_next_empty_line()
summary_str = " ".join([s.strip() for s... | Grab signature (if given) and summary | _parse_summary | python | mwaskom/seaborn | seaborn/external/docscrape.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/external/docscrape.py | BSD-3-Clause |
def evaluate(self, points):
"""Evaluate the estimated pdf on a set of points.
Parameters
----------
points : (# of dimensions, # of points)-array
Alternatively, a (# of dimensions,) vector can be passed in and
treated as a single point.
Returns
-... | Evaluate the estimated pdf on a set of points.
Parameters
----------
points : (# of dimensions, # of points)-array
Alternatively, a (# of dimensions,) vector can be passed in and
treated as a single point.
Returns
-------
values : (# of points,)-... | evaluate | python | mwaskom/seaborn | seaborn/external/kde.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/external/kde.py | BSD-3-Clause |
def set_bandwidth(self, bw_method=None):
"""Compute the estimator bandwidth with given method.
The new bandwidth calculated after a call to `set_bandwidth` is used
for subsequent evaluations of the estimated density.
Parameters
----------
bw_method : str, scalar or call... | Compute the estimator bandwidth with given method.
The new bandwidth calculated after a call to `set_bandwidth` is used
for subsequent evaluations of the estimated density.
Parameters
----------
bw_method : str, scalar or callable, optional
The method used to calcul... | set_bandwidth | python | mwaskom/seaborn | seaborn/external/kde.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/external/kde.py | BSD-3-Clause |
def _compute_covariance(self):
"""Computes the covariance matrix for each Gaussian kernel using
covariance_factor().
"""
self.factor = self.covariance_factor()
# Cache covariance and inverse covariance of the data
if not hasattr(self, '_data_inv_cov'):
self._d... | Computes the covariance matrix for each Gaussian kernel using
covariance_factor().
| _compute_covariance | python | mwaskom/seaborn | seaborn/external/kde.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/external/kde.py | BSD-3-Clause |
def __contains__(self, key: str) -> bool:
"""Boolean check on whether a variable is defined in this dataset."""
if self.frame is None:
return any(key in df for df in self.frames.values())
return key in self.frame | Boolean check on whether a variable is defined in this dataset. | __contains__ | python | mwaskom/seaborn | seaborn/_core/data.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/data.py | BSD-3-Clause |
def join(
self,
data: DataSource,
variables: dict[str, VariableSpec] | None,
) -> PlotData:
"""Add, replace, or drop variables and return as a new dataset."""
# Inherit the original source of the upstream data by default
if data is None:
data = self.source... | Add, replace, or drop variables and return as a new dataset. | join | python | mwaskom/seaborn | seaborn/_core/data.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/data.py | BSD-3-Clause |
def _assign_variables(
self,
data: DataFrame | Mapping | None,
variables: dict[str, VariableSpec],
) -> tuple[DataFrame, dict[str, str | None], dict[str, str | int]]:
"""
Assign values for plot variables given long-form data and/or vector inputs.
Parameters
-... |
Assign values for plot variables given long-form data and/or vector inputs.
Parameters
----------
data
Input data where variable names map to vector values.
variables
Keys are names of plot variables (x, y, ...) each value is one of:
- name ... | _assign_variables | python | mwaskom/seaborn | seaborn/_core/data.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/data.py | BSD-3-Clause |
def handle_data_source(data: object) -> pd.DataFrame | Mapping | None:
"""Convert the data source object to a common union representation."""
if isinstance(data, pd.DataFrame) or hasattr(data, "__dataframe__"):
# Check for pd.DataFrame inheritance could be removed once
# minimal pandas version s... | Convert the data source object to a common union representation. | handle_data_source | python | mwaskom/seaborn | seaborn/_core/data.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/data.py | BSD-3-Clause |
def convert_dataframe_to_pandas(data: object) -> pd.DataFrame:
"""Use the DataFrame exchange protocol, or fail gracefully."""
if isinstance(data, pd.DataFrame):
return data
if not hasattr(pd.api, "interchange"):
msg = (
"Support for non-pandas DataFrame objects requires a versio... | Use the DataFrame exchange protocol, or fail gracefully. | convert_dataframe_to_pandas | python | mwaskom/seaborn | seaborn/_core/data.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/data.py | BSD-3-Clause |
def _during(cls, step: str, var: str = "") -> PlotSpecError:
"""
Initialize the class to report the failure of a specific operation.
"""
message = []
if var:
message.append(f"{step} failed for the `{var}` variable.")
else:
message.append(f"{step} f... |
Initialize the class to report the failure of a specific operation.
| _during | python | mwaskom/seaborn | seaborn/_core/exceptions.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/exceptions.py | BSD-3-Clause |
def __init__(self, order: list[str] | dict[str, list | None]):
"""
Initialize the GroupBy from grouping variables and optional level orders.
Parameters
----------
order
List of variable names or dict mapping names to desired level orders.
Level order valu... |
Initialize the GroupBy from grouping variables and optional level orders.
Parameters
----------
order
List of variable names or dict mapping names to desired level orders.
Level order values can be None to use default ordering rules. The
variables ca... | __init__ | python | mwaskom/seaborn | seaborn/_core/groupby.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/groupby.py | BSD-3-Clause |
def _get_groups(
self, data: DataFrame
) -> tuple[str | list[str], Index | MultiIndex]:
"""Return index with Cartesian product of ordered grouping variable levels."""
levels = {}
for var, order in self.order.items():
if var in data:
if order is None:
... | Return index with Cartesian product of ordered grouping variable levels. | _get_groups | python | mwaskom/seaborn | seaborn/_core/groupby.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/groupby.py | BSD-3-Clause |
def _reorder_columns(self, res, data):
"""Reorder result columns to match original order with new columns appended."""
cols = [c for c in data if c in res]
cols += [c for c in res if c not in data]
return res.reindex(columns=pd.Index(cols)) | Reorder result columns to match original order with new columns appended. | _reorder_columns | python | mwaskom/seaborn | seaborn/_core/groupby.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/groupby.py | BSD-3-Clause |
def agg(self, data: DataFrame, *args, **kwargs) -> DataFrame:
"""
Reduce each group to a single row in the output.
The output will have a row for each unique combination of the grouping
variable levels with null values for the aggregated variable(s) where
those combinations do n... |
Reduce each group to a single row in the output.
The output will have a row for each unique combination of the grouping
variable levels with null values for the aggregated variable(s) where
those combinations do not appear in the dataset.
| agg | python | mwaskom/seaborn | seaborn/_core/groupby.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/groupby.py | BSD-3-Clause |
def apply(
self, data: DataFrame, func: Callable[..., DataFrame],
*args, **kwargs,
) -> DataFrame:
"""Apply a DataFrame -> DataFrame mapping to each group."""
grouper, groups = self._get_groups(data)
if not grouper:
return self._reorder_columns(func(data, *args, ... | Apply a DataFrame -> DataFrame mapping to each group. | apply | python | mwaskom/seaborn | seaborn/_core/groupby.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/groupby.py | BSD-3-Clause |
def build_plot_signature(cls):
"""
Decorator function for giving Plot a useful signature.
Currently this mostly saves us some duplicated typing, but we would
like eventually to have a way of registering new semantic properties,
at which point dynamic signature generation would become more important... |
Decorator function for giving Plot a useful signature.
Currently this mostly saves us some duplicated typing, but we would
like eventually to have a way of registering new semantic properties,
at which point dynamic signature generation would become more important.
| build_plot_signature | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def update(self, other: dict[str, Any] | None = None, /, **kwds):
"""Update the theme with a dictionary or keyword arguments of rc parameters."""
if other is not None:
theme = self._filter_params(other)
else:
theme = {}
theme.update(kwds)
super().update(th... | Update the theme with a dictionary or keyword arguments of rc parameters. | update | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def _resolve_positionals(
self,
args: tuple[DataSource | VariableSpec, ...],
data: DataSource,
variables: dict[str, VariableSpec],
) -> tuple[DataSource, dict[str, VariableSpec]]:
"""Handle positional arguments, which may contain data / x / y."""
if len(args) > 3:
... | Handle positional arguments, which may contain data / x / y. | _resolve_positionals | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def _clone(self) -> Plot:
"""Generate a new object with the same information as the current spec."""
new = Plot()
# TODO any way to enforce that data does not get mutated?
new._data = self._data
new._layers.extend(self._layers)
new._scales.update(self._scales)
... | Generate a new object with the same information as the current spec. | _clone | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def on(self, target: Axes | SubFigure | Figure) -> Plot:
"""
Provide existing Matplotlib figure or axes for drawing the plot.
When using this method, you will also need to explicitly call a method that
triggers compilation, such as :meth:`Plot.show` or :meth:`Plot.save`. If you
... |
Provide existing Matplotlib figure or axes for drawing the plot.
When using this method, you will also need to explicitly call a method that
triggers compilation, such as :meth:`Plot.show` or :meth:`Plot.save`. If you
want to postprocess using matplotlib, you'd need to call :meth:`Plot... | on | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def add(
self,
mark: Mark,
*transforms: Stat | Move,
orient: str | None = None,
legend: bool = True,
label: str | None = None,
data: DataSource = None,
**variables: VariableSpec,
) -> Plot:
"""
Specify a layer of the visualization in te... |
Specify a layer of the visualization in terms of mark and data transform(s).
This is the main method for specifying how the data should be visualized.
It can be called multiple times with different arguments to define
a plot with multiple layers.
Parameters
----------
... | add | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def pair(
self,
x: VariableSpecList = None,
y: VariableSpecList = None,
wrap: int | None = None,
cross: bool = True,
) -> Plot:
"""
Produce subplots by pairing multiple `x` and/or `y` variables.
Parameters
----------
x, y : sequence(s)... |
Produce subplots by pairing multiple `x` and/or `y` variables.
Parameters
----------
x, y : sequence(s) of data vectors or identifiers
Variables that will define the grid of subplots.
wrap : int
When using only `x` or `y`, "wrap" subplots across a two-di... | pair | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def facet(
self,
col: VariableSpec = None,
row: VariableSpec = None,
order: OrderSpec | dict[str, OrderSpec] = None,
wrap: int | None = None,
) -> Plot:
"""
Produce subplots with conditional subsets of the data.
Parameters
----------
c... |
Produce subplots with conditional subsets of the data.
Parameters
----------
col, row : data vectors or identifiers
Variables used to define subsets along the columns and/or rows of the grid.
Can be references to the global data source passed in the constructor.... | facet | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def scale(self, **scales: Scale) -> Plot:
"""
Specify mappings from data units to visual properties.
Keywords correspond to variables defined in the plot, including coordinate
variables (`x`, `y`) and semantic variables (`color`, `pointsize`, etc.).
A number of "magic" argument... |
Specify mappings from data units to visual properties.
Keywords correspond to variables defined in the plot, including coordinate
variables (`x`, `y`) and semantic variables (`color`, `pointsize`, etc.).
A number of "magic" arguments are accepted, including:
- The name of ... | scale | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def label(
self, *,
title: str | None = None,
legend: str | None = None,
**variables: str | Callable[[str], str]
) -> Plot:
"""
Control the labels and titles for axes, legends, and subplots.
Additional keywords correspond to variables defined in the plot.
... |
Control the labels and titles for axes, legends, and subplots.
Additional keywords correspond to variables defined in the plot.
Values can be one of the following types:
- string (used literally; pass "" to clear the default label)
- function (called on the default label)
... | label | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def layout(
self,
*,
size: tuple[float, float] | Default = default,
engine: str | None | Default = default,
extent: tuple[float, float, float, float] | Default = default,
) -> Plot:
"""
Control the figure size and layout.
.. note::
Defaul... |
Control the figure size and layout.
.. note::
Default figure sizes and the API for specifying the figure size are subject
to change in future "experimental" releases of the objects API. The default
layout engine may also change.
Parameters
--------... | layout | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def theme(self, config: Mapping[str, Any], /) -> Plot:
"""
Control the appearance of elements in the plot.
.. note::
The API for customizing plot appearance is not yet finalized.
Currently, the only valid argument is a dict of matplotlib rc parameters.
(This... |
Control the appearance of elements in the plot.
.. note::
The API for customizing plot appearance is not yet finalized.
Currently, the only valid argument is a dict of matplotlib rc parameters.
(This dict must be passed as a positional argument.)
It is... | theme | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def save(self, loc, **kwargs) -> Plot:
"""
Compile the plot and write it to a buffer or file on disk.
Parameters
----------
loc : str, path, or buffer
Location on disk to save the figure, or a buffer to write into.
kwargs
Other keyword arguments a... |
Compile the plot and write it to a buffer or file on disk.
Parameters
----------
loc : str, path, or buffer
Location on disk to save the figure, or a buffer to write into.
kwargs
Other keyword arguments are passed through to
:meth:`matplotlib... | save | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def show(self, **kwargs) -> None:
"""
Compile the plot and display it by hooking into pyplot.
Calling this method is not necessary to render a plot in notebook context,
but it may be in other environments (e.g., in a terminal). After compiling the
plot, it calls :func:`matplotli... |
Compile the plot and display it by hooking into pyplot.
Calling this method is not necessary to render a plot in notebook context,
but it may be in other environments (e.g., in a terminal). After compiling the
plot, it calls :func:`matplotlib.pyplot.show` (passing any keyword parameter... | show | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def show(self, **kwargs) -> None:
"""
Display the plot by hooking into pyplot.
This method calls :func:`matplotlib.pyplot.show` with any keyword parameters.
"""
# TODO if we did not create the Plotter with pyplot, is it possible to do this?
# If not we should clearly ra... |
Display the plot by hooking into pyplot.
This method calls :func:`matplotlib.pyplot.show` with any keyword parameters.
| show | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def _update_legend_contents(
self,
p: Plot,
mark: Mark,
data: PlotData,
scales: dict[str, Scale],
layer_label: str | None,
) -> None:
"""Add legend artists / labels for one layer in the plot."""
if data.frame.empty and data.frames:
legend_v... | Add legend artists / labels for one layer in the plot. | _update_legend_contents | python | mwaskom/seaborn | seaborn/_core/plot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/plot.py | BSD-3-Clause |
def __init__(self, variable: str | None = None):
"""Initialize the property with the name of the corresponding plot variable."""
if not variable:
variable = self.__class__.__name__.lower()
self.variable = variable | Initialize the property with the name of the corresponding plot variable. | __init__ | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def default_scale(self, data: Series) -> Scale:
"""Given data, initialize appropriate scale class."""
var_type = variable_type(data, boolean_type="boolean", strict_boolean=True)
if var_type == "numeric":
return Continuous()
elif var_type == "datetime":
return Tem... | Given data, initialize appropriate scale class. | default_scale | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def infer_scale(self, arg: Any, data: Series) -> Scale:
"""Given data and a scaling argument, initialize appropriate scale class."""
# TODO put these somewhere external for validation
# TODO putting this here won't pick it up if subclasses define infer_scale
# (e.g. color). How best to h... | Given data and a scaling argument, initialize appropriate scale class. | infer_scale | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def get_mapping(self, scale: Scale, data: Series) -> Mapping:
"""Return a function that maps from data domain to property range."""
def identity(x):
return x
return identity | Return a function that maps from data domain to property range. | get_mapping | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def _check_dict_entries(self, levels: list, values: dict) -> None:
"""Input check when values are provided as a dictionary."""
missing = set(levels) - set(values)
if missing:
formatted = ", ".join(map(repr, sorted(missing, key=str)))
err = f"No entry in {self.variable} di... | Input check when values are provided as a dictionary. | _check_dict_entries | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def _get_nominal_mapping(self, scale: Nominal, data: Series) -> Mapping:
"""Identify evenly-spaced values using interval or explicit mapping."""
levels = categorical_order(data, scale.order)
values = self._get_values(scale, levels)
def mapping(x):
ixs = np.asarray(x, np.intp... | Identify evenly-spaced values using interval or explicit mapping. | _get_nominal_mapping | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def _get_values(self, scale: Scale, levels: list) -> list:
"""Validate scale.values and identify a value for each level."""
if isinstance(scale.values, dict):
self._check_dict_entries(levels, scale.values)
values = [scale.values[x] for x in levels]
elif isinstance(scale.v... | Validate scale.values and identify a value for each level. | _get_values | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def default_range(self) -> tuple[float, float]:
"""Min and max values used by default for semantic mapping."""
base = mpl.rcParams["lines.linewidth"]
return base * .5, base * 2 | Min and max values used by default for semantic mapping. | default_range | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def get_mapping(self, scale: Scale, data: Series) -> Mapping:
"""Define mapping as lookup into list of object values."""
boolean_scale = isinstance(scale, Boolean)
order = getattr(scale, "order", [True, False] if boolean_scale else None)
levels = categorical_order(data, order)
va... | Define mapping as lookup into list of object values. | get_mapping | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def _default_values(self, n: int) -> list[MarkerStyle]:
"""Build an arbitrarily long list of unique marker styles.
Parameters
----------
n : int
Number of unique marker specs to generate.
Returns
-------
markers : list of string or tuples
... | Build an arbitrarily long list of unique marker styles.
Parameters
----------
n : int
Number of unique marker specs to generate.
Returns
-------
markers : list of string or tuples
Values for defining :class:`matplotlib.markers.MarkerStyle` object... | _default_values | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def _default_values(self, n: int) -> list[DashPatternWithOffset]:
"""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 tu... | 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
... | _default_values | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def _get_dash_pattern(style: str | DashPattern) -> DashPatternWithOffset:
"""Convert linestyle arguments to dash pattern with offset."""
# Copied and modified from Matplotlib 3.4
# go from short hand -> full strings
ls_mapper = {"-": "solid", "--": "dashed", "-.": "dashdot", ":": "dotted... | Convert linestyle arguments to dash pattern with offset. | _get_dash_pattern | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def _standardize_color_sequence(self, colors: ArrayLike) -> ArrayLike:
"""Convert color sequence to RGB(A) array, preserving but not adding alpha."""
def has_alpha(x):
return to_rgba(x) != to_rgba(x, 1)
if isinstance(colors, np.ndarray):
needs_alpha = colors.shape[1] == ... | Convert color sequence to RGB(A) array, preserving but not adding alpha. | _standardize_color_sequence | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def get_mapping(self, scale: Scale, data: Series) -> Mapping:
"""Return a function that maps from data domain to color values."""
# TODO what is best way to do this conditional?
# Should it be class-based or should classes have behavioral attributes?
if isinstance(scale, Nominal):
... | Return a function that maps from data domain to color values. | get_mapping | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def _default_values(self, n: int) -> list:
"""Return a list of n values, alternating True and False."""
if n > 2:
msg = " ".join([
f"The variable assigned to {self.variable} has more than two levels,",
f"so {self.variable} values will cycle and may be uninterp... | Return a list of n values, alternating True and False. | _default_values | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def get_mapping(self, scale: Scale, data: Series) -> Mapping:
"""Return a function that maps each data value to True or False."""
boolean_scale = isinstance(scale, Boolean)
order = getattr(scale, "order", [True, False] if boolean_scale else None)
levels = categorical_order(data, order)
... | Return a function that maps each data value to True or False. | get_mapping | python | mwaskom/seaborn | seaborn/_core/properties.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/properties.py | BSD-3-Clause |
def variable_type(
vector: Series,
boolean_type: Literal["numeric", "categorical", "boolean"] = "numeric",
strict_boolean: bool = False,
) -> VarType:
"""
Determine whether a vector contains numeric, categorical, or datetime data.
This function differs from the pandas typing API in a few ways:
... |
Determine whether a vector contains numeric, categorical, or datetime data.
This function differs from the pandas typing API in a few 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 ca... | variable_type | python | mwaskom/seaborn | seaborn/_core/rules.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/rules.py | BSD-3-Clause |
def categorical_order(vector: Series, order: list | None = None) -> list:
"""
Return a list of unique data values using seaborn's ordering rules.
Parameters
----------
vector : Series
Vector of "categorical" values
order : list
Desired order of category levels to override the or... |
Return a list of unique data values using seaborn's ordering rules.
Parameters
----------
vector : Series
Vector of "categorical" values
order : list
Desired order of category levels to override the order determined
from the `data` object.
Returns
-------
order... | categorical_order | python | mwaskom/seaborn | seaborn/_core/rules.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/rules.py | BSD-3-Clause |
def tick(self, locator: Locator | None = None) -> Nominal:
"""
Configure the selection of ticks for the scale's axis or legend.
.. note::
This API is under construction and will be enhanced over time.
At the moment, it is probably not very useful.
Parameters
... |
Configure the selection of ticks for the scale's axis or legend.
.. note::
This API is under construction and will be enhanced over time.
At the moment, it is probably not very useful.
Parameters
----------
locator : :class:`matplotlib.ticker.Locator` s... | tick | python | mwaskom/seaborn | seaborn/_core/scales.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/scales.py | BSD-3-Clause |
def label(self, formatter: Formatter | None = None) -> Nominal:
"""
Configure the selection of labels for the scale's axis or legend.
.. note::
This API is under construction and will be enhanced over time.
At the moment, it is probably not very useful.
Paramete... |
Configure the selection of labels for the scale's axis or legend.
.. note::
This API is under construction and will be enhanced over time.
At the moment, it is probably not very useful.
Parameters
----------
formatter : :class:`matplotlib.ticker.Formatt... | label | python | mwaskom/seaborn | seaborn/_core/scales.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/scales.py | BSD-3-Clause |
def label(
self,
formatter: Formatter | None = None, *,
like: str | Callable | None = None,
base: int | None | Default = default,
unit: str | None = None,
) -> Continuous:
"""
Configure the appearance of tick labels for the scale's axis or legend.
Par... |
Configure the appearance of tick labels for the scale's axis or legend.
Parameters
----------
formatter : :class:`matplotlib.ticker.Formatter` subclass
Pre-configured formatter to use; other parameters will be ignored.
like : str or callable
Either a for... | label | python | mwaskom/seaborn | seaborn/_core/scales.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/scales.py | BSD-3-Clause |
def tick(
self, locator: Locator | None = None, *,
upto: int | None = None,
) -> Temporal:
"""
Configure the selection of ticks for the scale's axis or legend.
.. note::
This API is under construction and will be enhanced over time.
Parameters
--... |
Configure the selection of ticks for the scale's axis or legend.
.. note::
This API is under construction and will be enhanced over time.
Parameters
----------
locator : :class:`matplotlib.ticker.Locator` subclass
Pre-configured matplotlib locator; othe... | tick | python | mwaskom/seaborn | seaborn/_core/scales.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/scales.py | BSD-3-Clause |
def label(
self,
formatter: Formatter | None = None, *,
concise: bool = False,
) -> Temporal:
"""
Configure the appearance of tick labels for the scale's axis or legend.
.. note::
This API is under construction and will be enhanced over time.
Par... |
Configure the appearance of tick labels for the scale's axis or legend.
.. note::
This API is under construction and will be enhanced over time.
Parameters
----------
formatter : :class:`matplotlib.ticker.Formatter` subclass
Pre-configured formatter to ... | label | python | mwaskom/seaborn | seaborn/_core/scales.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/scales.py | BSD-3-Clause |
def update_units(self, x):
"""Pass units to the internal converter, potentially updating its mapping."""
self.converter = mpl.units.registry.get_converter(x)
if self.converter is not None:
self.converter.default_units(x, self)
info = self.converter.axisinfo(self.units, s... | Pass units to the internal converter, potentially updating its mapping. | update_units | python | mwaskom/seaborn | seaborn/_core/scales.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/scales.py | BSD-3-Clause |
def convert_units(self, x):
"""Return a numeric representation of the input data."""
if np.issubdtype(np.asarray(x).dtype, np.number):
return x
elif self.converter is None:
return x
return self.converter.convert(x, self.units, self) | Return a numeric representation of the input data. | convert_units | python | mwaskom/seaborn | seaborn/_core/scales.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/scales.py | BSD-3-Clause |
def _check_dimension_uniqueness(
self, facet_spec: FacetSpec, pair_spec: PairSpec
) -> None:
"""Reject specs that pair and facet on (or wrap to) same figure dimension."""
err = None
facet_vars = facet_spec.get("variables", {})
if facet_spec.get("wrap") and {"col", "row"} <=... | Reject specs that pair and facet on (or wrap to) same figure dimension. | _check_dimension_uniqueness | python | mwaskom/seaborn | seaborn/_core/subplots.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/subplots.py | BSD-3-Clause |
def _determine_grid_dimensions(
self, facet_spec: FacetSpec, pair_spec: PairSpec
) -> None:
"""Parse faceting and pairing information to define figure structure."""
self.grid_dimensions: dict[str, list] = {}
for dim, axis in zip(["col", "row"], ["x", "y"]):
facet_vars = ... | Parse faceting and pairing information to define figure structure. | _determine_grid_dimensions | python | mwaskom/seaborn | seaborn/_core/subplots.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/subplots.py | BSD-3-Clause |
def _handle_wrapping(
self, facet_spec: FacetSpec, pair_spec: PairSpec
) -> None:
"""Update figure structure parameters based on facet/pair wrapping."""
self.wrap = wrap = facet_spec.get("wrap") or pair_spec.get("wrap")
if not wrap:
return
wrap_dim = "row" if sel... | Update figure structure parameters based on facet/pair wrapping. | _handle_wrapping | python | mwaskom/seaborn | seaborn/_core/subplots.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/subplots.py | BSD-3-Clause |
def _determine_axis_sharing(self, pair_spec: PairSpec) -> None:
"""Update subplot spec with default or specified axis sharing parameters."""
axis_to_dim = {"x": "col", "y": "row"}
key: str
val: str | bool
for axis in "xy":
key = f"share{axis}"
# Always use... | Update subplot spec with default or specified axis sharing parameters. | _determine_axis_sharing | python | mwaskom/seaborn | seaborn/_core/subplots.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/subplots.py | BSD-3-Clause |
def init_figure(
self,
pair_spec: PairSpec,
pyplot: bool = False,
figure_kws: dict | None = None,
target: Axes | Figure | SubFigure | None = None,
) -> Figure:
"""Initialize matplotlib objects and add seaborn-relevant metadata."""
# TODO reduce need to pass pa... | Initialize matplotlib objects and add seaborn-relevant metadata. | init_figure | python | mwaskom/seaborn | seaborn/_core/subplots.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_core/subplots.py | BSD-3-Clause |
def __init__(
self,
val: Any = None,
depend: str | None = None,
rc: str | None = None,
auto: bool = False,
grouping: bool = True,
):
"""
Property that can be mapped from data or set directly, with flexible defaults.
Parameters
--------... |
Property that can be mapped from data or set directly, with flexible defaults.
Parameters
----------
val : Any
Use this value as the default.
depend : str
Use the value of this feature as the default.
rc : str
Use the value of this rc... | __init__ | python | mwaskom/seaborn | seaborn/_marks/base.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_marks/base.py | BSD-3-Clause |
def __repr__(self):
"""Nice formatting for when object appears in Mark init signature."""
if self._val is not None:
s = f"<{repr(self._val)}>"
elif self._depend is not None:
s = f"<depend:{self._depend}>"
elif self._rc is not None:
s = f"<rc:{self._rc}... | Nice formatting for when object appears in Mark init signature. | __repr__ | python | mwaskom/seaborn | seaborn/_marks/base.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_marks/base.py | BSD-3-Clause |
def default(self) -> Any:
"""Get the default value for this feature, or access the relevant rcParam."""
if self._val is not None:
return self._val
elif self._rc is not None:
return mpl.rcParams.get(self._rc) | Get the default value for this feature, or access the relevant rcParam. | default | python | mwaskom/seaborn | seaborn/_marks/base.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_marks/base.py | BSD-3-Clause |
def _resolve(
self,
data: DataFrame | dict[str, Any],
name: str,
scales: dict[str, Scale] | None = None,
) -> Any:
"""Obtain default, specified, or mapped value for a named feature.
Parameters
----------
data : DataFrame or dict with scalar values
... | Obtain default, specified, or mapped value for a named feature.
Parameters
----------
data : DataFrame or dict with scalar values
Container with data values for features that will be semantically mapped.
name : string
Identity of the feature / semantic.
s... | _resolve | python | mwaskom/seaborn | seaborn/_marks/base.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_marks/base.py | BSD-3-Clause |
def resolve_color(
mark: Mark,
data: DataFrame | dict,
prefix: str = "",
scales: dict[str, Scale] | None = None,
) -> RGBATuple | ndarray:
"""
Obtain a default, specified, or mapped value for a color feature.
This method exists separately to support the relationship between a
color and ... |
Obtain a default, specified, or mapped value for a color feature.
This method exists separately to support the relationship between a
color and its corresponding alpha. We want to respect alpha values that
are passed in specified (or mapped) color values but also make use of a
separate `alpha` var... | resolve_color | python | mwaskom/seaborn | seaborn/_marks/base.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_marks/base.py | BSD-3-Clause |
def visible(x, axis=None):
"""Detect "invisible" colors to set alpha appropriately."""
# TODO First clause only needed to handle non-rgba arrays,
# which we are trying to handle upstream
return np.array(x).dtype.kind != "f" or np.isfinite(x).all(axis) | Detect "invisible" colors to set alpha appropriately. | visible | python | mwaskom/seaborn | seaborn/_marks/base.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_marks/base.py | BSD-3-Clause |
def _check_param_one_of(self, param: str, options: Iterable[Any]) -> None:
"""Raise when parameter value is not one of a specified set."""
value = getattr(self, param)
if value not in options:
*most, last = options
option_str = ", ".join(f"{x!r}" for x in most[:-1]) + f" ... | Raise when parameter value is not one of a specified set. | _check_param_one_of | python | mwaskom/seaborn | seaborn/_stats/base.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_stats/base.py | BSD-3-Clause |
def _check_grouping_vars(
self, param: str, data_vars: list[str], stacklevel: int = 2,
) -> None:
"""Warn if vars are named in parameter without being present in the data."""
param_vars = getattr(self, param)
undefined = set(param_vars) - set(data_vars)
if undefined:
... | Warn if vars are named in parameter without being present in the data. | _check_grouping_vars | python | mwaskom/seaborn | seaborn/_stats/base.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_stats/base.py | BSD-3-Clause |
def __call__(
self,
data: DataFrame,
groupby: GroupBy,
orient: str,
scales: dict[str, Scale],
) -> DataFrame:
"""Apply statistical transform to data subgroups and return combined result."""
return data | Apply statistical transform to data subgroups and return combined result. | __call__ | python | mwaskom/seaborn | seaborn/_stats/base.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_stats/base.py | BSD-3-Clause |
def _check_var_list_or_boolean(self, param: str, grouping_vars: Any) -> None:
"""Do input checks on grouping parameters."""
value = getattr(self, param)
if not (
isinstance(value, bool)
or (isinstance(value, list) and all(isinstance(v, str) for v in value))
):
... | Do input checks on grouping parameters. | _check_var_list_or_boolean | python | mwaskom/seaborn | seaborn/_stats/density.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_stats/density.py | BSD-3-Clause |
def _get_support(self, data: DataFrame, orient: str) -> ndarray:
"""Define the grid that the KDE will be evaluated on."""
if self.gridsize is None:
return data[orient].to_numpy()
kde = self._fit(data, orient)
bw = np.sqrt(kde.covariance.squeeze())
gridmin = data[orie... | Define the grid that the KDE will be evaluated on. | _get_support | python | mwaskom/seaborn | seaborn/_stats/density.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_stats/density.py | BSD-3-Clause |
def _fit_and_evaluate(
self, data: DataFrame, orient: str, support: ndarray
) -> DataFrame:
"""Transform single group by fitting a KDE and evaluating on a support grid."""
empty = pd.DataFrame(columns=[orient, "weight", "density"], dtype=float)
if len(data) < 2:
return em... | Transform single group by fitting a KDE and evaluating on a support grid. | _fit_and_evaluate | python | mwaskom/seaborn | seaborn/_stats/density.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_stats/density.py | BSD-3-Clause |
def _transform(
self, data: DataFrame, orient: str, grouping_vars: list[str]
) -> DataFrame:
"""Transform multiple groups by fitting KDEs and evaluating."""
empty = pd.DataFrame(columns=[*data.columns, "density"], dtype=float)
if len(data) < 2:
return empty
try:
... | Transform multiple groups by fitting KDEs and evaluating. | _transform | python | mwaskom/seaborn | seaborn/_stats/density.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/_stats/density.py | BSD-3-Clause |
def test_bootstrap(random):
"""Test that bootstrapping gives the right answer in dumb cases."""
a_ones = np.ones(10)
n_boot = 5
out1 = algo.bootstrap(a_ones, n_boot=n_boot)
assert_array_equal(out1, np.ones(n_boot))
out2 = algo.bootstrap(a_ones, n_boot=n_boot, func=np.median)
assert_array_equ... | Test that bootstrapping gives the right answer in dumb cases. | test_bootstrap | python | mwaskom/seaborn | tests/test_algorithms.py | https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py | BSD-3-Clause |
def test_bootstrap_length(random):
"""Test that we get a bootstrap array of the right shape."""
a_norm = np.random.randn(1000)
out = algo.bootstrap(a_norm)
assert len(out) == 10000
n_boot = 100
out = algo.bootstrap(a_norm, n_boot=n_boot)
assert len(out) == n_boot | Test that we get a bootstrap array of the right shape. | test_bootstrap_length | python | mwaskom/seaborn | tests/test_algorithms.py | https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py | BSD-3-Clause |
def test_bootstrap_range(random):
"""Test that bootstrapping a random array stays within the right range."""
a_norm = np.random.randn(1000)
amin, amax = a_norm.min(), a_norm.max()
out = algo.bootstrap(a_norm)
assert amin <= out.min()
assert amax >= out.max() | Test that bootstrapping a random array stays within the right range. | test_bootstrap_range | python | mwaskom/seaborn | tests/test_algorithms.py | https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py | BSD-3-Clause |
def test_bootstrap_multiarg(random):
"""Test that bootstrap works with multiple input arrays."""
x = np.vstack([[1, 10] for i in range(10)])
y = np.vstack([[5, 5] for i in range(10)])
def f(x, y):
return np.vstack((x, y)).max(axis=0)
out_actual = algo.bootstrap(x, y, n_boot=2, func=f)
... | Test that bootstrap works with multiple input arrays. | test_bootstrap_multiarg | python | mwaskom/seaborn | tests/test_algorithms.py | https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py | BSD-3-Clause |
def test_bootstrap_axis(random):
"""Test axis kwarg to bootstrap function."""
x = np.random.randn(10, 20)
n_boot = 100
out_default = algo.bootstrap(x, n_boot=n_boot)
assert out_default.shape == (n_boot,)
out_axis = algo.bootstrap(x, n_boot=n_boot, axis=0)
assert out_axis.shape, (n_boot, x.... | Test axis kwarg to bootstrap function. | test_bootstrap_axis | python | mwaskom/seaborn | tests/test_algorithms.py | https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py | BSD-3-Clause |
def test_bootstrap_seed(random):
"""Test that we can get reproducible resamples by seeding the RNG."""
data = np.random.randn(50)
seed = 42
boots1 = algo.bootstrap(data, seed=seed)
boots2 = algo.bootstrap(data, seed=seed)
assert_array_equal(boots1, boots2) | Test that we can get reproducible resamples by seeding the RNG. | test_bootstrap_seed | python | mwaskom/seaborn | tests/test_algorithms.py | https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py | BSD-3-Clause |
def test_bootstrap_ols(random):
"""Test bootstrap of OLS model fit."""
def ols_fit(X, y):
XtXinv = np.linalg.inv(np.dot(X.T, X))
return XtXinv.dot(X.T).dot(y)
X = np.column_stack((np.random.randn(50, 4), np.ones(50)))
w = [2, 4, 0, 3, 5]
y_noisy = np.dot(X, w) + np.random.randn(50) ... | Test bootstrap of OLS model fit. | test_bootstrap_ols | python | mwaskom/seaborn | tests/test_algorithms.py | https://github.com/mwaskom/seaborn/blob/master/tests/test_algorithms.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.