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 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 :meth:`matplotlib.axes.Axes.tick_params`. Returns ------- self : Grid instance Returns self for easy chaining. """ for ax in self.figure.axes: ax.tick_params(axis=axis, **kwargs) return self
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`. Returns ------- self : Grid instance Returns self for easy chaining.
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 data corresponding to each facet. The generator yields subsets that correspond with the self.axes.flat iterator, or self.axes[i, j] when `col_wrap` is None. """ data = self.data # Construct masks for the row variable if self.row_names: row_masks = [data[self._row_var] == n for n in self.row_names] else: row_masks = [np.repeat(True, len(self.data))] # Construct masks for the column variable if self.col_names: col_masks = [data[self._col_var] == n for n in self.col_names] else: col_masks = [np.repeat(True, len(self.data))] # Construct masks for the hue variable if self.hue_names: hue_masks = [data[self._hue_var] == n for n in self.hue_names] else: hue_masks = [np.repeat(True, len(self.data))] # Here is the main generator loop for (i, row), (j, col), (k, hue) in product(enumerate(row_masks), enumerate(col_masks), enumerate(hue_masks)): data_ijk = data[row & col & hue & self._not_na] yield (i, j, k), data_ijk
Generator for name indices and data subsets for each facet. Yields ------ (i, j, k), data_ijk : tuple of ints, DataFrame The ints provide an index into the {row, col, hue}_names attribute, and the dataframe contains a subset of the full data corresponding to each facet. The generator yields subsets that correspond with the self.axes.flat iterator, or self.axes[i, j] when `col_wrap` is None.
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 `color` keyword argument. If faceting on the `hue` dimension, it must also take a `label` keyword argument. args : strings Column names in self.data that identify variables with data to plot. The data for each variable is passed to `func` in the order the variables are specified in the call. kwargs : keyword arguments All keyword arguments are passed to the plotting function. Returns ------- self : object Returns self. """ # If color was a keyword argument, grab it here kw_color = kwargs.pop("color", None) # How we use the function depends on where it comes from func_module = str(getattr(func, "__module__", "")) # Check for categorical plots without order information if func_module == "seaborn.categorical": if "order" not in kwargs: warning = ("Using the {} function without specifying " "`order` is likely to produce an incorrect " "plot.".format(func.__name__)) warnings.warn(warning) if len(args) == 3 and "hue_order" not in kwargs: warning = ("Using the {} function without specifying " "`hue_order` is likely to produce an incorrect " "plot.".format(func.__name__)) warnings.warn(warning) # Iterate over the data subsets for (row_i, col_j, hue_k), data_ijk in self.facet_data(): # If this subset is null, move on if not data_ijk.values.size: continue # Get the current axis modify_state = not func_module.startswith("seaborn") ax = self.facet_axis(row_i, col_j, modify_state) # Decide what color to plot with kwargs["color"] = self._facet_color(hue_k, kw_color) # Insert the other hue aesthetics if appropriate for kw, val_list in self.hue_kws.items(): kwargs[kw] = val_list[hue_k] # Insert a label in the keyword arguments for the legend if self._hue_var is not None: kwargs["label"] = utils.to_utf8(self.hue_names[hue_k]) # Get the actual data we are going to plot with plot_data = data_ijk[list(args)] if self._dropna: plot_data = plot_data.dropna() plot_args = [v for k, v in plot_data.items()] # Some matplotlib functions don't handle pandas objects correctly if func_module.startswith("matplotlib"): plot_args = [v.values for v in plot_args] # Draw the plot self._facet_plot(func, ax, plot_args, kwargs) # Finalize the annotations and layout self._finalize_grid(args[:2]) return self
Apply a plotting function to each facet's subset of the data. Parameters ---------- func : callable A plotting function that takes data and keyword arguments. It must plot to the currently active matplotlib Axes and take a `color` keyword argument. If faceting on the `hue` dimension, it must also take a `label` keyword argument. args : strings Column names in self.data that identify variables with data to plot. The data for each variable is passed to `func` in the order the variables are specified in the call. kwargs : keyword arguments All keyword arguments are passed to the plotting function. Returns ------- self : object Returns self.
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 variable names. Parameters ---------- func : callable A plotting function that takes data and keyword arguments. Unlike the `map` method, a function used here must "understand" Pandas objects. It also must plot to the currently active matplotlib Axes and take a `color` keyword argument. If faceting on the `hue` dimension, it must also take a `label` keyword argument. args : strings Column names in self.data that identify variables with data to plot. The data for each variable is passed to `func` in the order the variables are specified in the call. kwargs : keyword arguments All keyword arguments are passed to the plotting function. Returns ------- self : object Returns self. """ # If color was a keyword argument, grab it here kw_color = kwargs.pop("color", None) # Iterate over the data subsets for (row_i, col_j, hue_k), data_ijk in self.facet_data(): # If this subset is null, move on if not data_ijk.values.size: continue # Get the current axis modify_state = not str(func.__module__).startswith("seaborn") ax = self.facet_axis(row_i, col_j, modify_state) # Decide what color to plot with kwargs["color"] = self._facet_color(hue_k, kw_color) # Insert the other hue aesthetics if appropriate for kw, val_list in self.hue_kws.items(): kwargs[kw] = val_list[hue_k] # Insert a label in the keyword arguments for the legend if self._hue_var is not None: kwargs["label"] = self.hue_names[hue_k] # Stick the facet dataframe into the kwargs if self._dropna: data_ijk = data_ijk.dropna() kwargs["data"] = data_ijk # Draw the plot self._facet_plot(func, ax, args, kwargs) # For axis labels, prefer to use positional args for backcompat # but also extract the x/y kwargs and use if no corresponding arg axis_labels = [kwargs.get("x", None), kwargs.get("y", None)] for i, val in enumerate(args[:2]): axis_labels[i] = val self._finalize_grid(axis_labels) return self
Like ``.map`` but passes args as strings and inserts data in kwargs. This method is suitable for plotting with functions that accept a long-form DataFrame as a `data` keyword argument and access the data in that DataFrame using string variable names. Parameters ---------- func : callable A plotting function that takes data and keyword arguments. Unlike the `map` method, a function used here must "understand" Pandas objects. It also must plot to the currently active matplotlib Axes and take a `color` keyword argument. If faceting on the `hue` dimension, it must also take a `label` keyword argument. args : strings Column names in self.data that identify variables with data to plot. The data for each variable is passed to `func` in the order the variables are specified in the call. kwargs : keyword arguments All keyword arguments are passed to the plotting function. Returns ------- self : object Returns self.
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, col_j] # Get a reference to the axes object we want, and make it active if modify_state: plt.sca(ax) return ax
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: self._y_var = y_var self.set_ylabels(y_var, clear_inner=clear_inner, **kwargs) return self
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_bottom_axes: ax.set_xlabel("") return self
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_left_axes: ax.set_ylabel("") return self
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.get_xticklabels()] if step is not None: xticks = ax.get_xticks()[::step] curr_labels = curr_labels[::step] ax.set_xticks(xticks) ax.set_xticklabels(curr_labels, **kwargs) else: ax.set_xticklabels(labels, **kwargs) return self
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 in ax.get_yticklabels()] ax.set_yticklabels(curr_labels, **kwargs) else: ax.set_yticklabels(labels, **kwargs) return self
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} (if using a `col` faceting variable) and/or {row_var} and {row_name} (if using a `row` faceting variable). row_template: Template for the row variable when titles are drawn on the grid margins. Must have {row_var} and {row_name} formatting keys. col_template: Template for the column variable when titles are drawn on the grid margins. Must have {col_var} and {col_name} formatting keys. Returns ------- self: object Returns self. """ args = dict(row_var=self._row_var, col_var=self._col_var) kwargs["size"] = kwargs.pop("size", mpl.rcParams["axes.labelsize"]) # Establish default templates if row_template is None: row_template = "{row_var} = {row_name}" if col_template is None: col_template = "{col_var} = {col_name}" if template is None: if self._row_var is None: template = col_template elif self._col_var is None: template = row_template else: template = " | ".join([row_template, col_template]) row_template = utils.to_utf8(row_template) col_template = utils.to_utf8(col_template) template = utils.to_utf8(template) if self._margin_titles: # Remove any existing title texts for text in self._margin_titles_texts: text.remove() self._margin_titles_texts = [] if self.row_names is not None: # Draw the row titles on the right edge of the grid for i, row_name in enumerate(self.row_names): ax = self.axes[i, -1] args.update(dict(row_name=row_name)) title = row_template.format(**args) text = ax.annotate( title, xy=(1.02, .5), xycoords="axes fraction", rotation=270, ha="left", va="center", **kwargs ) self._margin_titles_texts.append(text) if self.col_names is not None: # Draw the column titles as normal titles for j, col_name in enumerate(self.col_names): args.update(dict(col_name=col_name)) title = col_template.format(**args) self.axes[0, j].set_title(title, **kwargs) return self # Otherwise title each facet with all the necessary information if (self._row_var is not None) and (self._col_var is not None): for i, row_name in enumerate(self.row_names): for j, col_name in enumerate(self.col_names): args.update(dict(row_name=row_name, col_name=col_name)) title = template.format(**args) self.axes[i, j].set_title(title, **kwargs) elif self.row_names is not None and len(self.row_names): for i, row_name in enumerate(self.row_names): args.update(dict(row_name=row_name)) title = template.format(**args) self.axes[i, 0].set_title(title, **kwargs) elif self.col_names is not None and len(self.col_names): for i, col_name in enumerate(self.col_names): args.update(dict(col_name=col_name)) title = template.format(**args) # Index the flat array so col_wrap works self.axes.flat[i].set_title(title, **kwargs) return self
Draw titles either above each facet or on the grid margins. Parameters ---------- template : string Template for all titles with the formatting keys {col_var} and {col_name} (if using a `col` faceting variable) and/or {row_var} and {row_name} (if using a `row` faceting variable). row_template: Template for the row variable when titles are drawn on the grid margins. Must have {row_var} and {row_name} formatting keys. col_template: Template for the column variable when titles are drawn on the grid margins. Must have {col_var} and {col_name} formatting keys. Returns ------- self: object Returns self.
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 color of the reference line(s). Pass ``color=None`` to use ``hue`` mapping. linestyle : str Specifies the style of the reference line(s). line_kws : key, value mappings Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline` when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y`` is not None. Returns ------- :class:`FacetGrid` instance Returns ``self`` for easy method chaining. """ line_kws['color'] = color line_kws['linestyle'] = linestyle if x is not None: self.map(plt.axvline, x=x, **line_kws) if y is not None: self.map(plt.axhline, y=y, **line_kws) return self
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. linestyle : str Specifies the style of the reference line(s). line_kws : key, value mappings Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline` when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y`` is not None. Returns ------- :class:`FacetGrid` instance Returns ``self`` for easy method chaining.
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 AttributeError(err)
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): append = ( i % self._ncol and i < (self._ncol * (self._nrow - 1)) and i < (self._ncol * (self._nrow - 1) - n_empty) ) if append: axes.append(ax) return np.array(axes, object).flat
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 np.array(axes, object).flat
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.append(ax) return np.array(axes, object).flat
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): append = ( i >= (self._ncol * (self._nrow - 1)) or i >= (self._ncol * (self._nrow - 1) - n_empty) ) if append: axes.append(ax) return np.array(axes, object).flat
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.axes): append = ( i < (self._ncol * (self._nrow - 1)) and i < (self._ncol * (self._nrow - 1) - n_empty) ) if append: axes.append(ax) return np.array(axes, object).flat
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. Parameters ---------- data : DataFrame Tidy (long-form) dataframe where each column is a variable and each row is an observation. hue : string (variable name) Variable in ``data`` to map plot aspects to different colors. This variable will be excluded from the default x and y variables. vars : list of variable names Variables within ``data`` to use, otherwise use every column with a numeric datatype. {x, y}_vars : lists of variable names Variables within ``data`` to use separately for the rows and columns of the figure; i.e. to make a non-square plot. hue_order : list of strings Order for the levels of the hue variable in the palette palette : dict or seaborn color palette Set of colors for mapping the ``hue`` variable. If a dict, keys should be values in the ``hue`` variable. hue_kws : dictionary of param -> list of values mapping Other keyword arguments to insert into the plotting call to let other plot attributes vary across levels of the hue variable (e.g. the markers in a scatterplot). corner : bool If True, don't add axes to the upper (off-diagonal) triangle of the grid, making this a "corner" plot. height : scalar Height (in inches) of each facet. aspect : scalar Aspect * height gives the width (in inches) of each facet. layout_pad : scalar Padding between axes; passed to ``fig.tight_layout``. despine : boolean Remove the top and right spines from the plots. dropna : boolean Drop missing values from the data before plotting. See Also -------- pairplot : Easily drawing common uses of :class:`PairGrid`. FacetGrid : Subplot grid for plotting conditional relationships. Examples -------- .. include:: ../docstrings/PairGrid.rst """ super().__init__() data = handle_data_source(data) # Sort out the variables that define the grid numeric_cols = self._find_numeric_cols(data) if hue in numeric_cols: numeric_cols.remove(hue) if vars is not None: x_vars = list(vars) y_vars = list(vars) if x_vars is None: x_vars = numeric_cols if y_vars is None: y_vars = numeric_cols if np.isscalar(x_vars): x_vars = [x_vars] if np.isscalar(y_vars): y_vars = [y_vars] self.x_vars = x_vars = list(x_vars) self.y_vars = y_vars = list(y_vars) self.square_grid = self.x_vars == self.y_vars if not x_vars: raise ValueError("No variables found for grid columns.") if not y_vars: raise ValueError("No variables found for grid rows.") # Create the figure and the array of subplots figsize = len(x_vars) * height * aspect, len(y_vars) * height with _disable_autolayout(): fig = plt.figure(figsize=figsize) axes = fig.subplots(len(y_vars), len(x_vars), sharex="col", sharey="row", squeeze=False) # Possibly remove upper axes to make a corner grid # Note: setting up the axes is usually the most time-intensive part # of using the PairGrid. We are foregoing the speed improvement that # we would get by just not setting up the hidden axes so that we can # avoid implementing fig.subplots ourselves. But worth thinking about. self._corner = corner if corner: hide_indices = np.triu_indices_from(axes, 1) for i, j in zip(*hide_indices): axes[i, j].remove() axes[i, j] = None self._figure = fig self.axes = axes self.data = data # Save what we are going to do with the diagonal self.diag_sharey = diag_sharey self.diag_vars = None self.diag_axes = None self._dropna = dropna # Label the axes self._add_axis_labels() # Sort out the hue variable self._hue_var = hue if hue is None: self.hue_names = hue_order = ["_nolegend_"] self.hue_vals = pd.Series(["_nolegend_"] * len(data), index=data.index) else: # We need hue_order and hue_names because the former is used to control # the order of drawing and the latter is used to control the order of # the legend. hue_names can become string-typed while hue_order must # retain the type of the input data. This is messy but results from # the fact that PairGrid can implement the hue-mapping logic itself # (and was originally written exclusively that way) but now can delegate # to the axes-level functions, while always handling legend creation. # See GH2307 hue_names = hue_order = categorical_order(data[hue], hue_order) if dropna: # Filter NA from the list of unique hue names hue_names = list(filter(pd.notnull, hue_names)) self.hue_names = hue_names self.hue_vals = data[hue] # Additional dict of kwarg -> list of values for mapping the hue var self.hue_kws = hue_kws if hue_kws is not None else {} self._orig_palette = palette self._hue_order = hue_order self.palette = self._get_palette(data, hue, hue_order, palette) self._legend_data = {} # Make the plot look nice for ax in axes[:-1, :].flat: if ax is None: continue for label in ax.get_xticklabels(): label.set_visible(False) ax.xaxis.offsetText.set_visible(False) ax.xaxis.label.set_visible(False) for ax in axes[:, 1:].flat: if ax is None: continue for label in ax.get_yticklabels(): label.set_visible(False) ax.yaxis.offsetText.set_visible(False) ax.yaxis.label.set_visible(False) self._tight_layout_rect = [.01, .01, .99, .99] self._tight_layout_pad = layout_pad self._despine = despine if despine: utils.despine(fig=fig) self.tight_layout(pad=layout_pad)
Initialize the plot figure and PairGrid object. Parameters ---------- data : DataFrame Tidy (long-form) dataframe where each column is a variable and each row is an observation. hue : string (variable name) Variable in ``data`` to map plot aspects to different colors. This variable will be excluded from the default x and y variables. vars : list of variable names Variables within ``data`` to use, otherwise use every column with a numeric datatype. {x, y}_vars : lists of variable names Variables within ``data`` to use separately for the rows and columns of the figure; i.e. to make a non-square plot. hue_order : list of strings Order for the levels of the hue variable in the palette palette : dict or seaborn color palette Set of colors for mapping the ``hue`` variable. If a dict, keys should be values in the ``hue`` variable. hue_kws : dictionary of param -> list of values mapping Other keyword arguments to insert into the plotting call to let other plot attributes vary across levels of the hue variable (e.g. the markers in a scatterplot). corner : bool If True, don't add axes to the upper (off-diagonal) triangle of the grid, making this a "corner" plot. height : scalar Height (in inches) of each facet. aspect : scalar Aspect * height gives the width (in inches) of each facet. layout_pad : scalar Padding between axes; passed to ``fig.tight_layout``. despine : boolean Remove the top and right spines from the plots. dropna : boolean Drop missing values from the data before plotting. See Also -------- pairplot : Easily drawing common uses of :class:`PairGrid`. FacetGrid : Subplot grid for plotting conditional relationships. Examples -------- .. include:: ../docstrings/PairGrid.rst
__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 called ``color`` and ``label``. """ row_indices, col_indices = np.indices(self.axes.shape) indices = zip(row_indices.flat, col_indices.flat) self._map_bivariate(func, indices, **kwargs) return self
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 needs to accept kwargs called ``color`` and ``label``. """ indices = zip(*np.tril_indices_from(self.axes, -1)) self._map_bivariate(func, indices, **kwargs) return self
Plot with a bivariate function on the lower diagonal subplots. Parameters ---------- func : callable plotting function Must take x, y arrays as positional arguments and draw onto the "currently active" matplotlib Axes. Also needs to accept kwargs called ``color`` and ``label``.
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 needs to accept kwargs called ``color`` and ``label``. """ indices = zip(*np.triu_indices_from(self.axes, 1)) self._map_bivariate(func, indices, **kwargs) return self
Plot with a bivariate function on the upper diagonal subplots. Parameters ---------- func : callable plotting function Must take x, y arrays as positional arguments and draw onto the "currently active" matplotlib Axes. Also needs to accept kwargs called ``color`` and ``label``.
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 needs to accept kwargs called ``color`` and ``label``. """ if self.square_grid: self.map_lower(func, **kwargs) if not self._corner: self.map_upper(func, **kwargs) else: indices = [] for i, (y_var) in enumerate(self.y_vars): for j, (x_var) in enumerate(self.x_vars): if x_var != y_var: indices.append((i, j)) self._map_bivariate(func, indices, **kwargs) return self
Plot with a bivariate function on the off-diagonal subplots. Parameters ---------- func : callable plotting function Must take x, y arrays as positional arguments and draw onto the "currently active" matplotlib Axes. Also needs to accept kwargs called ``color`` and ``label``.
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 to accept kwargs called ``color`` and ``label``. """ # Add special diagonal axes for the univariate plot if self.diag_axes is None: diag_vars = [] diag_axes = [] for i, y_var in enumerate(self.y_vars): for j, x_var in enumerate(self.x_vars): if x_var == y_var: # Make the density axes diag_vars.append(x_var) ax = self.axes[i, j] diag_ax = ax.twinx() diag_ax.set_axis_off() diag_axes.append(diag_ax) # Work around matplotlib bug # https://github.com/matplotlib/matplotlib/issues/15188 if not plt.rcParams.get("ytick.left", True): for tick in ax.yaxis.majorTicks: tick.tick1line.set_visible(False) # Remove main y axis from density axes in a corner plot if self._corner: ax.yaxis.set_visible(False) if self._despine: utils.despine(ax=ax, left=True) # TODO add optional density ticks (on the right) # when drawing a corner plot? if self.diag_sharey and diag_axes: for ax in diag_axes[1:]: share_axis(diag_axes[0], ax, "y") self.diag_vars = diag_vars self.diag_axes = diag_axes if "hue" not in signature(func).parameters: return self._map_diag_iter_hue(func, **kwargs) # Loop over diagonal variables and axes, making one plot in each for var, ax in zip(self.diag_vars, self.diag_axes): plot_kwargs = kwargs.copy() if str(func.__module__).startswith("seaborn"): plot_kwargs["ax"] = ax else: plt.sca(ax) vector = self.data[var] if self._hue_var is not None: hue = self.data[self._hue_var] else: hue = None if self._dropna: not_na = vector.notna() if hue is not None: not_na &= hue.notna() vector = vector[not_na] if hue is not None: hue = hue[not_na] plot_kwargs.setdefault("hue", hue) plot_kwargs.setdefault("hue_order", self._hue_order) plot_kwargs.setdefault("palette", self._orig_palette) func(x=vector, **plot_kwargs) ax.legend_ = None self._add_axis_labels() return self
Plot with a univariate function on each diagonal subplot. Parameters ---------- func : callable plotting function Must take an x array as a positional argument and draw onto the "currently active" matplotlib Axes. Also needs to accept kwargs called ``color`` and ``label``.
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].groupby(self.hue_vals, observed=True) plot_kwargs = kwargs.copy() if str(func.__module__).startswith("seaborn"): plot_kwargs["ax"] = ax else: plt.sca(ax) for k, label_k in enumerate(self._hue_order): # Attempt to get data for this level, allowing for empty try: data_k = hue_grouped.get_group(label_k) except KeyError: data_k = pd.Series([], dtype=float) if fixed_color is None: color = self.palette[k] else: color = fixed_color if self._dropna: data_k = utils.remove_na(data_k) if str(func.__module__).startswith("seaborn"): func(x=data_k, label=label_k, color=color, **plot_kwargs) else: func(data_k, label=label_k, color=color, **plot_kwargs) self._add_axis_labels() return self
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 in the axisgrid functions. from .distributions import histplot, kdeplot if func is histplot or func is kdeplot: self._extract_legend_handles = True kws = kwargs.copy() # Use copy as we insert other kwargs for i, j in indices: x_var = self.x_vars[j] y_var = self.y_vars[i] ax = self.axes[i, j] if ax is None: # i.e. we are in corner mode continue self._plot_bivariate(x_var, y_var, ax, func, **kws) self._add_axis_labels() if "hue" in signature(func).parameters: self.hue_names = list(self._legend_data)
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.__module__).startswith("seaborn"): kwargs["ax"] = ax else: plt.sca(ax) if x_var == y_var: axes_vars = [x_var] else: axes_vars = [x_var, y_var] if self._hue_var is not None and self._hue_var not in axes_vars: axes_vars.append(self._hue_var) data = self.data[axes_vars] if self._dropna: data = data.dropna() x = data[x_var] y = data[y_var] if self._hue_var is None: hue = None else: hue = data.get(self._hue_var) if "hue" not in kwargs: kwargs.update({ "hue": hue, "hue_order": self._hue_order, "palette": self._orig_palette, }) func(x=x, y=y, **kwargs) self._update_legend_data(ax)
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: axes_vars = [x_var] else: axes_vars = [x_var, y_var] hue_grouped = self.data.groupby(self.hue_vals, observed=True) for k, label_k in enumerate(self._hue_order): kws = kwargs.copy() # Attempt to get data for this level, allowing for empty try: data_k = hue_grouped.get_group(label_k) except KeyError: data_k = pd.DataFrame(columns=axes_vars, dtype=float) if self._dropna: data_k = data_k[axes_vars].dropna() x = data_k[x_var] y = data_k[y_var] for kw, val_list in self.hue_kws.items(): kws[kw] = val_list[k] kws.setdefault("color", self.palette[k]) if self._hue_var is not None: kws["label"] = label_k if str(func.__module__).startswith("seaborn"): func(x=x, y=y, **kws) else: func(x, y, **kws) self._update_legend_data(ax)
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` directly with specific parameters. Parameters ---------- joint_func, marginal_func : callables Functions to draw the bivariate and univariate plots. See methods referenced above for information about the required characteristics of these functions. kwargs Additional keyword arguments are passed to both functions. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining. """ self.plot_marginals(marginal_func, **kwargs) self.plot_joint(joint_func, **kwargs) return self
Draw the plot by passing functions for joint and marginal axes. This method passes the ``kwargs`` dictionary to both functions. If you need more control, call :meth:`JointGrid.plot_joint` and :meth:`JointGrid.plot_marginals` directly with specific parameters. Parameters ---------- joint_func, marginal_func : callables Functions to draw the bivariate and univariate plots. See methods referenced above for information about the required characteristics of these functions. kwargs Additional keyword arguments are passed to both functions. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining.
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 first two positional arguments, and it must plot on the "current" axes. If ``hue`` was defined in the class constructor, the function must accept ``hue`` as a parameter. kwargs Keyword argument are passed to the plotting function. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining. """ kwargs = kwargs.copy() if str(func.__module__).startswith("seaborn"): kwargs["ax"] = self.ax_joint else: plt.sca(self.ax_joint) if self.hue is not None: kwargs["hue"] = self.hue self._inject_kwargs(func, kwargs, self._hue_params) if str(func.__module__).startswith("seaborn"): func(x=self.x, y=self.y, **kwargs) else: func(self.x, self.y, **kwargs) return self
Draw a bivariate plot on the joint axes of the grid. Parameters ---------- func : plotting callable If a seaborn function, it should accept ``x`` and ``y``. Otherwise, it must accept ``x`` and ``y`` vectors of data as the first two positional arguments, and it must plot on the "current" axes. If ``hue`` was defined in the class constructor, the function must accept ``hue`` as a parameter. kwargs Keyword argument are passed to the plotting function. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining.
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 a vector of data as the first positional argument and determine its orientation using the ``vertical`` parameter, and it must plot on the "current" axes. If ``hue`` was defined in the class constructor, it must accept ``hue`` as a parameter. kwargs Keyword argument are passed to the plotting function. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining. """ seaborn_func = ( str(func.__module__).startswith("seaborn") # deprecated distplot has a legacy API, special case it and not func.__name__ == "distplot" ) func_params = signature(func).parameters kwargs = kwargs.copy() if self.hue is not None: kwargs["hue"] = self.hue self._inject_kwargs(func, kwargs, self._hue_params) if "legend" in func_params: kwargs.setdefault("legend", False) if "orientation" in func_params: # e.g. plt.hist orient_kw_x = {"orientation": "vertical"} orient_kw_y = {"orientation": "horizontal"} elif "vertical" in func_params: # e.g. sns.distplot (also how did this get backwards?) orient_kw_x = {"vertical": False} orient_kw_y = {"vertical": True} if seaborn_func: func(x=self.x, ax=self.ax_marg_x, **kwargs) else: plt.sca(self.ax_marg_x) func(self.x, **orient_kw_x, **kwargs) if seaborn_func: func(y=self.y, ax=self.ax_marg_y, **kwargs) else: plt.sca(self.ax_marg_y) func(self.y, **orient_kw_y, **kwargs) self.ax_marg_x.yaxis.get_label().set_visible(False) self.ax_marg_y.xaxis.get_label().set_visible(False) return self
Draw univariate plots on each marginal axes. Parameters ---------- func : plotting callable If a seaborn function, it should accept ``x`` and ``y`` and plot when only one of them is defined. Otherwise, it must accept a vector of data as the first positional argument and determine its orientation using the ``vertical`` parameter, and it must plot on the "current" axes. If ``hue`` was defined in the class constructor, it must accept ``hue`` as a parameter. kwargs Keyword argument are passed to the plotting function. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining.
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, marginal : bools Whether to add the reference line(s) to the joint/marginal axes. color : :mod:`matplotlib color <matplotlib.colors>` Specifies the color of the reference line(s). linestyle : str Specifies the style of the reference line(s). line_kws : key, value mappings Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline` when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y`` is not None. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining. """ line_kws['color'] = color line_kws['linestyle'] = linestyle if x is not None: if joint: self.ax_joint.axvline(x, **line_kws) if marginal: self.ax_marg_x.axvline(x, **line_kws) if y is not None: if joint: self.ax_joint.axhline(y, **line_kws) if marginal: self.ax_marg_y.axhline(y, **line_kws) return self
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 <matplotlib.colors>` Specifies the color of the reference line(s). linestyle : str Specifies the style of the reference line(s). line_kws : key, value mappings Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline` when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y`` is not None. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining.
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 the following functions: - :meth:`matplotlib.axes.Axes.set_xlabel` - :meth:`matplotlib.axes.Axes.set_ylabel` Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining. """ self.ax_joint.set_xlabel(xlabel, **kwargs) self.ax_joint.set_ylabel(ylabel, **kwargs) return self
Set axis labels on the bivariate axes. Parameters ---------- xlabel, ylabel : strings Label names for the x and y variables. kwargs : key, value mappings Other keyword arguments are passed to the following functions: - :meth:`matplotlib.axes.Axes.set_xlabel` - :meth:`matplotlib.axes.Axes.set_ylabel` Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining.
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 dataset. By default, this function will create a grid of Axes such that each numeric variable in ``data`` will by shared across the y-axes across a single row and the x-axes across a single column. The diagonal plots are treated differently: a univariate distribution plot is drawn to show the marginal distribution of the data in each column. It is also possible to show a subset of variables or plot different variables on the rows and columns. This is a high-level interface for :class:`PairGrid` that is intended to make it easy to draw a few common styles. You should use :class:`PairGrid` directly if you need more flexibility. Parameters ---------- data : `pandas.DataFrame` Tidy (long-form) dataframe where each column is a variable and each row is an observation. hue : name of variable in ``data`` Variable in ``data`` to map plot aspects to different colors. hue_order : list of strings Order for the levels of the hue variable in the palette palette : dict or seaborn color palette Set of colors for mapping the ``hue`` variable. If a dict, keys should be values in the ``hue`` variable. vars : list of variable names Variables within ``data`` to use, otherwise use every column with a numeric datatype. {x, y}_vars : lists of variable names Variables within ``data`` to use separately for the rows and columns of the figure; i.e. to make a non-square plot. kind : {'scatter', 'kde', 'hist', 'reg'} Kind of plot to make. diag_kind : {'auto', 'hist', 'kde', None} Kind of plot for the diagonal subplots. If 'auto', choose based on whether or not ``hue`` is used. markers : single matplotlib marker code or list Either the marker to use for all scatterplot points or a list of markers with a length the same as the number of levels in the hue variable so that differently colored points will also have different scatterplot markers. height : scalar Height (in inches) of each facet. aspect : scalar Aspect * height gives the width (in inches) of each facet. corner : bool If True, don't add axes to the upper (off-diagonal) triangle of the grid, making this a "corner" plot. dropna : boolean Drop missing values from the data before plotting. {plot, diag, grid}_kws : dicts Dictionaries of keyword arguments. ``plot_kws`` are passed to the bivariate plotting function, ``diag_kws`` are passed to the univariate plotting function, and ``grid_kws`` are passed to the :class:`PairGrid` constructor. Returns ------- grid : :class:`PairGrid` Returns the underlying :class:`PairGrid` instance for further tweaking. See Also -------- PairGrid : Subplot grid for more flexible plotting of pairwise relationships. JointGrid : Grid for plotting joint and marginal distributions of two variables. Examples -------- .. include:: ../docstrings/pairplot.rst """ # Avoid circular import from .distributions import histplot, kdeplot # Handle deprecations if size is not None: height = size msg = ("The `size` parameter has been renamed to `height`; " "please update your code.") warnings.warn(msg, UserWarning) if not isinstance(data, pd.DataFrame): raise TypeError( f"'data' must be pandas DataFrame object, not: {type(data)}") plot_kws = {} if plot_kws is None else plot_kws.copy() diag_kws = {} if diag_kws is None else diag_kws.copy() grid_kws = {} if grid_kws is None else grid_kws.copy() # Resolve "auto" diag kind if diag_kind == "auto": if hue is None: diag_kind = "kde" if kind == "kde" else "hist" else: diag_kind = "hist" if kind == "hist" else "kde" # Set up the PairGrid grid_kws.setdefault("diag_sharey", diag_kind == "hist") grid = PairGrid(data, vars=vars, x_vars=x_vars, y_vars=y_vars, hue=hue, hue_order=hue_order, palette=palette, corner=corner, height=height, aspect=aspect, dropna=dropna, **grid_kws) # Add the markers here as PairGrid has figured out how many levels of the # hue variable are needed and we don't want to duplicate that process if markers is not None: if kind == "reg": # Needed until regplot supports style if grid.hue_names is None: n_markers = 1 else: n_markers = len(grid.hue_names) if not isinstance(markers, list): markers = [markers] * n_markers if len(markers) != n_markers: raise ValueError("markers must be a singleton or a list of " "markers for each level of the hue variable") grid.hue_kws = {"marker": markers} elif kind == "scatter": if isinstance(markers, str): plot_kws["marker"] = markers elif hue is not None: plot_kws["style"] = data[hue] plot_kws["markers"] = markers # Draw the marginal plots on the diagonal diag_kws = diag_kws.copy() diag_kws.setdefault("legend", False) if diag_kind == "hist": grid.map_diag(histplot, **diag_kws) elif diag_kind == "kde": diag_kws.setdefault("fill", True) diag_kws.setdefault("warn_singular", False) grid.map_diag(kdeplot, **diag_kws) # Maybe plot on the off-diagonals if diag_kind is not None: plotter = grid.map_offdiag else: plotter = grid.map if kind == "scatter": from .relational import scatterplot # Avoid circular import plotter(scatterplot, **plot_kws) elif kind == "reg": from .regression import regplot # Avoid circular import plotter(regplot, **plot_kws) elif kind == "kde": from .distributions import kdeplot # Avoid circular import plot_kws.setdefault("warn_singular", False) plotter(kdeplot, **plot_kws) elif kind == "hist": from .distributions import histplot # Avoid circular import plotter(histplot, **plot_kws) # Add a legend if hue is not None: grid.add_legend() grid.tight_layout() return grid
Plot pairwise relationships in a dataset. By default, this function will create a grid of Axes such that each numeric variable in ``data`` will by shared across the y-axes across a single row and the x-axes across a single column. The diagonal plots are treated differently: a univariate distribution plot is drawn to show the marginal distribution of the data in each column. It is also possible to show a subset of variables or plot different variables on the rows and columns. This is a high-level interface for :class:`PairGrid` that is intended to make it easy to draw a few common styles. You should use :class:`PairGrid` directly if you need more flexibility. Parameters ---------- data : `pandas.DataFrame` Tidy (long-form) dataframe where each column is a variable and each row is an observation. hue : name of variable in ``data`` Variable in ``data`` to map plot aspects to different colors. hue_order : list of strings Order for the levels of the hue variable in the palette palette : dict or seaborn color palette Set of colors for mapping the ``hue`` variable. If a dict, keys should be values in the ``hue`` variable. vars : list of variable names Variables within ``data`` to use, otherwise use every column with a numeric datatype. {x, y}_vars : lists of variable names Variables within ``data`` to use separately for the rows and columns of the figure; i.e. to make a non-square plot. kind : {'scatter', 'kde', 'hist', 'reg'} Kind of plot to make. diag_kind : {'auto', 'hist', 'kde', None} Kind of plot for the diagonal subplots. If 'auto', choose based on whether or not ``hue`` is used. markers : single matplotlib marker code or list Either the marker to use for all scatterplot points or a list of markers with a length the same as the number of levels in the hue variable so that differently colored points will also have different scatterplot markers. height : scalar Height (in inches) of each facet. aspect : scalar Aspect * height gives the width (in inches) of each facet. corner : bool If True, don't add axes to the upper (off-diagonal) triangle of the grid, making this a "corner" plot. dropna : boolean Drop missing values from the data before plotting. {plot, diag, grid}_kws : dicts Dictionaries of keyword arguments. ``plot_kws`` are passed to the bivariate plotting function, ``diag_kws`` are passed to the univariate plotting function, and ``grid_kws`` are passed to the :class:`PairGrid` constructor. Returns ------- grid : :class:`PairGrid` Returns the underlying :class:`PairGrid` instance for further tweaking. See Also -------- PairGrid : Subplot grid for more flexible plotting of pairwise relationships. JointGrid : Grid for plotting joint and marginal distributions of two variables. Examples -------- .. include:: ../docstrings/pairplot.rst
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 removed after completion of the work. """ # The original categorical functions applied a palette to the categorical axis # by default. We want to require an explicit hue mapping, to be more consistent # with how things work elsewhere now. I don't think there's any good way to # do this gently -- because it's triggered by the default value of hue=None, # users would always get a warning, unless we introduce some sentinel "default" # argument for this change. That's possible, but asking users to set `hue=None` # on every call is annoying. # We are keeping the logic for implementing the old behavior in with the current # system so that (a) we can punt on that decision and (b) we can ensure that # refactored code passes old tests. default_behavior = color is None or palette is not None if force_hue and "hue" not in self.variables and default_behavior: self._redundant_hue = True self.plot_data["hue"] = self.plot_data[self.orient] self.variables["hue"] = self.variables[self.orient] self.var_types["hue"] = "categorical" hue_order = self.var_levels[self.orient] # Because we convert the categorical axis variable to string, # we need to update a dictionary palette too if isinstance(palette, dict): palette = {str(k): v for k, v in palette.items()} else: if "hue" in self.variables: redundant = (self.plot_data["hue"] == self.plot_data[self.orient]).all() else: redundant = False self._redundant_hue = redundant # Previously, categorical plots had a trick where color= could seed the palette. # Because that's an explicit parameterization, we are going to give it one # release cycle with a warning before removing. if "hue" in self.variables and palette is None and color is not None: if not isinstance(color, str): color = mpl.colors.to_hex(color) palette = f"dark:{color}" msg = ( "\n\nSetting a gradient palette using color= is deprecated and will be " f"removed in v0.14.0. Set `palette='{palette}'` for the same effect.\n" ) warnings.warn(msg, FutureWarning, stacklevel=3) return palette, hue_order
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 " f"and will be removed in v0.14.0. Assign the `{self.orient}` variable " "to `hue` and set `legend=False` for the same effect.\n" ) warnings.warn(msg, FutureWarning, stacklevel=3) self.legend = False self.plot_data["hue"] = self.plot_data[self.orient] self.variables["hue"] = self.variables.get(self.orient) self.var_types["hue"] = self.var_types.get(self.orient) hue_order = self.var_levels.get(self.orient) self._var_levels.pop("hue", None) return hue_order
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 = ( "\n\n" "The `scale` parameter is deprecated and will be removed in v0.15.0. " "You can now control the size of each plot element using matplotlib " "`Line2D` parameters (e.g., `linewidth`, `markersize`, etc.)." "\n" ) warnings.warn(msg, stacklevel=3) kwargs.update(linewidth=lw, markeredgewidth=mew, markersize=ms) if join is not deprecated: msg = ( "\n\n" "The `join` parameter is deprecated and will be removed in v0.15.0." ) if not join: msg += ( " You can remove the line between points with `linestyle='none'`." ) kwargs.update(linestyle="") msg += "\n" warnings.warn(msg, stacklevel=3)
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}}}" msg = ( f"\n\nThe `{name}` parameter is deprecated. And will be removed " f"in v0.15.0. Pass `{suggest}` instead.\n" ) warnings.warn(msg, FutureWarning, stacklevel=4) err_kws[key] = val if errcolor is not None: deprecate_err_param("errcolor", "color", errcolor) deprecate_err_param("errwidth", "linewidth", errwidth) if capsize is None: capsize = 0 msg = ( "\n\nPassing `capsize=None` is deprecated and will be removed " "in v0.15.0. Pass `capsize=0` to disable caps.\n" ) warnings.warn(msg, FutureWarning, stacklevel=3) return err_kws, capsize
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 " f"in v0.15.0. Pass `density_norm={scale!r}` for the same effect." ) warnings.warn(msg, FutureWarning, stacklevel=3) if scale_hue is not deprecated: common_norm = scale_hue msg = ( "\n\nThe `scale_hue` parameter has been replaced and will be removed " f"in v0.15.0. Pass `common_norm={not scale_hue}` for the same effect." ) warnings.warn(msg, FutureWarning, stacklevel=3) return density_norm, common_norm
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`. Setting `bw_method={bw!r}`, but please see docs for the new parameters and update your code. This will become an error in seaborn v0.15.0. """) warnings.warn(msg, FutureWarning, stacklevel=3) return bw_method
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 _boxen_scale_backcompat(self, scale, width_method): """Provide two cycles of backcompat for scale kwargs""" if scale is not deprecated: width_method = scale msg = ( "\n\nThe `scale` parameter has been renamed to `width_method` and " f"will be removed in v0.15. Pass `width_method={scale!r}" ) if scale == "area": msg += ", but note that the result for 'area' will appear different." else: msg += " for the same effect." warnings.warn(msg, FutureWarning, stacklevel=3) return width_method
Provide two cycles of backcompat for scale kwargs
_boxen_scale_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 definition.' ) warnings.warn(msg, FutureWarning, stacklevel=3) color = "auto" elif color is None or color is default: color = "auto" if color != "auto": return color if hue_map.lookup_table is None: if base_color is None: return None basis = [mpl.colors.to_rgb(base_color)] else: basis = [mpl.colors.to_rgb(c) for c in hue_map.lookup_table.values()] unique_colors = np.unique(basis, axis=0) light_vals = [rgb_to_hls(*rgb[:3])[1] for rgb in unique_colors] lum = min(light_vals) * .6 return (lum, lum, lum)
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 isinstance(value, list): mapping = {k: v for k, v in zip(levels, value)} else: mapping = {k: value for k in levels} else: mapping = {None: value} return mapping
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"]].value_counts() return orient.size != paired.size return False
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 just treat it as a no-op. return hue_idx = self._hue_map.levels.index(keys["hue"]) n = len(self._hue_map.levels) data["width"] /= n full_width = data["width"] * n offset = data["width"] * hue_idx + data["width"] / 2 - full_width / 2 data[self.orient] += offset
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 data["edge"] = inv(data[var] - hw) data["width"] = inv(data[var] + hw) - data["edge"].to_numpy() for suf in ["", "min", "max"]: if (col := f"{var}{suf}") in data: data[col] = inv(data[col])
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 unique_values = np.unique(self.comp_data[self.orient]) if len(unique_values) > 1: native_width = np.nanmin(np.diff(unique_values)) else: native_width = 1 return native_width
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 offsets = np.linspace(0, width - each_width, n_levels) offsets -= offsets.mean() else: offsets = np.zeros(n_levels) return offsets
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() # Reset the categorical positions to the center line cat_idx = 1 if self.orient == "y" else 0 orig_xy_data[:, cat_idx] = center # Transform the data coordinates to point coordinates. # We'll figure out the swarm positions in the latter # and then convert back to data coordinates and replot orig_x_data, orig_y_data = orig_xy_data.T orig_xy = ax.transData.transform(orig_xy_data) # Order the variables so that x is the categorical axis if self.orient == "y": orig_xy = orig_xy[:, [1, 0]] # Add a column with each point's radius sizes = points.get_sizes() if sizes.size == 1: sizes = np.repeat(sizes, orig_xy.shape[0]) edge = points.get_linewidth().item() radii = (np.sqrt(sizes) + edge) / 2 * (dpi / 72) orig_xy = np.c_[orig_xy, radii] # Sort along the value axis to facilitate the beeswarm sorter = np.argsort(orig_xy[:, 1]) orig_xyr = orig_xy[sorter] # Adjust points along the categorical axis to prevent overlaps new_xyr = np.empty_like(orig_xyr) new_xyr[sorter] = self.beeswarm(orig_xyr) # Transform the point coordinates back to data coordinates if self.orient == "y": new_xy = new_xyr[:, [1, 0]] else: new_xy = new_xyr[:, :2] new_x_data, new_y_data = ax.transData.inverted().transform(new_xy).T # Add gutters t_fwd, t_inv = _get_transform_functions(ax, self.orient) if self.orient == "y": self.add_gutters(new_y_data, center, t_fwd, t_inv) else: self.add_gutters(new_x_data, center, t_fwd, t_inv) # Reposition the points so they do not overlap if self.orient == "y": points.set_offsets(np.c_[orig_x_data, new_y_data]) else: points.set_offsets(np.c_[new_x_data, orig_y_data])
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_xyr[0]) # Loop over the remaining points for xyr_i in orig_xyr[1:]: # Find the points in the swarm that could possibly # overlap with the point we are currently placing neighbors = self.could_overlap(xyr_i, swarm) # Find positions that would be valid individually # with respect to each of the swarm neighbors candidates = self.position_candidates(xyr_i, neighbors) # Sort candidates by their centrality offsets = np.abs(candidates[:, 0] - midline) candidates = candidates[np.argsort(offsets)] # Find the first candidate that does not overlap any neighbors new_xyr_i = self.first_non_overlapping_candidate(candidates, neighbors) # Place it into the swarm swarm = np.vstack([swarm, new_xyr_i]) return swarm
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 reversed(swarm): _, y_j, r_j = xyr_j if (y_i - y_j) < (r_i + r_j): neighbors.append(xyr_j) else: break return np.array(neighbors)[::-1]
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) ** 2 - dy ** 2, 0)) * 1.05 cl, cr = (x_j - dx, y_i, r_i), (x_j + dx, y_i, r_i) if left_first: new_candidates = [cl, cr] else: new_candidates = [cr, cl] candidates.extend(new_candidates) left_first = not left_first return np.array(candidates)
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] neighbors_y = neighbors[:, 1] neighbors_r = neighbors[:, 2] for xyr_i in candidates: x_i, y_i, r_i = xyr_i dx = neighbors_x - x_i dy = neighbors_y - y_i sq_distances = np.square(dx) + np.square(dy) sep_needed = np.square(neighbors_r + r_i) # Good candidate does not overlap any of neighbors which means that # squared distance between candidate and any of the neighbors has # to be at least square of the summed radii good_candidate = np.all(sq_distances >= sep_needed) if good_candidate: return xyr_i raise RuntimeError( "No non-overlapping candidates found. This should not happen." )
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] = low_gutter high_gutter = trans_inv(trans_fwd(center) + half_width) off_high = points > high_gutter if off_high.any(): points[off_high] = high_gutter gutter_prop = (off_high + off_low).sum() / len(points) if gutter_prop > self.warn_thresh: msg = ( "{:.1%} of the points cannot be placed; you may want " "to decrease the size of the markers or use stripplot." ).format(gutter_prop) warnings.warn(msg, UserWarning) return points
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 conceptual name for x/y. return bool({"x", "y"} - set(self.variables))
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).pop()
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 = [] labels = [] for level in self._hue_map.levels: color = self._hue_map(level) kws = self._artist_kws( artist_kws, fill, element, multiple, color, alpha ) # color gets added to the kws to workaround an issue with barplot's color # cycle integration but it causes problems in this context where we are # setting artist properties directly, so pop it off here if "facecolor" in kws: kws.pop("color", None) handles.append(artist(**kws)) labels.append(level) if isinstance(ax_obj, mpl.axes.Axes): ax_obj.legend(handles, labels, title=self.variables["hue"], **legend_kws) else: # i.e. a FacetGrid. TODO make this better legend_data = dict(zip(labels, handles)) ax_obj.add_legend( legend_data, title=self.variables["hue"], label_order=self.var_levels["hue"], **legend_kws )
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)) if element == "bars": # Make bar() interface with property cycle correctly # https://github.com/matplotlib/matplotlib/issues/19385 kws["color"] = "none" if multiple in ["stack", "fill"] or element == "bars": kws.setdefault("edgecolor", mpl.rcParams["patch.edgecolor"]) else: kws.setdefault("edgecolor", to_rgba(color, 1)) elif element == "bars": kws["facecolor"] = "none" kws["edgecolor"] = to_rgba(color, alpha) else: kws["color"] = to_rgba(color, alpha) return kws
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.searchsorted(normalized_values, 1 - isoprop) levels = np.take(sorted_values, idx, mode="clip") return levels
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_husl(r, g, b) xx = np.linspace(-1, 1, int(1.15 * 256))[:256] ramp = np.zeros((256, 3)) ramp[:, 0] = h ramp[:, 1] = s * np.cos(xx) ramp[:, 2] = np.linspace(35, 80, 256) colors = np.clip([husl.husl_to_rgb(*hsl) for hsl in ramp], 0, 1) return mpl.colors.ListedColormap(colors[::-1])
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 = self.var_types["y"] == "categorical" discrete = discrete_x, discrete_y return discrete
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 checking if any # "grouping" (terminnology?) semantics have been assigned if "hue" not in self.variables: return curves, baselines if multiple in ("stack", "fill"): # Setting stack or fill means that the curves share a # support grid / set of bin edges, so we can make a dataframe # Reverse the column order to plot from top to bottom curves = pd.DataFrame(curves).iloc[:, ::-1] # Find column groups that are nested within col/row variables column_groups = {} for i, keyd in enumerate(map(dict, curves.columns)): facet_key = keyd.get("col", None), keyd.get("row", None) column_groups.setdefault(facet_key, []) column_groups[facet_key].append(i) baselines = curves.copy() for col_idxs in column_groups.values(): cols = curves.columns[col_idxs] norm_constant = curves[cols].sum(axis="columns") # Take the cumulative sum to stack curves[cols] = curves[cols].cumsum(axis="columns") # Normalize by row sum to fill if multiple == "fill": curves[cols] = curves[cols].div(norm_constant, axis="index") # Define where each segment starts baselines[cols] = curves[cols].shift(1, axis=1).fillna(0) if multiple == "dodge": # Account for the unique semantic (non-faceting) levels # This will require rethiniking if we add other semantics! hue_levels = self.var_levels["hue"] n = len(hue_levels) f_fwd, f_inv = self._get_scale_transforms(self.data_variable) for key in curves: level = dict(key)["hue"] hist = curves[key].reset_index(name="heights") level_idx = hue_levels.index(level) a = f_fwd(hist["edges"]) b = f_fwd(hist["edges"] + hist["widths"]) w = (b - a) / n new_min = f_inv(a + level_idx * w) new_max = f_inv(a + (level_idx + 1) * w) hist["widths"] = new_max - new_min hist["edges"] = new_min curves[key] = hist.set_index(["edges", "widths"])["heights"] return curves, baselines
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)) # fall back to sqrt(a) bins if iqr is 0 if h == 0: return int(np.sqrt(a.size)) else: return int(np.ceil((a.max() - a.min()) / h))
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 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/de44147ed2974457ad6372750bbe5751 """ if kde and not hist: axes_level_suggestion = ( "`kdeplot` (an axes-level function for kernel density plots)" ) else: axes_level_suggestion = ( "`histplot` (an axes-level function for histograms)" ) msg = textwrap.dedent(f""" `distplot` is a deprecated function and will be removed in seaborn v0.14.0. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or {axes_level_suggestion}. For a guide to updating your code to use the new functions, please see https://gist.github.com/mwaskom/de44147ed2974457ad6372750bbe5751 """) warnings.warn(msg, UserWarning, stacklevel=2) if ax is None: ax = plt.gca() # Intelligently label the support axis label_ax = bool(axlabel) if axlabel is None and hasattr(a, "name"): axlabel = a.name if axlabel is not None: label_ax = True # Support new-style API if x is not None: a = x # Make a a 1-d float array a = np.asarray(a, float) if a.ndim > 1: a = a.squeeze() # Drop null values from array a = remove_na(a) # Decide if the hist is normed norm_hist = norm_hist or kde or (fit is not None) # Handle dictionary defaults hist_kws = {} if hist_kws is None else hist_kws.copy() kde_kws = {} if kde_kws is None else kde_kws.copy() rug_kws = {} if rug_kws is None else rug_kws.copy() fit_kws = {} if fit_kws is None else fit_kws.copy() # Get the color from the current color cycle if color is None: if vertical: line, = ax.plot(0, a.mean()) else: line, = ax.plot(a.mean(), 0) color = line.get_color() line.remove() # Plug the label into the right kwarg dictionary if label is not None: if hist: hist_kws["label"] = label elif kde: kde_kws["label"] = label elif rug: rug_kws["label"] = label elif fit: fit_kws["label"] = label if hist: if bins is None: bins = min(_freedman_diaconis_bins(a), 50) hist_kws.setdefault("alpha", 0.4) hist_kws.setdefault("density", norm_hist) orientation = "horizontal" if vertical else "vertical" hist_color = hist_kws.pop("color", color) ax.hist(a, bins, orientation=orientation, color=hist_color, **hist_kws) if hist_color != color: hist_kws["color"] = hist_color axis = "y" if vertical else "x" if kde: kde_color = kde_kws.pop("color", color) kdeplot(**{axis: a}, ax=ax, color=kde_color, **kde_kws) if kde_color != color: kde_kws["color"] = kde_color if rug: rug_color = rug_kws.pop("color", color) rugplot(**{axis: a}, ax=ax, color=rug_color, **rug_kws) if rug_color != color: rug_kws["color"] = rug_color if fit is not None: def pdf(x): return fit.pdf(x, *params) fit_color = fit_kws.pop("color", "#282828") gridsize = fit_kws.pop("gridsize", 200) cut = fit_kws.pop("cut", 3) clip = fit_kws.pop("clip", (-np.inf, np.inf)) bw = gaussian_kde(a).scotts_factor() * a.std(ddof=1) x = _kde_support(a, bw, gridsize, cut, clip) params = fit.fit(a) y = pdf(x) if vertical: x, y = y, x ax.plot(x, y, color=fit_color, **fit_kws) if fit_color != "#282828": fit_kws["color"] = fit_color if label_ax: if vertical: ax.set_ylabel(axlabel) else: ax.set_xlabel(axlabel) return ax
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/de44147ed2974457ad6372750bbe5751
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, we have nested lists return [list(map(to_rgb, color_list)) for color_list in colors]
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.shape, bool) if isinstance(mask, pd.DataFrame): # For DataFrame masks, ensure that semantic labels match data if not mask.index.equals(data.index) \ and mask.columns.equals(data.columns): err = "Mask must have the same index and columns as data." raise ValueError(err) elif hasattr(mask, "__array__"): mask = np.asarray(mask) # For array masks, ensure that shape matches data then convert if mask.shape != data.shape: raise ValueError("Mask must have the same shape as data.") mask = pd.DataFrame(mask, index=data.index, columns=data.columns, dtype=bool) # Add any cells with missing data to the mask # This works around an issue where `plt.pcolormesh` doesn't represent # missing data properly mask = mask | pd.isnull(data) return 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.
_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: if robust: vmin = np.nanpercentile(calc_data, 2) else: vmin = np.nanmin(calc_data) if vmax is None: if robust: vmax = np.nanpercentile(calc_data, 98) else: vmax = np.nanmax(calc_data) self.vmin, self.vmax = vmin, vmax # Choose default colormaps if not provided if cmap is None: if center is None: self.cmap = cm.rocket else: self.cmap = cm.icefire elif isinstance(cmap, str): self.cmap = get_colormap(cmap) elif isinstance(cmap, list): self.cmap = mpl.colors.ListedColormap(cmap) else: self.cmap = cmap # Recenter a divergent colormap if center is not None: # Copy bad values # in mpl<3.2 only masked values are honored with "bad" color spec # (see https://github.com/matplotlib/matplotlib/pull/14257) bad = self.cmap(np.ma.masked_invalid([np.nan]))[0] # under/over values are set for sure when cmap extremes # do not map to the same color as +-inf under = self.cmap(-np.inf) over = self.cmap(np.inf) under_set = under != self.cmap(0) over_set = over != self.cmap(self.cmap.N - 1) vrange = max(vmax - center, center - vmin) normlize = mpl.colors.Normalize(center - vrange, center + vrange) cmin, cmax = normlize([vmin, vmax]) cc = np.linspace(cmin, cmax, 256) self.cmap = mpl.colors.ListedColormap(self.cmap(cc)) self.cmap.set_bad(bad) if under_set: self.cmap.set_under(under) if over_set: self.cmap.set_over(over)
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.flat, mesh.get_array().flat, mesh.get_facecolors(), self.annot_data.flat): if m is not np.ma.masked: lum = relative_luminance(color) text_color = ".15" if lum > .408 else "w" annotation = ("{:" + self.fmt + "}").format(val) text_kwargs = dict(color=text_color, ha="center", va="center") text_kwargs.update(self.annot_kws) ax.text(x, y, annotation, **text_kwargs)
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 = 0, n, tickevery ticks = np.arange(start, end, step) + .5 labels = labels[start:end:step] return ticks, labels
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] tick, = axis.set_ticks([0]) fontsize = tick.label1.get_size() max_ticks = int(size // (fontsize / 72)) if max_ticks < 1: return [], [] tick_every = len(labels) // max_ticks + 1 tick_every = 1 if tick_every == 0 else tick_every ticks, labels = self._skip_ticks(labels, tick_every) return ticks, labels
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: kws.setdefault("vmin", self.vmin) kws.setdefault("vmax", self.vmax) # Draw the heatmap mesh = ax.pcolormesh(self.plot_data, cmap=self.cmap, **kws) # Set the axis limits ax.set(xlim=(0, self.data.shape[1]), ylim=(0, self.data.shape[0])) # Invert the y axis to show the plot in matrix form ax.invert_yaxis() # Possibly add a colorbar if self.cbar: cb = ax.figure.colorbar(mesh, cax, ax, **self.cbar_kws) cb.outline.set_linewidth(0) # If rasterized is passed to pcolormesh, also rasterize the # colorbar to avoid white lines on the PDF rendering if kws.get('rasterized', False): cb.solids.set_rasterized(True) # Add row and column labels if isinstance(self.xticks, str) and self.xticks == "auto": xticks, xticklabels = self._auto_ticks(ax, self.xticklabels, 0) else: xticks, xticklabels = self.xticks, self.xticklabels if isinstance(self.yticks, str) and self.yticks == "auto": yticks, yticklabels = self._auto_ticks(ax, self.yticklabels, 1) else: yticks, yticklabels = self.yticks, self.yticklabels ax.set(xticks=xticks, yticks=yticks) xtl = ax.set_xticklabels(xticklabels) ytl = ax.set_yticklabels(yticklabels, rotation="vertical") plt.setp(ytl, va="center") # GH2484 # Possibly rotate them if they overlap _draw_figure(ax.figure) if axis_ticklabels_overlap(xtl): plt.setp(xtl, rotation="vertical") if axis_ticklabels_overlap(ytl): plt.setp(ytl, rotation="horizontal") # Add the axis labels ax.set(xlabel=self.xlabel, ylabel=self.ylabel) # Annotate the cells with the formatted values if self.annot: self._annotate_heatmap(ax, mesh)
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 ): """Plot rectangular data as a color-encoded matrix. This is an Axes-level function and will draw the heatmap into the currently-active Axes if none is provided to the ``ax`` argument. Part of this Axes space will be taken and used to plot a colormap, unless ``cbar`` is False or a separate Axes is provided to ``cbar_ax``. Parameters ---------- data : rectangular dataset 2D dataset that can be coerced into an ndarray. If a Pandas DataFrame is provided, the index/column information will be used to label the columns and rows. vmin, vmax : floats, optional Values to anchor the colormap, otherwise they are inferred from the data and other keyword arguments. cmap : matplotlib colormap name or object, or list of colors, optional The mapping from data values to color space. If not provided, the default will depend on whether ``center`` is set. center : float, optional The value at which to center the colormap when plotting divergent data. Using this parameter will change the default ``cmap`` if none is specified. robust : bool, optional If True and ``vmin`` or ``vmax`` are absent, the colormap range is computed with robust quantiles instead of the extreme values. annot : bool or rectangular dataset, optional If True, write the data value in each cell. If an array-like with the same shape as ``data``, then use this to annotate the heatmap instead of the data. Note that DataFrames will match on position, not index. fmt : str, optional String formatting code to use when adding annotations. annot_kws : dict of key, value mappings, optional Keyword arguments for :meth:`matplotlib.axes.Axes.text` when ``annot`` is True. linewidths : float, optional Width of the lines that will divide each cell. linecolor : color, optional Color of the lines that will divide each cell. cbar : bool, optional Whether to draw a colorbar. cbar_kws : dict of key, value mappings, optional Keyword arguments for :meth:`matplotlib.figure.Figure.colorbar`. cbar_ax : matplotlib Axes, optional Axes in which to draw the colorbar, otherwise take space from the main Axes. square : bool, optional If True, set the Axes aspect to "equal" so each cell will be square-shaped. xticklabels, yticklabels : "auto", bool, list-like, or int, optional If True, plot the column names of the dataframe. If False, don't plot the column names. If list-like, plot these alternate labels as the xticklabels. If an integer, use the column names but plot only every n label. If "auto", try to densely plot non-overlapping labels. mask : bool array or DataFrame, optional If passed, data will not be shown in cells where ``mask`` is True. Cells with missing values are automatically masked. ax : matplotlib Axes, optional Axes in which to draw the plot, otherwise use the currently-active Axes. kwargs : other keyword arguments All other keyword arguments are passed to :meth:`matplotlib.axes.Axes.pcolormesh`. Returns ------- ax : matplotlib Axes Axes object with the heatmap. See Also -------- clustermap : Plot a matrix using hierarchical clustering to arrange the rows and columns. Examples -------- .. include:: ../docstrings/heatmap.rst """ # Initialize the plotter object plotter = _HeatMapper(data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, cbar, cbar_kws, xticklabels, yticklabels, mask) # Add the pcolormesh kwargs here kwargs["linewidths"] = linewidths kwargs["edgecolor"] = linecolor # Draw the plot and return the Axes if ax is None: ax = plt.gca() if square: ax.set_aspect("equal") plotter.plot(ax, cbar_ax, kwargs) return ax
Plot rectangular data as a color-encoded matrix. This is an Axes-level function and will draw the heatmap into the currently-active Axes if none is provided to the ``ax`` argument. Part of this Axes space will be taken and used to plot a colormap, unless ``cbar`` is False or a separate Axes is provided to ``cbar_ax``. Parameters ---------- data : rectangular dataset 2D dataset that can be coerced into an ndarray. If a Pandas DataFrame is provided, the index/column information will be used to label the columns and rows. vmin, vmax : floats, optional Values to anchor the colormap, otherwise they are inferred from the data and other keyword arguments. cmap : matplotlib colormap name or object, or list of colors, optional The mapping from data values to color space. If not provided, the default will depend on whether ``center`` is set. center : float, optional The value at which to center the colormap when plotting divergent data. Using this parameter will change the default ``cmap`` if none is specified. robust : bool, optional If True and ``vmin`` or ``vmax`` are absent, the colormap range is computed with robust quantiles instead of the extreme values. annot : bool or rectangular dataset, optional If True, write the data value in each cell. If an array-like with the same shape as ``data``, then use this to annotate the heatmap instead of the data. Note that DataFrames will match on position, not index. fmt : str, optional String formatting code to use when adding annotations. annot_kws : dict of key, value mappings, optional Keyword arguments for :meth:`matplotlib.axes.Axes.text` when ``annot`` is True. linewidths : float, optional Width of the lines that will divide each cell. linecolor : color, optional Color of the lines that will divide each cell. cbar : bool, optional Whether to draw a colorbar. cbar_kws : dict of key, value mappings, optional Keyword arguments for :meth:`matplotlib.figure.Figure.colorbar`. cbar_ax : matplotlib Axes, optional Axes in which to draw the colorbar, otherwise take space from the main Axes. square : bool, optional If True, set the Axes aspect to "equal" so each cell will be square-shaped. xticklabels, yticklabels : "auto", bool, list-like, or int, optional If True, plot the column names of the dataframe. If False, don't plot the column names. If list-like, plot these alternate labels as the xticklabels. If an integer, use the column names but plot only every n label. If "auto", try to densely plot non-overlapping labels. mask : bool array or DataFrame, optional If passed, data will not be shown in cells where ``mask`` is True. Cells with missing values are automatically masked. ax : matplotlib Axes, optional Axes in which to draw the plot, otherwise use the currently-active Axes. kwargs : other keyword arguments All other keyword arguments are passed to :meth:`matplotlib.axes.Axes.pcolormesh`. Returns ------- ax : matplotlib Axes Axes object with the heatmap. See Also -------- clustermap : Plot a matrix using hierarchical clustering to arrange the rows and columns. Examples -------- .. include:: ../docstrings/heatmap.rst
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: data = data.T if isinstance(data, pd.DataFrame): array = data.values else: array = np.asarray(data) data = pd.DataFrame(array) self.array = array self.data = data self.shape = self.data.shape self.metric = metric self.method = method self.axis = axis self.label = label self.rotate = rotate if linkage is None: self.linkage = self.calculated_linkage else: self.linkage = linkage self.dendrogram = self.calculate_dendrogram() # Dendrogram ends are always at multiples of 5, who knows why ticks = 10 * np.arange(self.data.shape[0]) + 5 if self.label: ticklabels = _index_to_ticklabels(self.data.index) ticklabels = [ticklabels[i] for i in self.reordered_ind] if self.rotate: self.xticks = [] self.yticks = ticks self.xticklabels = [] self.yticklabels = ticklabels self.ylabel = _index_to_label(self.data.index) self.xlabel = '' else: self.xticks = ticks self.yticks = [] self.xticklabels = ticklabels self.yticklabels = [] self.ylabel = '' self.xlabel = _index_to_label(self.data.index) else: self.xticks, self.yticks = [], [] self.yticklabels, self.xticklabels = [], [] self.xlabel, self.ylabel = '', '' self.dependent_coord = self.dendrogram['dcoord'] self.independent_coord = self.dendrogram['icoord']
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() tree_kws.setdefault("linewidths", .5) tree_kws.setdefault("colors", tree_kws.pop("color", (.2, .2, .2))) if self.rotate and self.axis == 0: coords = zip(self.dependent_coord, self.independent_coord) else: coords = zip(self.independent_coord, self.dependent_coord) lines = LineCollection([list(zip(x, y)) for x, y in coords], **tree_kws) ax.add_collection(lines) number_of_leaves = len(self.reordered_ind) max_dependent_coord = max(map(max, self.dependent_coord)) if self.rotate: ax.yaxis.set_ticks_position('right') # Constants 10 and 1.05 come from # `scipy.cluster.hierarchy._plot_dendrogram` ax.set_ylim(0, number_of_leaves * 10) ax.set_xlim(0, max_dependent_coord * 1.05) ax.invert_xaxis() ax.invert_yaxis() else: # Constants 10 and 1.05 come from # `scipy.cluster.hierarchy._plot_dendrogram` ax.set_xlim(0, number_of_leaves * 10) ax.set_ylim(0, max_dependent_coord * 1.05) despine(ax=ax, bottom=True, left=True) ax.set(xticks=self.xticks, yticks=self.yticks, xlabel=self.xlabel, ylabel=self.ylabel) xtl = ax.set_xticklabels(self.xticklabels) ytl = ax.set_yticklabels(self.yticklabels, rotation='vertical') # Force a draw of the plot to avoid matplotlib window error _draw_figure(ax.figure) if len(ytl) > 0 and axis_ticklabels_overlap(ytl): plt.setp(ytl, rotation="horizontal") if len(xtl) > 0 and axis_ticklabels_overlap(xtl): plt.setp(xtl, rotation="vertical") return self
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, optional Linkage matrix axis : int, optional Which axis to use to calculate linkage. 0 is rows, 1 is columns. label : bool, optional If True, label the dendrogram at leaves with column or row names metric : str, optional Distance metric. Anything valid for scipy.spatial.distance.pdist method : str, optional Linkage method to use. Anything valid for scipy.cluster.hierarchy.linkage rotate : bool, optional When plotting the matrix, whether to rotate it 90 degrees counter-clockwise, so the leaves face right tree_kws : dict, optional Keyword arguments for the ``matplotlib.collections.LineCollection`` that is used for plotting the lines of the dendrogram tree. ax : matplotlib axis, optional Axis to plot on, otherwise uses current axis Returns ------- dendrogramplotter : _DendrogramPlotter A Dendrogram plotter object. Notes ----- Access the reordered dendrogram indices with dendrogramplotter.reordered_ind """ if _no_scipy: raise RuntimeError("dendrogram requires scipy to be installed") plotter = _DendrogramPlotter(data, linkage=linkage, axis=axis, metric=metric, method=method, label=label, rotate=rotate) if ax is None: ax = plt.gca() return plotter.plot(ax=ax, tree_kws=tree_kws)
Draw a tree diagram of relationships within a matrix Parameters ---------- data : pandas.DataFrame Rectangular data linkage : numpy.array, optional Linkage matrix axis : int, optional Which axis to use to calculate linkage. 0 is rows, 1 is columns. label : bool, optional If True, label the dendrogram at leaves with column or row names metric : str, optional Distance metric. Anything valid for scipy.spatial.distance.pdist method : str, optional Linkage method to use. Anything valid for scipy.cluster.hierarchy.linkage rotate : bool, optional When plotting the matrix, whether to rotate it 90 degrees counter-clockwise, so the leaves face right tree_kws : dict, optional Keyword arguments for the ``matplotlib.collections.LineCollection`` that is used for plotting the lines of the dendrogram tree. ax : matplotlib axis, optional Axis to plot on, otherwise uses current axis Returns ------- dendrogramplotter : _DendrogramPlotter A Dendrogram plotter object. Notes ----- Access the reordered dendrogram indices with dendrogramplotter.reordered_ind
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_scipy: raise RuntimeError("ClusterGrid requires scipy to be available") if isinstance(data, pd.DataFrame): self.data = data else: self.data = pd.DataFrame(data) self.data2d = self.format_data(self.data, pivot_kws, z_score, standard_scale) self.mask = _matrix_mask(self.data2d, mask) self._figure = plt.figure(figsize=figsize) self.row_colors, self.row_color_labels = \ self._preprocess_colors(data, row_colors, axis=0) self.col_colors, self.col_color_labels = \ self._preprocess_colors(data, col_colors, axis=1) try: row_dendrogram_ratio, col_dendrogram_ratio = dendrogram_ratio except TypeError: row_dendrogram_ratio = col_dendrogram_ratio = dendrogram_ratio try: row_colors_ratio, col_colors_ratio = colors_ratio except TypeError: row_colors_ratio = col_colors_ratio = colors_ratio width_ratios = self.dim_ratios(self.row_colors, row_dendrogram_ratio, row_colors_ratio) height_ratios = self.dim_ratios(self.col_colors, col_dendrogram_ratio, col_colors_ratio) nrows = 2 if self.col_colors is None else 3 ncols = 2 if self.row_colors is None else 3 self.gs = gridspec.GridSpec(nrows, ncols, width_ratios=width_ratios, height_ratios=height_ratios) self.ax_row_dendrogram = self._figure.add_subplot(self.gs[-1, 0]) self.ax_col_dendrogram = self._figure.add_subplot(self.gs[0, -1]) self.ax_row_dendrogram.set_axis_off() self.ax_col_dendrogram.set_axis_off() self.ax_row_colors = None self.ax_col_colors = None if self.row_colors is not None: self.ax_row_colors = self._figure.add_subplot( self.gs[-1, 1]) if self.col_colors is not None: self.ax_col_colors = self._figure.add_subplot( self.gs[1, -1]) self.ax_heatmap = self._figure.add_subplot(self.gs[-1, -1]) if cbar_pos is None: self.ax_cbar = self.cax = None else: # Initialize the colorbar axes in the gridspec so that tight_layout # works. We will move it where it belongs later. This is a hack. self.ax_cbar = self._figure.add_subplot(self.gs[0, 0]) self.cax = self.ax_cbar # Backwards compatibility self.cbar_pos = cbar_pos self.dendrogram_row = None self.dendrogram_col = None
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 hasattr(data, "index") and axis == 0) or ( not hasattr(data, "columns") and axis == 1 ): axis_name = "col" if axis else "row" msg = (f"{axis_name}_colors indices can't be matched with data " f"indices. Provide {axis_name}_colors as a non-indexed " "datatype, e.g. by using `.to_numpy()``") raise TypeError(msg) # Ensure colors match data indices if axis == 0: colors = colors.reindex(data.index) else: colors = colors.reindex(data.columns) # Replace na's with white color # TODO We should set these to transparent instead colors = colors.astype(object).fillna('white') # Extract color values and labels from frame/series if isinstance(colors, pd.DataFrame): labels = list(colors.columns) colors = colors.T.values else: if colors.name is None: labels = [""] else: labels = [colors.name] colors = colors.values colors = _convert_colors(colors) return colors, labels
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) else: data2d = data if z_score is not None and standard_scale is not None: raise ValueError( 'Cannot perform both z-scoring and standard-scaling on data') if z_score is not None: data2d = self.z_score(data2d, z_score) if standard_scale is not None: data2d = self.standard_scale(data2d, standard_scale) return data2d
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 columns. Returns ------- normalized : pandas.DataFrame Noramlized data with a mean of 0 and variance of 1 across the specified axis. """ if axis == 1: z_scored = data2d else: z_scored = data2d.T z_scored = (z_scored - z_scored.mean()) / z_scored.std() if axis == 1: return z_scored else: return z_scored.T
Standarize the mean and variance of the data axis Parameters ---------- data2d : pandas.DataFrame Data to normalize axis : int Which axis to normalize across. If 0, normalize across rows, if 1, normalize across columns. Returns ------- normalized : pandas.DataFrame Noramlized data with a mean of 0 and variance of 1 across the specified axis.
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, normalize across columns. Returns ------- standardized : pandas.DataFrame Noramlized data with a mean of 0 and variance of 1 across the specified axis. """ # Normalize these values to range from 0 to 1 if axis == 1: standardized = data2d else: standardized = data2d.T subtract = standardized.min() standardized = (standardized - subtract) / ( standardized.max() - standardized.min()) if axis == 1: return standardized else: return standardized.T
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 ------- standardized : pandas.DataFrame Noramlized data with a mean of 0 and variance of 1 across the specified axis.
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: n_colors = len(colors) else: n_colors = 1 ratios += [n_colors * colors_ratio] # Add the ratio for the heatmap itself ratios.append(1 - sum(ratios)) return ratios
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 matplotlib colors Colors to label the rows or columns of a dataframe. ind : list of ints Ordering of the rows or columns, to reorder the original colors by the clustered dendrogram order axis : int Which axis this is labeling Returns ------- matrix : numpy.array A numpy array of integer values, where each indexes into the cmap cmap : matplotlib.colors.ListedColormap """ try: mpl.colors.to_rgb(colors[0]) except ValueError: # We have a 2D color structure m, n = len(colors), len(colors[0]) if not all(len(c) == n for c in colors[1:]): raise ValueError("Multiple side color vectors must have same size") else: # We have one vector of colors m, n = 1, len(colors) colors = [colors] # Map from unique colors to colormap index value unique_colors = {} matrix = np.zeros((m, n), int) for i, inner in enumerate(colors): for j, color in enumerate(inner): idx = unique_colors.setdefault(color, len(unique_colors)) matrix[i, j] = idx # Reorder for clustering and transpose for axis matrix = matrix[:, ind] if axis == 0: matrix = matrix.T cmap = mpl.colors.ListedColormap(list(unique_colors)) return matrix, cmap
Turns a list of colors into a numpy matrix and matplotlib colormap These arguments can now be plotted using heatmap(matrix, cmap) and the provided colors will be plotted. Parameters ---------- colors : list of matplotlib colors Colors to label the rows or columns of a dataframe. ind : list of ints Ordering of the rows or columns, to reorder the original colors by the clustered dendrogram order axis : int Which axis this is labeling Returns ------- matrix : numpy.array A numpy array of integer values, where each indexes into the cmap cmap : matplotlib.colors.ListedColormap
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 caused problems when we # have missed kwargs that need to be excluded that it might # be better to rewrite *in*clusively. kws = kws.copy() kws.pop('cmap', None) kws.pop('norm', None) kws.pop('center', None) kws.pop('annot', None) kws.pop('vmin', None) kws.pop('vmax', None) kws.pop('robust', None) kws.pop('xticklabels', None) kws.pop('yticklabels', None) # Plot the row colors if self.row_colors is not None: matrix, cmap = self.color_list_to_matrix_and_cmap( self.row_colors, yind, axis=0) # Get row_color labels if self.row_color_labels is not None: row_color_labels = self.row_color_labels else: row_color_labels = False heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_row_colors, xticklabels=row_color_labels, yticklabels=False, **kws) # Adjust rotation of labels if row_color_labels is not False: plt.setp(self.ax_row_colors.get_xticklabels(), rotation=90) else: despine(self.ax_row_colors, left=True, bottom=True) # Plot the column colors if self.col_colors is not None: matrix, cmap = self.color_list_to_matrix_and_cmap( self.col_colors, xind, axis=1) # Get col_color labels if self.col_color_labels is not None: col_color_labels = self.col_color_labels else: col_color_labels = False heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_col_colors, xticklabels=False, yticklabels=col_color_labels, **kws) # Adjust rotation of labels, place on right side if col_color_labels is not False: self.ax_col_colors.yaxis.tick_right() plt.setp(self.ax_col_colors.get_yticklabels(), rotation=0) else: despine(self.ax_col_colors, left=True, bottom=True)
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_ratio=0.03, cbar_pos=(.02, .8, .05, .18), tree_kws=None, **kwargs ): """ 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 keyword arguments for pivot to create a rectangular dataframe. method : str, optional Linkage method to use for calculating clusters. See :func:`scipy.cluster.hierarchy.linkage` documentation for more information. metric : str, optional Distance metric to use for the data. See :func:`scipy.spatial.distance.pdist` documentation for more options. To use different metrics (or methods) for rows and columns, you may construct each linkage matrix yourself and provide them as `{row,col}_linkage`. z_score : int or None, optional Either 0 (rows) or 1 (columns). Whether or not to calculate z-scores for the rows or the columns. Z scores are: z = (x - mean)/std, so values in each row (column) will get the mean of the row (column) subtracted, then divided by the standard deviation of the row (column). This ensures that each row (column) has mean of 0 and variance of 1. standard_scale : int or None, optional Either 0 (rows) or 1 (columns). Whether or not to standardize that dimension, meaning for each row or column, subtract the minimum and divide each by its maximum. figsize : tuple of (width, height), optional Overall size of the figure. cbar_kws : dict, optional Keyword arguments to pass to `cbar_kws` in :func:`heatmap`, e.g. to add a label to the colorbar. {row,col}_cluster : bool, optional If ``True``, cluster the {rows, columns}. {row,col}_linkage : :class:`numpy.ndarray`, optional Precomputed linkage matrix for the rows or columns. See :func:`scipy.cluster.hierarchy.linkage` for specific formats. {row,col}_colors : list-like or pandas DataFrame/Series, optional List of colors to label for either the rows or columns. Useful to evaluate whether samples within a group are clustered together. Can use nested lists or DataFrame for multiple color levels of labeling. If given as a :class:`pandas.DataFrame` or :class:`pandas.Series`, labels for the colors are extracted from the DataFrames column names or from the name of the Series. DataFrame/Series colors are also matched to the data by their index, ensuring colors are drawn in the correct order. mask : bool array or DataFrame, optional If passed, data will not be shown in cells where `mask` is True. Cells with missing values are automatically masked. Only used for visualizing, not for calculating. {dendrogram,colors}_ratio : float, or pair of floats, optional Proportion of the figure size devoted to the two marginal elements. If a pair is given, they correspond to (row, col) ratios. cbar_pos : tuple of (left, bottom, width, height), optional Position of the colorbar axes in the figure. Setting to ``None`` will disable the colorbar. tree_kws : dict, optional Parameters for the :class:`matplotlib.collections.LineCollection` that is used to plot the lines of the dendrogram tree. kwargs : other keyword arguments All other keyword arguments are passed to :func:`heatmap`. Returns ------- :class:`ClusterGrid` A :class:`ClusterGrid` instance. See Also -------- heatmap : Plot rectangular data as a color-encoded matrix. Notes ----- The returned object has a ``savefig`` method that should be used if you want to save the figure object without clipping the dendrograms. To access the reordered row indices, use: ``clustergrid.dendrogram_row.reordered_ind`` Column indices, use: ``clustergrid.dendrogram_col.reordered_ind`` Examples -------- .. include:: ../docstrings/clustermap.rst """ if _no_scipy: raise RuntimeError("clustermap requires scipy to be available") plotter = ClusterGrid(data, pivot_kws=pivot_kws, figsize=figsize, row_colors=row_colors, col_colors=col_colors, z_score=z_score, standard_scale=standard_scale, mask=mask, dendrogram_ratio=dendrogram_ratio, colors_ratio=colors_ratio, cbar_pos=cbar_pos) return plotter.plot(metric=metric, method=method, colorbar_kws=cbar_kws, row_cluster=row_cluster, col_cluster=col_cluster, row_linkage=row_linkage, col_linkage=col_linkage, tree_kws=tree_kws, **kwargs)
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 keyword arguments for pivot to create a rectangular dataframe. method : str, optional Linkage method to use for calculating clusters. See :func:`scipy.cluster.hierarchy.linkage` documentation for more information. metric : str, optional Distance metric to use for the data. See :func:`scipy.spatial.distance.pdist` documentation for more options. To use different metrics (or methods) for rows and columns, you may construct each linkage matrix yourself and provide them as `{row,col}_linkage`. z_score : int or None, optional Either 0 (rows) or 1 (columns). Whether or not to calculate z-scores for the rows or the columns. Z scores are: z = (x - mean)/std, so values in each row (column) will get the mean of the row (column) subtracted, then divided by the standard deviation of the row (column). This ensures that each row (column) has mean of 0 and variance of 1. standard_scale : int or None, optional Either 0 (rows) or 1 (columns). Whether or not to standardize that dimension, meaning for each row or column, subtract the minimum and divide each by its maximum. figsize : tuple of (width, height), optional Overall size of the figure. cbar_kws : dict, optional Keyword arguments to pass to `cbar_kws` in :func:`heatmap`, e.g. to add a label to the colorbar. {row,col}_cluster : bool, optional If ``True``, cluster the {rows, columns}. {row,col}_linkage : :class:`numpy.ndarray`, optional Precomputed linkage matrix for the rows or columns. See :func:`scipy.cluster.hierarchy.linkage` for specific formats. {row,col}_colors : list-like or pandas DataFrame/Series, optional List of colors to label for either the rows or columns. Useful to evaluate whether samples within a group are clustered together. Can use nested lists or DataFrame for multiple color levels of labeling. If given as a :class:`pandas.DataFrame` or :class:`pandas.Series`, labels for the colors are extracted from the DataFrames column names or from the name of the Series. DataFrame/Series colors are also matched to the data by their index, ensuring colors are drawn in the correct order. mask : bool array or DataFrame, optional If passed, data will not be shown in cells where `mask` is True. Cells with missing values are automatically masked. Only used for visualizing, not for calculating. {dendrogram,colors}_ratio : float, or pair of floats, optional Proportion of the figure size devoted to the two marginal elements. If a pair is given, they correspond to (row, col) ratios. cbar_pos : tuple of (left, bottom, width, height), optional Position of the colorbar axes in the figure. Setting to ``None`` will disable the colorbar. tree_kws : dict, optional Parameters for the :class:`matplotlib.collections.LineCollection` that is used to plot the lines of the dendrogram tree. kwargs : other keyword arguments All other keyword arguments are passed to :func:`heatmap`. Returns ------- :class:`ClusterGrid` A :class:`ClusterGrid` instance. See Also -------- heatmap : Plot rectangular data as a color-encoded matrix. Notes ----- The returned object has a ``savefig`` method that should be used if you want to save the figure object without clipping the dendrograms. To access the reordered row indices, use: ``clustergrid.dendrogram_row.reordered_ind`` Column indices, use: ``clustergrid.dendrogram_col.reordered_ind`` Examples -------- .. include:: ../docstrings/clustermap.rst
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.subplots(1, 1, figsize=(n * size, size)) ax.imshow(np.arange(n).reshape(1, n), cmap=mpl.colors.ListedColormap(list(pal)), interpolation="nearest", aspect="auto") ax.set_xticks(np.arange(n) - .5) ax.set_yticks([-.5, .5]) # Ensure nice border between colors ax.set_xticklabels(["" for _ in range(n)]) # The proper way to set no ticks ax.yaxis.set_major_locator(ticker.NullLocator())
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
def _repr_html_(self): """Rich display of the color palette in an HTML frontend.""" s = 55 n = len(self) html = f'<svg width="{n * s}" height="{s}">' for i, c in enumerate(self.as_hex()): html += ( f'<rect x="{i * s}" y="0" width="{s}" height="{s}" style="fill:{c};' 'stroke-width:2;stroke:rgb(255,255,255)"/>' ) html += '</svg>' return html
Rich display of the color palette in an HTML frontend.
_repr_html_
python
mwaskom/seaborn
seaborn/palettes.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
BSD-3-Clause
def _patch_colormap_display(): """Simplify the rich display of matplotlib color maps in a notebook.""" def _repr_png_(self): """Generate a PNG representation of the Colormap.""" import io from PIL import Image import numpy as np IMAGE_SIZE = (400, 50) X = np.tile(np.linspace(0, 1, IMAGE_SIZE[0]), (IMAGE_SIZE[1], 1)) pixels = self(X, bytes=True) png_bytes = io.BytesIO() Image.fromarray(pixels).save(png_bytes, format='png') return png_bytes.getvalue() def _repr_html_(self): """Generate an HTML representation of the Colormap.""" import base64 png_bytes = self._repr_png_() png_base64 = base64.b64encode(png_bytes).decode('ascii') return ('<img ' + 'alt="' + self.name + ' color map" ' + 'title="' + self.name + '"' + 'src="data:image/png;base64,' + png_base64 + '">') mpl.colors.Colormap._repr_png_ = _repr_png_ mpl.colors.Colormap._repr_html_ = _repr_html_
Simplify the rich display of matplotlib color maps in a notebook.
_patch_colormap_display
python
mwaskom/seaborn
seaborn/palettes.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
BSD-3-Clause
def _repr_png_(self): """Generate a PNG representation of the Colormap.""" import io from PIL import Image import numpy as np IMAGE_SIZE = (400, 50) X = np.tile(np.linspace(0, 1, IMAGE_SIZE[0]), (IMAGE_SIZE[1], 1)) pixels = self(X, bytes=True) png_bytes = io.BytesIO() Image.fromarray(pixels).save(png_bytes, format='png') return png_bytes.getvalue()
Generate a PNG representation of the Colormap.
_repr_png_
python
mwaskom/seaborn
seaborn/palettes.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
BSD-3-Clause
def _repr_html_(self): """Generate an HTML representation of the Colormap.""" import base64 png_bytes = self._repr_png_() png_base64 = base64.b64encode(png_bytes).decode('ascii') return ('<img ' + 'alt="' + self.name + ' color map" ' + 'title="' + self.name + '"' + 'src="data:image/png;base64,' + png_base64 + '">')
Generate an HTML representation of the Colormap.
_repr_html_
python
mwaskom/seaborn
seaborn/palettes.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
BSD-3-Clause
def color_palette(palette=None, n_colors=None, desat=None, as_cmap=False): """Return a list of colors or continuous colormap defining a palette. Possible ``palette`` values include: - Name of a seaborn palette (deep, muted, bright, pastel, dark, colorblind) - Name of matplotlib colormap - 'husl' or 'hls' - 'ch:<cubehelix arguments>' - 'light:<color>', 'dark:<color>', 'blend:<color>,<color>', - A sequence of colors in any format matplotlib accepts Calling this function with ``palette=None`` will return the current matplotlib color cycle. This function can also be used in a ``with`` statement to temporarily set the color cycle for a plot or set of plots. See the :ref:`tutorial <palette_tutorial>` for more information. Parameters ---------- palette : None, string, or sequence, optional Name of palette or None to return current palette. If a sequence, input colors are used but possibly cycled and desaturated. n_colors : int, optional Number of colors in the palette. If ``None``, the default will depend on how ``palette`` is specified. Named palettes default to 6 colors, but grabbing the current palette or passing in a list of colors will not change the number of colors unless this is specified. Asking for more colors than exist in the palette will cause it to cycle. Ignored when ``as_cmap`` is True. desat : float, optional Proportion to desaturate each color by. as_cmap : bool If True, return a :class:`matplotlib.colors.ListedColormap`. Returns ------- list of RGB tuples or :class:`matplotlib.colors.ListedColormap` See Also -------- set_palette : Set the default color cycle for all plots. set_color_codes : Reassign color codes like ``"b"``, ``"g"``, etc. to colors from one of the seaborn palettes. Examples -------- .. include:: ../docstrings/color_palette.rst """ if palette is None: palette = get_color_cycle() if n_colors is None: n_colors = len(palette) elif not isinstance(palette, str): palette = palette if n_colors is None: n_colors = len(palette) else: if n_colors is None: # Use all colors in a qualitative palette or 6 of another kind n_colors = QUAL_PALETTE_SIZES.get(palette, 6) if palette in SEABORN_PALETTES: # Named "seaborn variant" of matplotlib default color cycle palette = SEABORN_PALETTES[palette] elif palette == "hls": # Evenly spaced colors in cylindrical RGB space palette = hls_palette(n_colors, as_cmap=as_cmap) elif palette == "husl": # Evenly spaced colors in cylindrical Lab space palette = husl_palette(n_colors, as_cmap=as_cmap) elif palette.lower() == "jet": # Paternalism raise ValueError("No.") elif palette.startswith("ch:"): # Cubehelix palette with params specified in string args, kwargs = _parse_cubehelix_args(palette) palette = cubehelix_palette(n_colors, *args, **kwargs, as_cmap=as_cmap) elif palette.startswith("light:"): # light palette to color specified in string _, color = palette.split(":") reverse = color.endswith("_r") if reverse: color = color[:-2] palette = light_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap) elif palette.startswith("dark:"): # light palette to color specified in string _, color = palette.split(":") reverse = color.endswith("_r") if reverse: color = color[:-2] palette = dark_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap) elif palette.startswith("blend:"): # blend palette between colors specified in string _, colors = palette.split(":") colors = colors.split(",") palette = blend_palette(colors, n_colors, as_cmap=as_cmap) else: try: # Perhaps a named matplotlib colormap? palette = mpl_palette(palette, n_colors, as_cmap=as_cmap) except (ValueError, KeyError): # Error class changed in mpl36 raise ValueError(f"{palette!r} is not a valid palette name") if desat is not None: palette = [desaturate(c, desat) for c in palette] if not as_cmap: # Always return as many colors as we asked for pal_cycle = cycle(palette) palette = [next(pal_cycle) for _ in range(n_colors)] # Always return in r, g, b tuple format try: palette = map(mpl.colors.colorConverter.to_rgb, palette) palette = _ColorPalette(palette) except ValueError: raise ValueError(f"Could not generate a palette for {palette}") return palette
Return a list of colors or continuous colormap defining a palette. Possible ``palette`` values include: - Name of a seaborn palette (deep, muted, bright, pastel, dark, colorblind) - Name of matplotlib colormap - 'husl' or 'hls' - 'ch:<cubehelix arguments>' - 'light:<color>', 'dark:<color>', 'blend:<color>,<color>', - A sequence of colors in any format matplotlib accepts Calling this function with ``palette=None`` will return the current matplotlib color cycle. This function can also be used in a ``with`` statement to temporarily set the color cycle for a plot or set of plots. See the :ref:`tutorial <palette_tutorial>` for more information. Parameters ---------- palette : None, string, or sequence, optional Name of palette or None to return current palette. If a sequence, input colors are used but possibly cycled and desaturated. n_colors : int, optional Number of colors in the palette. If ``None``, the default will depend on how ``palette`` is specified. Named palettes default to 6 colors, but grabbing the current palette or passing in a list of colors will not change the number of colors unless this is specified. Asking for more colors than exist in the palette will cause it to cycle. Ignored when ``as_cmap`` is True. desat : float, optional Proportion to desaturate each color by. as_cmap : bool If True, return a :class:`matplotlib.colors.ListedColormap`. Returns ------- list of RGB tuples or :class:`matplotlib.colors.ListedColormap` See Also -------- set_palette : Set the default color cycle for all plots. set_color_codes : Reassign color codes like ``"b"``, ``"g"``, etc. to colors from one of the seaborn palettes. Examples -------- .. include:: ../docstrings/color_palette.rst
color_palette
python
mwaskom/seaborn
seaborn/palettes.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
BSD-3-Clause
def hls_palette(n_colors=6, h=.01, l=.6, s=.65, as_cmap=False): # noqa """ Return hues with constant lightness and saturation in the HLS system. The hues are evenly sampled along a circular path. The resulting palette will be appropriate for categorical or cyclical data. The `h`, `l`, and `s` values should be between 0 and 1. .. note:: While the separation of the resulting colors will be mathematically constant, the HLS system does not construct a perceptually-uniform space, so their apparent intensity will vary. Parameters ---------- n_colors : int Number of colors in the palette. h : float The value of the first hue. l : float The lightness value. s : float The saturation intensity. as_cmap : bool If True, return a matplotlib colormap object. Returns ------- palette list of RGB tuples or :class:`matplotlib.colors.ListedColormap` See Also -------- husl_palette : Make a palette using evenly spaced hues in the HUSL system. Examples -------- .. include:: ../docstrings/hls_palette.rst """ if as_cmap: n_colors = 256 hues = np.linspace(0, 1, int(n_colors) + 1)[:-1] hues += h hues %= 1 hues -= hues.astype(int) palette = [colorsys.hls_to_rgb(h_i, l, s) for h_i in hues] if as_cmap: return mpl.colors.ListedColormap(palette, "hls") else: return _ColorPalette(palette)
Return hues with constant lightness and saturation in the HLS system. The hues are evenly sampled along a circular path. The resulting palette will be appropriate for categorical or cyclical data. The `h`, `l`, and `s` values should be between 0 and 1. .. note:: While the separation of the resulting colors will be mathematically constant, the HLS system does not construct a perceptually-uniform space, so their apparent intensity will vary. Parameters ---------- n_colors : int Number of colors in the palette. h : float The value of the first hue. l : float The lightness value. s : float The saturation intensity. as_cmap : bool If True, return a matplotlib colormap object. Returns ------- palette list of RGB tuples or :class:`matplotlib.colors.ListedColormap` See Also -------- husl_palette : Make a palette using evenly spaced hues in the HUSL system. Examples -------- .. include:: ../docstrings/hls_palette.rst
hls_palette
python
mwaskom/seaborn
seaborn/palettes.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
BSD-3-Clause
def husl_palette(n_colors=6, h=.01, s=.9, l=.65, as_cmap=False): # noqa """ Return hues with constant lightness and saturation in the HUSL system. The hues are evenly sampled along a circular path. The resulting palette will be appropriate for categorical or cyclical data. The `h`, `l`, and `s` values should be between 0 and 1. This function is similar to :func:`hls_palette`, but it uses a nonlinear color space that is more perceptually uniform. Parameters ---------- n_colors : int Number of colors in the palette. h : float The value of the first hue. l : float The lightness value. s : float The saturation intensity. as_cmap : bool If True, return a matplotlib colormap object. Returns ------- palette list of RGB tuples or :class:`matplotlib.colors.ListedColormap` See Also -------- hls_palette : Make a palette using evenly spaced hues in the HSL system. Examples -------- .. include:: ../docstrings/husl_palette.rst """ if as_cmap: n_colors = 256 hues = np.linspace(0, 1, int(n_colors) + 1)[:-1] hues += h hues %= 1 hues *= 359 s *= 99 l *= 99 # noqa palette = [_color_to_rgb((h_i, s, l), input="husl") for h_i in hues] if as_cmap: return mpl.colors.ListedColormap(palette, "hsl") else: return _ColorPalette(palette)
Return hues with constant lightness and saturation in the HUSL system. The hues are evenly sampled along a circular path. The resulting palette will be appropriate for categorical or cyclical data. The `h`, `l`, and `s` values should be between 0 and 1. This function is similar to :func:`hls_palette`, but it uses a nonlinear color space that is more perceptually uniform. Parameters ---------- n_colors : int Number of colors in the palette. h : float The value of the first hue. l : float The lightness value. s : float The saturation intensity. as_cmap : bool If True, return a matplotlib colormap object. Returns ------- palette list of RGB tuples or :class:`matplotlib.colors.ListedColormap` See Also -------- hls_palette : Make a palette using evenly spaced hues in the HSL system. Examples -------- .. include:: ../docstrings/husl_palette.rst
husl_palette
python
mwaskom/seaborn
seaborn/palettes.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
BSD-3-Clause
def mpl_palette(name, n_colors=6, as_cmap=False): """ Return a palette or colormap from the matplotlib registry. For continuous palettes, evenly-spaced discrete samples are chosen while excluding the minimum and maximum value in the colormap to provide better contrast at the extremes. For qualitative palettes (e.g. those from colorbrewer), exact values are indexed (rather than interpolated), but fewer than `n_colors` can be returned if the palette does not define that many. Parameters ---------- name : string Name of the palette. This should be a named matplotlib colormap. n_colors : int Number of discrete colors in the palette. Returns ------- list of RGB tuples or :class:`matplotlib.colors.ListedColormap` Examples -------- .. include:: ../docstrings/mpl_palette.rst """ if name.endswith("_d"): sub_name = name[:-2] if sub_name.endswith("_r"): reverse = True sub_name = sub_name[:-2] else: reverse = False pal = color_palette(sub_name, 2) + ["#333333"] if reverse: pal = pal[::-1] cmap = blend_palette(pal, n_colors, as_cmap=True) else: cmap = get_colormap(name) if name in MPL_QUAL_PALS: bins = np.linspace(0, 1, MPL_QUAL_PALS[name])[:n_colors] else: bins = np.linspace(0, 1, int(n_colors) + 2)[1:-1] palette = list(map(tuple, cmap(bins)[:, :3])) if as_cmap: return cmap else: return _ColorPalette(palette)
Return a palette or colormap from the matplotlib registry. For continuous palettes, evenly-spaced discrete samples are chosen while excluding the minimum and maximum value in the colormap to provide better contrast at the extremes. For qualitative palettes (e.g. those from colorbrewer), exact values are indexed (rather than interpolated), but fewer than `n_colors` can be returned if the palette does not define that many. Parameters ---------- name : string Name of the palette. This should be a named matplotlib colormap. n_colors : int Number of discrete colors in the palette. Returns ------- list of RGB tuples or :class:`matplotlib.colors.ListedColormap` Examples -------- .. include:: ../docstrings/mpl_palette.rst
mpl_palette
python
mwaskom/seaborn
seaborn/palettes.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
BSD-3-Clause
def _color_to_rgb(color, input): """Add some more flexibility to color choices.""" if input == "hls": color = colorsys.hls_to_rgb(*color) elif input == "husl": color = husl.husl_to_rgb(*color) color = tuple(np.clip(color, 0, 1)) elif input == "xkcd": color = xkcd_rgb[color] return mpl.colors.to_rgb(color)
Add some more flexibility to color choices.
_color_to_rgb
python
mwaskom/seaborn
seaborn/palettes.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
BSD-3-Clause