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 poisson_disc_sample(array_radius, pad_radius, candidates=100, d=2, seed=None):
"""Find positions using poisson-disc sampling."""
# See http://bost.ocks.org/mike/algorithms/
rng = np.random.default_rng(seed)
uniform = rng.uniform
randint = rng.integers
# Cache the results
key = array_rad... | Find positions using poisson-disc sampling. | poisson_disc_sample | python | mwaskom/seaborn | doc/tools/generate_logos.py | https://github.com/mwaskom/seaborn/blob/master/doc/tools/generate_logos.py | BSD-3-Clause |
def strip_output(nb):
"""
Strip the outputs, execution count/prompt number and miscellaneous
metadata from a notebook object, unless specified to keep either the
outputs or counts.
"""
keys = {'metadata': [], 'cell': {'metadata': ["execution"]}}
nb.metadata.pop('signature', None)
nb.met... |
Strip the outputs, execution count/prompt number and miscellaneous
metadata from a notebook object, unless specified to keep either the
outputs or counts.
| strip_output | python | mwaskom/seaborn | doc/tools/nb_to_doc.py | https://github.com/mwaskom/seaborn/blob/master/doc/tools/nb_to_doc.py | BSD-3-Clause |
def bootstrap(*args, **kwargs):
"""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 itera... | 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
... | bootstrap | python | mwaskom/seaborn | seaborn/algorithms.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/algorithms.py | BSD-3-Clause |
def set(self, **kwargs):
"""Set attributes on each subplot Axes."""
for ax in self.axes.flat:
if ax is not None: # Handle removed axes
ax.set(**kwargs)
return self | Set attributes on each subplot Axes. | set | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def savefig(self, *args, **kwargs):
"""
Save an image of the plot.
This wraps :meth:`matplotlib.figure.Figure.savefig`, using bbox_inches="tight"
by default. Parameters are passed through to the matplotlib function.
"""
kwargs = kwargs.copy()
kwargs.setdefault("... |
Save an image of the plot.
This wraps :meth:`matplotlib.figure.Figure.savefig`, using bbox_inches="tight"
by default. Parameters are passed through to the matplotlib function.
| savefig | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def tight_layout(self, *args, **kwargs):
"""Call fig.tight_layout within rect that exclude the legend."""
kwargs = kwargs.copy()
kwargs.setdefault("rect", self._tight_layout_rect)
if self._tight_layout_pad is not None:
kwargs.setdefault("pad", self._tight_layout_pad)
... | Call fig.tight_layout within rect that exclude the legend. | tight_layout | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def add_legend(self, legend_data=None, title=None, label_order=None,
adjust_subtitles=False, **kwargs):
"""Draw a legend, maybe placing it outside axes and resizing the figure.
Parameters
----------
legend_data : dict
Dictionary mapping label names (or two... | 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... | add_legend | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _update_legend_data(self, ax):
"""Extract the legend data from an axes object and save it."""
data = {}
# Get data directly from the legend, which is necessary
# for newer functions that don't add labeled proxy artists
if ax.legend_ is not None and self._extract_legend_handl... | Extract the legend data from an axes object and save it. | _update_legend_data | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _get_palette(self, data, hue, hue_order, palette):
"""Get a list of colors for the hue variable."""
if hue is None:
palette = color_palette(n_colors=1)
else:
hue_names = categorical_order(data[hue], hue_order)
n_colors = len(hue_names)
# By d... | Get a list of colors for the hue variable. | _get_palette | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def legend(self):
"""The :class:`matplotlib.legend.Legend` object, if present."""
try:
return self._legend
except AttributeError:
return None | The :class:`matplotlib.legend.Legend` object, if present. | legend | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def tick_params(self, axis='both', **kwargs):
"""Modify the ticks, tick labels, and gridlines.
Parameters
----------
axis : {'x', 'y', 'both'}
The axis on which to apply the formatting.
kwargs : keyword arguments
Additional keyword arguments to pass to
... | Modify the ticks, tick labels, and gridlines.
Parameters
----------
axis : {'x', 'y', 'both'}
The axis on which to apply the formatting.
kwargs : keyword arguments
Additional keyword arguments to pass to
:meth:`matplotlib.axes.Axes.tick_params`.
... | tick_params | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def facet_data(self):
"""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 d... | 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 ... | facet_data | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def map(self, func, *args, **kwargs):
"""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... | 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 facetin... | map | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def map_dataframe(self, func, *args, **kwargs):
"""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 v... | 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
----------
... | map_dataframe | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def facet_axis(self, row_i, col_j, modify_state=True):
"""Make the axis identified by these indices active and return it."""
# Calculate the actual indices of the axes to plot on
if self._col_wrap is not None:
ax = self.axes.flat[col_j]
else:
ax = self.axes[row_i... | Make the axis identified by these indices active and return it. | facet_axis | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def set_axis_labels(self, x_var=None, y_var=None, clear_inner=True, **kwargs):
"""Set axis labels on the left column and bottom row of the grid."""
if x_var is not None:
self._x_var = x_var
self.set_xlabels(x_var, clear_inner=clear_inner, **kwargs)
if y_var is not None:
... | Set axis labels on the left column and bottom row of the grid. | set_axis_labels | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def set_xlabels(self, label=None, clear_inner=True, **kwargs):
"""Label the x axis on the bottom row of the grid."""
if label is None:
label = self._x_var
for ax in self._bottom_axes:
ax.set_xlabel(label, **kwargs)
if clear_inner:
for ax in self._not_b... | Label the x axis on the bottom row of the grid. | set_xlabels | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def set_ylabels(self, label=None, clear_inner=True, **kwargs):
"""Label the y axis on the left column of the grid."""
if label is None:
label = self._y_var
for ax in self._left_axes:
ax.set_ylabel(label, **kwargs)
if clear_inner:
for ax in self._not_le... | Label the y axis on the left column of the grid. | set_ylabels | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def set_xticklabels(self, labels=None, step=None, **kwargs):
"""Set x axis tick labels of the grid."""
for ax in self.axes.flat:
curr_ticks = ax.get_xticks()
ax.set_xticks(curr_ticks)
if labels is None:
curr_labels = [label.get_text() for label in ax.g... | Set x axis tick labels of the grid. | set_xticklabels | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def set_yticklabels(self, labels=None, **kwargs):
"""Set y axis tick labels on the left column of the grid."""
for ax in self.axes.flat:
curr_ticks = ax.get_yticks()
ax.set_yticks(curr_ticks)
if labels is None:
curr_labels = [label.get_text() for label... | Set y axis tick labels on the left column of the grid. | set_yticklabels | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def set_titles(self, template=None, row_template=None, col_template=None, **kwargs):
"""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} (... | 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... | set_titles | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def refline(self, *, x=None, y=None, color='.5', linestyle='--', **line_kws):
"""Add a reference line(s) to each facet.
Parameters
----------
x, y : numeric
Value(s) to draw the line(s) at.
color : :mod:`matplotlib color <matplotlib.colors>`
Specifies the... | Add a reference line(s) to each facet.
Parameters
----------
x, y : numeric
Value(s) to draw the line(s) at.
color : :mod:`matplotlib color <matplotlib.colors>`
Specifies the color of the reference line(s). Pass ``color=None`` to
use ``hue`` mapping.
... | refline | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def ax(self):
"""The :class:`matplotlib.axes.Axes` when no faceting variables are assigned."""
if self.axes.shape == (1, 1):
return self.axes[0, 0]
else:
err = (
"Use the `.axes` attribute when facet variables are assigned."
)
raise... | The :class:`matplotlib.axes.Axes` when no faceting variables are assigned. | ax | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _inner_axes(self):
"""Return a flat array of the inner axes."""
if self._col_wrap is None:
return self.axes[:-1, 1:].flat
else:
axes = []
n_empty = self._nrow * self._ncol - self._n_facets
for i, ax in enumerate(self.axes):
appe... | Return a flat array of the inner axes. | _inner_axes | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _left_axes(self):
"""Return a flat array of the left column of axes."""
if self._col_wrap is None:
return self.axes[:, 0].flat
else:
axes = []
for i, ax in enumerate(self.axes):
if not i % self._ncol:
axes.append(ax)
... | Return a flat array of the left column of axes. | _left_axes | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _not_left_axes(self):
"""Return a flat array of axes that aren't on the left column."""
if self._col_wrap is None:
return self.axes[:, 1:].flat
else:
axes = []
for i, ax in enumerate(self.axes):
if i % self._ncol:
axes.a... | Return a flat array of axes that aren't on the left column. | _not_left_axes | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _bottom_axes(self):
"""Return a flat array of the bottom row of axes."""
if self._col_wrap is None:
return self.axes[-1, :].flat
else:
axes = []
n_empty = self._nrow * self._ncol - self._n_facets
for i, ax in enumerate(self.axes):
... | Return a flat array of the bottom row of axes. | _bottom_axes | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _not_bottom_axes(self):
"""Return a flat array of axes that aren't on the bottom row."""
if self._col_wrap is None:
return self.axes[:-1, :].flat
else:
axes = []
n_empty = self._nrow * self._ncol - self._n_facets
for i, ax in enumerate(self.axe... | Return a flat array of axes that aren't on the bottom row. | _not_bottom_axes | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def __init__(
self, data, *, hue=None, vars=None, x_vars=None, y_vars=None,
hue_order=None, palette=None, hue_kws=None, corner=False, diag_sharey=True,
height=2.5, aspect=1, layout_pad=.5, despine=True, dropna=False,
):
"""Initialize the plot figure and PairGrid object.
Para... | 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 ... | __init__ | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def map(self, func, **kwargs):
"""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... | 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... | map | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def map_lower(self, func, **kwargs):
"""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... | 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 ``col... | map_lower | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def map_upper(self, func, **kwargs):
"""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... | 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 ``col... | map_upper | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def map_offdiag(self, func, **kwargs):
"""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... | 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... | map_offdiag | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def map_diag(self, func, **kwargs):
"""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... | 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`` ... | map_diag | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _map_diag_iter_hue(self, func, **kwargs):
"""Put marginal plot on each diagonal axes, iterating over hue."""
# Plot on each of the diagonal axes
fixed_color = kwargs.pop("color", None)
for var, ax in zip(self.diag_vars, self.diag_axes):
hue_grouped = self.data[var].group... | Put marginal plot on each diagonal axes, iterating over hue. | _map_diag_iter_hue | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _map_bivariate(self, func, indices, **kwargs):
"""Draw a bivariate plot on the indicated axes."""
# This is a hack to handle the fact that new distribution plots don't add
# their artists onto the axes. This is probably superior in general, but
# we'll need a better way to handle it ... | Draw a bivariate plot on the indicated axes. | _map_bivariate | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _plot_bivariate(self, x_var, y_var, ax, func, **kwargs):
"""Draw a bivariate plot on the specified axes."""
if "hue" not in signature(func).parameters:
self._plot_bivariate_iter_hue(x_var, y_var, ax, func, **kwargs)
return
kwargs = kwargs.copy()
if str(func._... | Draw a bivariate plot on the specified axes. | _plot_bivariate | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _plot_bivariate_iter_hue(self, x_var, y_var, ax, func, **kwargs):
"""Draw a bivariate plot while iterating over hue subsets."""
kwargs = kwargs.copy()
if str(func.__module__).startswith("seaborn"):
kwargs["ax"] = ax
else:
plt.sca(ax)
if x_var == y_var... | Draw a bivariate plot while iterating over hue subsets. | _plot_bivariate_iter_hue | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _add_axis_labels(self):
"""Add labels to the left and bottom Axes."""
for ax, label in zip(self.axes[-1, :], self.x_vars):
ax.set_xlabel(label)
for ax, label in zip(self.axes[:, 0], self.y_vars):
ax.set_ylabel(label) | Add labels to the left and bottom Axes. | _add_axis_labels | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _find_numeric_cols(self, data):
"""Find which variables in a DataFrame are numeric."""
numeric_cols = []
for col in data:
if variable_type(data[col]) == "numeric":
numeric_cols.append(col)
return numeric_cols | Find which variables in a DataFrame are numeric. | _find_numeric_cols | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _inject_kwargs(self, func, kws, params):
"""Add params to kws if they are accepted by func."""
func_params = signature(func).parameters
for key, val in params.items():
if key in func_params:
kws.setdefault(key, val) | Add params to kws if they are accepted by func. | _inject_kwargs | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def plot(self, joint_func, marginal_func, **kwargs):
"""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` direct... | 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
-------... | plot | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def plot_joint(self, func, **kwargs):
"""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 ... | 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 i... | plot_joint | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def plot_marginals(self, func, **kwargs):
"""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 ... | 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 ... | plot_marginals | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def refline(
self, *, x=None, y=None, joint=True, marginal=True,
color='.5', linestyle='--', **line_kws
):
"""Add a reference line(s) to joint and/or marginal axes.
Parameters
----------
x, y : numeric
Value(s) to draw the line(s) at.
joint, margi... | Add a reference line(s) to joint and/or marginal axes.
Parameters
----------
x, y : numeric
Value(s) to draw the line(s) at.
joint, marginal : bools
Whether to add the reference line(s) to the joint/marginal axes.
color : :mod:`matplotlib color <matplotli... | refline | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def set_axis_labels(self, xlabel="", ylabel="", **kwargs):
"""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 t... | 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... | set_axis_labels | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def pairplot(
data, *,
hue=None, hue_order=None, palette=None,
vars=None, x_vars=None, y_vars=None,
kind="scatter", diag_kind="auto", markers=None,
height=2.5, aspect=1, corner=False, dropna=False,
plot_kws=None, diag_kws=None, grid_kws=None, size=None,
):
"""Plot pairwise relationships in a... | 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 pl... | pairplot | python | mwaskom/seaborn | seaborn/axisgrid.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py | BSD-3-Clause |
def _hue_backcompat(self, color, palette, hue_order, force_hue=False):
"""Implement backwards compatibility for hue parametrization.
Note: the force_hue parameter is used so that functions can be shown to
pass existing tests during refactoring and then tested for new behavior.
It can be... | Implement backwards compatibility for hue parametrization.
Note: the force_hue parameter is used so that functions can be shown to
pass existing tests during refactoring and then tested for new behavior.
It can be removed after completion of the work.
| _hue_backcompat | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def _palette_without_hue_backcompat(self, palette, hue_order):
"""Provide one cycle where palette= implies hue= when not provided"""
if "hue" not in self.variables and palette is not None:
msg = (
"\n\nPassing `palette` without assigning `hue` is deprecated "
... | Provide one cycle where palette= implies hue= when not provided | _palette_without_hue_backcompat | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def _point_kwargs_backcompat(self, scale, join, kwargs):
"""Provide two cycles where scale= and join= work, but redirect to kwargs."""
if scale is not deprecated:
lw = mpl.rcParams["lines.linewidth"] * 1.8 * scale
mew = lw * .75
ms = lw * 2
msg = (
... | Provide two cycles where scale= and join= work, but redirect to kwargs. | _point_kwargs_backcompat | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def _err_kws_backcompat(self, err_kws, errcolor, errwidth, capsize):
"""Provide two cycles where existing signature-level err_kws are handled."""
def deprecate_err_param(name, key, val):
if val is deprecated:
return
suggest = f"err_kws={{'{key}': {val!r}}}"
... | Provide two cycles where existing signature-level err_kws are handled. | _err_kws_backcompat | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def _violin_scale_backcompat(self, scale, scale_hue, density_norm, common_norm):
"""Provide two cycles of backcompat for scale kwargs"""
if scale is not deprecated:
density_norm = scale
msg = (
"\n\nThe `scale` parameter has been renamed and will be removed "
... | Provide two cycles of backcompat for scale kwargs | _violin_scale_backcompat | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def _violin_bw_backcompat(self, bw, bw_method):
"""Provide two cycles of backcompat for violin bandwidth parameterization."""
if bw is not deprecated:
bw_method = bw
msg = dedent(f"""\n
The `bw` parameter is deprecated in favor of `bw_method`/`bw_adjust`.
... | Provide two cycles of backcompat for violin bandwidth parameterization. | _violin_bw_backcompat | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def _complement_color(self, color, base_color, hue_map):
"""Allow a color to be set automatically using a basis of comparison."""
if color == "gray":
msg = (
'Use "auto" to set automatic grayscale colors. From v0.14.0, '
'"gray" will default to matplotlib\'s d... | Allow a color to be set automatically using a basis of comparison. | _complement_color | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def _map_prop_with_hue(self, name, value, fallback, plot_kws):
"""Support pointplot behavior of modifying the marker/linestyle with hue."""
if value is default:
value = plot_kws.pop(name, fallback)
if "hue" in self.variables:
levels = self._hue_map.levels
if ... | Support pointplot behavior of modifying the marker/linestyle with hue. | _map_prop_with_hue | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def _dodge_needed(self):
"""Return True when use of `hue` would cause overlaps."""
groupers = list({self.orient, "col", "row"} & set(self.variables))
if "hue" in self.variables:
orient = self.plot_data[groupers].value_counts()
paired = self.plot_data[[*groupers, "hue"]].v... | Return True when use of `hue` would cause overlaps. | _dodge_needed | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def _dodge(self, keys, data):
"""Apply a dodge transform to coordinates in place."""
if "hue" not in self.variables:
# Short-circuit if hue variable was not assigned
# We could potentially warn when hue=None, dodge=True, user may be confused
# But I think it's fine to... | Apply a dodge transform to coordinates in place. | _dodge | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def _invert_scale(self, ax, data, vars=("x", "y")):
"""Undo scaling after computation so data are plotted correctly."""
for var in vars:
_, inv = _get_transform_functions(ax, var[0])
if var == self.orient and "width" in data:
hw = data["width"] / 2
... | Undo scaling after computation so data are plotted correctly. | _invert_scale | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def _native_width(self):
"""Return unit of width separating categories on native numeric scale."""
# Categorical data always have a unit width
if self.var_types[self.orient] == "categorical":
return 1
# Otherwise, define the width as the smallest space between observations
... | Return unit of width separating categories on native numeric scale. | _native_width | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def _nested_offsets(self, width, dodge):
"""Return offsets for each hue level for dodged plots."""
offsets = None
if "hue" in self.variables and self._hue_map.levels is not None:
n_levels = len(self._hue_map.levels)
if dodge:
each_width = width / n_levels
... | Return offsets for each hue level for dodged plots. | _nested_offsets | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def __call__(self, points, center):
"""Swarm `points`, a PathCollection, around the `center` position."""
# Convert from point size (area) to diameter
ax = points.axes
dpi = ax.figure.dpi
# Get the original positions of the points
orig_xy_data = points.get_offsets()
... | Swarm `points`, a PathCollection, around the `center` position. | __call__ | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def beeswarm(self, orig_xyr):
"""Adjust x position of points to avoid overlaps."""
# In this method, `x` is always the categorical axis
# Center of the swarm, in point coordinates
midline = orig_xyr[0, 0]
# Start the swarm with the first point
swarm = np.atleast_2d(orig_... | Adjust x position of points to avoid overlaps. | beeswarm | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def could_overlap(self, xyr_i, swarm):
"""Return a list of all swarm points that could overlap with target."""
# Because we work backwards through the swarm and can short-circuit,
# the for-loop is faster than vectorization
_, y_i, r_i = xyr_i
neighbors = []
for xyr_j in ... | Return a list of all swarm points that could overlap with target. | could_overlap | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def position_candidates(self, xyr_i, neighbors):
"""Return a list of coordinates that might be valid by adjusting x."""
candidates = [xyr_i]
x_i, y_i, r_i = xyr_i
left_first = True
for x_j, y_j, r_j in neighbors:
dy = y_i - y_j
dx = np.sqrt(max((r_i + r_j)... | Return a list of coordinates that might be valid by adjusting x. | position_candidates | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def first_non_overlapping_candidate(self, candidates, neighbors):
"""Find the first candidate that does not overlap with the swarm."""
# If we have no neighbors, all candidates are good.
if len(neighbors) == 0:
return candidates[0]
neighbors_x = neighbors[:, 0]
neig... | Find the first candidate that does not overlap with the swarm. | first_non_overlapping_candidate | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def add_gutters(self, points, center, trans_fwd, trans_inv):
"""Stop points from extending beyond their territory."""
half_width = self.width / 2
low_gutter = trans_inv(trans_fwd(center) - half_width)
off_low = points < low_gutter
if off_low.any():
points[off_low] = l... | Stop points from extending beyond their territory. | add_gutters | python | mwaskom/seaborn | seaborn/categorical.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/categorical.py | BSD-3-Clause |
def univariate(self):
"""Return True if only x or y are used."""
# TODO this could go down to core, but putting it here now.
# We'd want to be conceptually clear that univariate only applies
# to x/y and not to other semantics, which can exist.
# We haven't settled on a good conc... | Return True if only x or y are used. | univariate | python | mwaskom/seaborn | seaborn/distributions.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/distributions.py | BSD-3-Clause |
def data_variable(self):
"""Return the variable with data for univariate plots."""
# TODO This could also be in core, but it should have a better name.
if not self.univariate:
raise AttributeError("This is not a univariate plot")
return {"x", "y"}.intersection(self.variables)... | Return the variable with data for univariate plots. | data_variable | python | mwaskom/seaborn | seaborn/distributions.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/distributions.py | BSD-3-Clause |
def has_xy_data(self):
"""Return True at least one of x or y is defined."""
# TODO see above points about where this should go
return bool({"x", "y"} & set(self.variables)) | Return True at least one of x or y is defined. | has_xy_data | python | mwaskom/seaborn | seaborn/distributions.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/distributions.py | BSD-3-Clause |
def _add_legend(
self,
ax_obj, artist, fill, element, multiple, alpha, artist_kws, legend_kws,
):
"""Add artists that reflect semantic mappings and put then in a legend."""
# TODO note that this doesn't handle numeric mappings like the relational plots
handles = []
la... | Add artists that reflect semantic mappings and put then in a legend. | _add_legend | python | mwaskom/seaborn | seaborn/distributions.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/distributions.py | BSD-3-Clause |
def _artist_kws(self, kws, fill, element, multiple, color, alpha):
"""Handle differences between artists in filled/unfilled plots."""
kws = kws.copy()
if fill:
kws = normalize_kwargs(kws, mpl.collections.PolyCollection)
kws.setdefault("facecolor", to_rgba(color, alpha))
... | Handle differences between artists in filled/unfilled plots. | _artist_kws | python | mwaskom/seaborn | seaborn/distributions.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/distributions.py | BSD-3-Clause |
def _quantile_to_level(self, data, quantile):
"""Return data levels corresponding to quantile cuts of mass."""
isoprop = np.asarray(quantile)
values = np.ravel(data)
sorted_values = np.sort(values)[::-1]
normalized_values = np.cumsum(sorted_values) / values.sum()
idx = np... | Return data levels corresponding to quantile cuts of mass. | _quantile_to_level | python | mwaskom/seaborn | seaborn/distributions.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/distributions.py | BSD-3-Clause |
def _cmap_from_color(self, color):
"""Return a sequential colormap given a color seed."""
# Like so much else here, this is broadly useful, but keeping it
# in this class to signify that I haven't thought overly hard about it...
r, g, b, _ = to_rgba(color)
h, s, _ = husl.rgb_to_h... | Return a sequential colormap given a color seed. | _cmap_from_color | python | mwaskom/seaborn | seaborn/distributions.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/distributions.py | BSD-3-Clause |
def _default_discrete(self):
"""Find default values for discrete hist estimation based on variable type."""
if self.univariate:
discrete = self.var_types[self.data_variable] == "categorical"
else:
discrete_x = self.var_types["x"] == "categorical"
discrete_y = ... | Find default values for discrete hist estimation based on variable type. | _default_discrete | python | mwaskom/seaborn | seaborn/distributions.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/distributions.py | BSD-3-Clause |
def _resolve_multiple(self, curves, multiple):
"""Modify the density data structure to handle multiple densities."""
# Default baselines have all densities starting at 0
baselines = {k: np.zeros_like(v) for k, v in curves.items()}
# TODO we should have some central clearinghouse for ch... | Modify the density data structure to handle multiple densities. | _resolve_multiple | python | mwaskom/seaborn | seaborn/distributions.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/distributions.py | BSD-3-Clause |
def _freedman_diaconis_bins(a):
"""Calculate number of hist bins using Freedman-Diaconis rule."""
# From https://stats.stackexchange.com/questions/798/
a = np.asarray(a)
if len(a) < 2:
return 1
iqr = np.subtract.reduce(np.nanpercentile(a, [75, 25]))
h = 2 * iqr / (len(a) ** (1 / 3))
... | Calculate number of hist bins using Freedman-Diaconis rule. | _freedman_diaconis_bins | python | mwaskom/seaborn | seaborn/distributions.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/distributions.py | BSD-3-Clause |
def distplot(a=None, bins=None, hist=True, kde=True, rug=False, fit=None,
hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None,
color=None, vertical=False, norm_hist=False, axlabel=None,
label=None, ax=None, x=None):
"""
DEPRECATED
This function has been deprecated... |
DEPRECATED
This function has been deprecated and will be removed in seaborn v0.14.0.
It has been replaced by :func:`histplot` and :func:`displot`, two functions
with a modern API and many more capabilities.
For a guide to updating, please see this notebook:
https://gist.github.com/mwaskom/de... | distplot | python | mwaskom/seaborn | seaborn/distributions.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/distributions.py | BSD-3-Clause |
def _index_to_label(index):
"""Convert a pandas index or multiindex to an axis label."""
if isinstance(index, pd.MultiIndex):
return "-".join(map(to_utf8, index.names))
else:
return index.name | Convert a pandas index or multiindex to an axis label. | _index_to_label | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def _index_to_ticklabels(index):
"""Convert a pandas index or multiindex into ticklabels."""
if isinstance(index, pd.MultiIndex):
return ["-".join(map(to_utf8, i)) for i in index.values]
else:
return index.values | Convert a pandas index or multiindex into ticklabels. | _index_to_ticklabels | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def _convert_colors(colors):
"""Convert either a list of colors or nested lists of colors to RGB."""
to_rgb = mpl.colors.to_rgb
try:
to_rgb(colors[0])
# If this works, there is only one level of colors
return list(map(to_rgb, colors))
except ValueError:
# If we get here,... | Convert either a list of colors or nested lists of colors to RGB. | _convert_colors | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def _matrix_mask(data, mask):
"""Ensure that data and mask are compatible and add missing values.
Values will be plotted for cells where ``mask`` is ``False``.
``data`` is expected to be a DataFrame; ``mask`` can be an array or
a DataFrame.
"""
if mask is None:
mask = np.zeros(data.sh... | Ensure that data and mask are compatible and add missing values.
Values will be plotted for cells where ``mask`` is ``False``.
``data`` is expected to be a DataFrame; ``mask`` can be an array or
a DataFrame.
| _matrix_mask | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def _determine_cmap_params(self, plot_data, vmin, vmax,
cmap, center, robust):
"""Use some heuristics to set good defaults for colorbar and range."""
# plot_data is a np.ma.array instance
calc_data = plot_data.astype(float).filled(np.nan)
if vmin is None:
... | Use some heuristics to set good defaults for colorbar and range. | _determine_cmap_params | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def _annotate_heatmap(self, ax, mesh):
"""Add textual labels with the value in each cell."""
mesh.update_scalarmappable()
height, width = self.annot_data.shape
xpos, ypos = np.meshgrid(np.arange(width) + .5, np.arange(height) + .5)
for x, y, m, color, val in zip(xpos.flat, ypos.f... | Add textual labels with the value in each cell. | _annotate_heatmap | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def _skip_ticks(self, labels, tickevery):
"""Return ticks and labels at evenly spaced intervals."""
n = len(labels)
if tickevery == 0:
ticks, labels = [], []
elif tickevery == 1:
ticks, labels = np.arange(n) + .5, labels
else:
start, end, step ... | Return ticks and labels at evenly spaced intervals. | _skip_ticks | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def _auto_ticks(self, ax, labels, axis):
"""Determine ticks and ticklabels that minimize overlap."""
transform = ax.figure.dpi_scale_trans.inverted()
bbox = ax.get_window_extent().transformed(transform)
size = [bbox.width, bbox.height][axis]
axis = [ax.xaxis, ax.yaxis][axis]
... | Determine ticks and ticklabels that minimize overlap. | _auto_ticks | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def plot(self, ax, cax, kws):
"""Draw the heatmap on the provided Axes."""
# Remove all the Axes spines
despine(ax=ax, left=True, bottom=True)
# setting vmin/vmax in addition to norm is deprecated
# so avoid setting if norm is set
if kws.get("norm") is None:
... | Draw the heatmap on the provided Axes. | plot | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def heatmap(
data, *,
vmin=None, vmax=None, cmap=None, center=None, robust=False,
annot=None, fmt=".2g", annot_kws=None,
linewidths=0, linecolor="white",
cbar=True, cbar_kws=None, cbar_ax=None,
square=False, xticklabels="auto", yticklabels="auto",
mask=None, ax=None,
**kwargs
):
"""P... | 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 provide... | heatmap | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def __init__(self, data, linkage, metric, method, axis, label, rotate):
"""Plot a dendrogram of the relationships between the columns of data
Parameters
----------
data : pandas.DataFrame
Rectangular data
"""
self.axis = axis
if self.axis == 1:
... | Plot a dendrogram of the relationships between the columns of data
Parameters
----------
data : pandas.DataFrame
Rectangular data
| __init__ | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def plot(self, ax, tree_kws):
"""Plots a dendrogram of the similarities between data on the axes
Parameters
----------
ax : matplotlib.axes.Axes
Axes object upon which the dendrogram is plotted
"""
tree_kws = {} if tree_kws is None else tree_kws.copy()
... | Plots a dendrogram of the similarities between data on the axes
Parameters
----------
ax : matplotlib.axes.Axes
Axes object upon which the dendrogram is plotted
| plot | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def dendrogram(
data, *,
linkage=None, axis=1, label=True, metric='euclidean',
method='average', rotate=False, tree_kws=None, ax=None
):
"""Draw a tree diagram of relationships within a matrix
Parameters
----------
data : pandas.DataFrame
Rectangular data
linkage : numpy.array, ... | 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... | dendrogram | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def __init__(self, data, pivot_kws=None, z_score=None, standard_scale=None,
figsize=None, row_colors=None, col_colors=None, mask=None,
dendrogram_ratio=None, colors_ratio=None, cbar_pos=None):
"""Grid object for organizing clustered heatmap input on to axes"""
if _no_sc... | Grid object for organizing clustered heatmap input on to axes | __init__ | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def _preprocess_colors(self, data, colors, axis):
"""Preprocess {row/col}_colors to extract labels and convert colors."""
labels = None
if colors is not None:
if isinstance(colors, (pd.DataFrame, pd.Series)):
# If data is unindexed, raise
if (not has... | Preprocess {row/col}_colors to extract labels and convert colors. | _preprocess_colors | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def format_data(self, data, pivot_kws, z_score=None,
standard_scale=None):
"""Extract variables from data or use directly."""
# Either the data is already in 2d matrix format, or need to do a pivot
if pivot_kws is not None:
data2d = data.pivot(**pivot_kws)
... | Extract variables from data or use directly. | format_data | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def z_score(data2d, axis=1):
"""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 ... | 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
------... | z_score | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def standard_scale(data2d, axis=1):
"""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,
no... | 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.
Returns
... | standard_scale | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def dim_ratios(self, colors, dendrogram_ratio, colors_ratio):
"""Get the proportions of the figure taken up by each axes."""
ratios = [dendrogram_ratio]
if colors is not None:
# Colors are encoded as rgb, so there is an extra dimension
if np.ndim(colors) > 2:
... | Get the proportions of the figure taken up by each axes. | dim_ratios | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def color_list_to_matrix_and_cmap(colors, ind, axis=0):
"""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 m... | 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... | color_list_to_matrix_and_cmap | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def plot_colors(self, xind, yind, **kws):
"""Plots color labels between the dendrogram and the heatmap
Parameters
----------
heatmap_kws : dict
Keyword arguments heatmap
"""
# Remove any custom colormap and centering
# TODO this code has consistently... | Plots color labels between the dendrogram and the heatmap
Parameters
----------
heatmap_kws : dict
Keyword arguments heatmap
| plot_colors | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def clustermap(
data, *,
pivot_kws=None, method='average', metric='euclidean',
z_score=None, standard_scale=None, figsize=(10, 10),
cbar_kws=None, row_cluster=True, col_cluster=True,
row_linkage=None, col_linkage=None,
row_colors=None, col_colors=None, mask=None,
dendrogram_ratio=.2, colors_... |
Plot a matrix dataset as a hierarchically-clustered heatmap.
This function requires scipy to be available.
Parameters
----------
data : 2D array-like
Rectangular data for clustering. Cannot contain NAs.
pivot_kws : dict, optional
If `data` is a tidy dataframe, can provide keyw... | clustermap | python | mwaskom/seaborn | seaborn/matrix.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/matrix.py | BSD-3-Clause |
def palplot(pal, size=1):
"""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
"""
n = len(pal)
_, ax = plt.subpl... | 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
| palplot | python | mwaskom/seaborn | seaborn/miscplot.py | https://github.com/mwaskom/seaborn/blob/master/seaborn/miscplot.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.