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 dark_palette(color, n_colors=6, reverse=False, as_cmap=False, input="rgb"):
"""Make a sequential palette that blends from dark to ``color``.
This kind of palette is good for data that range between relatively
uninteresting low values and interesting high values.
The ``color`` parameter can be specified in a number of ways, including
all options for defining a color in matplotlib and several additional
color spaces that are handled by seaborn. You can also use the database
of named colors from the XKCD color survey.
If you are using the IPython notebook, you can also choose this palette
interactively with the :func:`choose_dark_palette` function.
Parameters
----------
color : base color for high values
hex, rgb-tuple, or html color name
n_colors : int, optional
number of colors in the palette
reverse : bool, optional
if True, reverse the direction of the blend
as_cmap : bool, optional
If True, return a :class:`matplotlib.colors.ListedColormap`.
input : {'rgb', 'hls', 'husl', xkcd'}
Color space to interpret the input color. The first three options
apply to tuple inputs and the latter applies to string inputs.
Returns
-------
palette
list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
See Also
--------
light_palette : Create a sequential palette with bright low values.
diverging_palette : Create a diverging palette with two colors.
Examples
--------
.. include:: ../docstrings/dark_palette.rst
"""
rgb = _color_to_rgb(color, input)
hue, sat, _ = husl.rgb_to_husl(*rgb)
gray_s, gray_l = .15 * sat, 15
gray = _color_to_rgb((hue, gray_s, gray_l), input="husl")
colors = [rgb, gray] if reverse else [gray, rgb]
return blend_palette(colors, n_colors, as_cmap)
|
Make a sequential palette that blends from dark to ``color``.
This kind of palette is good for data that range between relatively
uninteresting low values and interesting high values.
The ``color`` parameter can be specified in a number of ways, including
all options for defining a color in matplotlib and several additional
color spaces that are handled by seaborn. You can also use the database
of named colors from the XKCD color survey.
If you are using the IPython notebook, you can also choose this palette
interactively with the :func:`choose_dark_palette` function.
Parameters
----------
color : base color for high values
hex, rgb-tuple, or html color name
n_colors : int, optional
number of colors in the palette
reverse : bool, optional
if True, reverse the direction of the blend
as_cmap : bool, optional
If True, return a :class:`matplotlib.colors.ListedColormap`.
input : {'rgb', 'hls', 'husl', xkcd'}
Color space to interpret the input color. The first three options
apply to tuple inputs and the latter applies to string inputs.
Returns
-------
palette
list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
See Also
--------
light_palette : Create a sequential palette with bright low values.
diverging_palette : Create a diverging palette with two colors.
Examples
--------
.. include:: ../docstrings/dark_palette.rst
|
dark_palette
|
python
|
mwaskom/seaborn
|
seaborn/palettes.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
|
BSD-3-Clause
|
def light_palette(color, n_colors=6, reverse=False, as_cmap=False, input="rgb"):
"""Make a sequential palette that blends from light to ``color``.
The ``color`` parameter can be specified in a number of ways, including
all options for defining a color in matplotlib and several additional
color spaces that are handled by seaborn. You can also use the database
of named colors from the XKCD color survey.
If you are using a Jupyter notebook, you can also choose this palette
interactively with the :func:`choose_light_palette` function.
Parameters
----------
color : base color for high values
hex code, html color name, or tuple in `input` space.
n_colors : int, optional
number of colors in the palette
reverse : bool, optional
if True, reverse the direction of the blend
as_cmap : bool, optional
If True, return a :class:`matplotlib.colors.ListedColormap`.
input : {'rgb', 'hls', 'husl', xkcd'}
Color space to interpret the input color. The first three options
apply to tuple inputs and the latter applies to string inputs.
Returns
-------
palette
list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
See Also
--------
dark_palette : Create a sequential palette with dark low values.
diverging_palette : Create a diverging palette with two colors.
Examples
--------
.. include:: ../docstrings/light_palette.rst
"""
rgb = _color_to_rgb(color, input)
hue, sat, _ = husl.rgb_to_husl(*rgb)
gray_s, gray_l = .15 * sat, 95
gray = _color_to_rgb((hue, gray_s, gray_l), input="husl")
colors = [rgb, gray] if reverse else [gray, rgb]
return blend_palette(colors, n_colors, as_cmap)
|
Make a sequential palette that blends from light to ``color``.
The ``color`` parameter can be specified in a number of ways, including
all options for defining a color in matplotlib and several additional
color spaces that are handled by seaborn. You can also use the database
of named colors from the XKCD color survey.
If you are using a Jupyter notebook, you can also choose this palette
interactively with the :func:`choose_light_palette` function.
Parameters
----------
color : base color for high values
hex code, html color name, or tuple in `input` space.
n_colors : int, optional
number of colors in the palette
reverse : bool, optional
if True, reverse the direction of the blend
as_cmap : bool, optional
If True, return a :class:`matplotlib.colors.ListedColormap`.
input : {'rgb', 'hls', 'husl', xkcd'}
Color space to interpret the input color. The first three options
apply to tuple inputs and the latter applies to string inputs.
Returns
-------
palette
list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
See Also
--------
dark_palette : Create a sequential palette with dark low values.
diverging_palette : Create a diverging palette with two colors.
Examples
--------
.. include:: ../docstrings/light_palette.rst
|
light_palette
|
python
|
mwaskom/seaborn
|
seaborn/palettes.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
|
BSD-3-Clause
|
def diverging_palette(h_neg, h_pos, s=75, l=50, sep=1, n=6, # noqa
center="light", as_cmap=False):
"""Make a diverging palette between two HUSL colors.
If you are using the IPython notebook, you can also choose this palette
interactively with the :func:`choose_diverging_palette` function.
Parameters
----------
h_neg, h_pos : float in [0, 359]
Anchor hues for negative and positive extents of the map.
s : float in [0, 100], optional
Anchor saturation for both extents of the map.
l : float in [0, 100], optional
Anchor lightness for both extents of the map.
sep : int, optional
Size of the intermediate region.
n : int, optional
Number of colors in the palette (if not returning a cmap)
center : {"light", "dark"}, optional
Whether the center of the palette is light or dark
as_cmap : bool, optional
If True, return a :class:`matplotlib.colors.ListedColormap`.
Returns
-------
palette
list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
See Also
--------
dark_palette : Create a sequential palette with dark values.
light_palette : Create a sequential palette with light values.
Examples
--------
.. include: ../docstrings/diverging_palette.rst
"""
palfunc = dict(dark=dark_palette, light=light_palette)[center]
n_half = int(128 - (sep // 2))
neg = palfunc((h_neg, s, l), n_half, reverse=True, input="husl")
pos = palfunc((h_pos, s, l), n_half, input="husl")
midpoint = dict(light=[(.95, .95, .95)], dark=[(.133, .133, .133)])[center]
mid = midpoint * sep
pal = blend_palette(np.concatenate([neg, mid, pos]), n, as_cmap=as_cmap)
return pal
|
Make a diverging palette between two HUSL colors.
If you are using the IPython notebook, you can also choose this palette
interactively with the :func:`choose_diverging_palette` function.
Parameters
----------
h_neg, h_pos : float in [0, 359]
Anchor hues for negative and positive extents of the map.
s : float in [0, 100], optional
Anchor saturation for both extents of the map.
l : float in [0, 100], optional
Anchor lightness for both extents of the map.
sep : int, optional
Size of the intermediate region.
n : int, optional
Number of colors in the palette (if not returning a cmap)
center : {"light", "dark"}, optional
Whether the center of the palette is light or dark
as_cmap : bool, optional
If True, return a :class:`matplotlib.colors.ListedColormap`.
Returns
-------
palette
list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
See Also
--------
dark_palette : Create a sequential palette with dark values.
light_palette : Create a sequential palette with light values.
Examples
--------
.. include: ../docstrings/diverging_palette.rst
|
diverging_palette
|
python
|
mwaskom/seaborn
|
seaborn/palettes.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
|
BSD-3-Clause
|
def blend_palette(colors, n_colors=6, as_cmap=False, input="rgb"):
"""Make a palette that blends between a list of colors.
Parameters
----------
colors : sequence of colors in various formats interpreted by `input`
hex code, html color name, or tuple in `input` space.
n_colors : int, optional
Number of colors in the palette.
as_cmap : bool, optional
If True, return a :class:`matplotlib.colors.ListedColormap`.
Returns
-------
palette
list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
Examples
--------
.. include: ../docstrings/blend_palette.rst
"""
colors = [_color_to_rgb(color, input) for color in colors]
name = "blend"
pal = mpl.colors.LinearSegmentedColormap.from_list(name, colors)
if not as_cmap:
rgb_array = pal(np.linspace(0, 1, int(n_colors)))[:, :3] # no alpha
pal = _ColorPalette(map(tuple, rgb_array))
return pal
|
Make a palette that blends between a list of colors.
Parameters
----------
colors : sequence of colors in various formats interpreted by `input`
hex code, html color name, or tuple in `input` space.
n_colors : int, optional
Number of colors in the palette.
as_cmap : bool, optional
If True, return a :class:`matplotlib.colors.ListedColormap`.
Returns
-------
palette
list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
Examples
--------
.. include: ../docstrings/blend_palette.rst
|
blend_palette
|
python
|
mwaskom/seaborn
|
seaborn/palettes.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
|
BSD-3-Clause
|
def xkcd_palette(colors):
"""Make a palette with color names from the xkcd color survey.
See xkcd for the full list of colors: https://xkcd.com/color/rgb/
This is just a simple wrapper around the `seaborn.xkcd_rgb` dictionary.
Parameters
----------
colors : list of strings
List of keys in the `seaborn.xkcd_rgb` dictionary.
Returns
-------
palette
A list of colors as RGB tuples.
See Also
--------
crayon_palette : Make a palette with Crayola crayon colors.
"""
palette = [xkcd_rgb[name] for name in colors]
return color_palette(palette, len(palette))
|
Make a palette with color names from the xkcd color survey.
See xkcd for the full list of colors: https://xkcd.com/color/rgb/
This is just a simple wrapper around the `seaborn.xkcd_rgb` dictionary.
Parameters
----------
colors : list of strings
List of keys in the `seaborn.xkcd_rgb` dictionary.
Returns
-------
palette
A list of colors as RGB tuples.
See Also
--------
crayon_palette : Make a palette with Crayola crayon colors.
|
xkcd_palette
|
python
|
mwaskom/seaborn
|
seaborn/palettes.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
|
BSD-3-Clause
|
def crayon_palette(colors):
"""Make a palette with color names from Crayola crayons.
Colors are taken from here:
https://en.wikipedia.org/wiki/List_of_Crayola_crayon_colors
This is just a simple wrapper around the `seaborn.crayons` dictionary.
Parameters
----------
colors : list of strings
List of keys in the `seaborn.crayons` dictionary.
Returns
-------
palette
A list of colors as RGB tuples.
See Also
--------
xkcd_palette : Make a palette with named colors from the XKCD color survey.
"""
palette = [crayons[name] for name in colors]
return color_palette(palette, len(palette))
|
Make a palette with color names from Crayola crayons.
Colors are taken from here:
https://en.wikipedia.org/wiki/List_of_Crayola_crayon_colors
This is just a simple wrapper around the `seaborn.crayons` dictionary.
Parameters
----------
colors : list of strings
List of keys in the `seaborn.crayons` dictionary.
Returns
-------
palette
A list of colors as RGB tuples.
See Also
--------
xkcd_palette : Make a palette with named colors from the XKCD color survey.
|
crayon_palette
|
python
|
mwaskom/seaborn
|
seaborn/palettes.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
|
BSD-3-Clause
|
def cubehelix_palette(n_colors=6, start=0, rot=.4, gamma=1.0, hue=0.8,
light=.85, dark=.15, reverse=False, as_cmap=False):
"""Make a sequential palette from the cubehelix system.
This produces a colormap with linearly-decreasing (or increasing)
brightness. That means that information will be preserved if printed to
black and white or viewed by someone who is colorblind. "cubehelix" is
also available as a matplotlib-based palette, but this function gives the
user more control over the look of the palette and has a different set of
defaults.
In addition to using this function, it is also possible to generate a
cubehelix palette generally in seaborn using a string starting with
`ch:` and containing other parameters (e.g. `"ch:s=.25,r=-.5"`).
Parameters
----------
n_colors : int
Number of colors in the palette.
start : float, 0 <= start <= 3
The hue value at the start of the helix.
rot : float
Rotations around the hue wheel over the range of the palette.
gamma : float 0 <= gamma
Nonlinearity to emphasize dark (gamma < 1) or light (gamma > 1) colors.
hue : float, 0 <= hue <= 1
Saturation of the colors.
dark : float 0 <= dark <= 1
Intensity of the darkest color in the palette.
light : float 0 <= light <= 1
Intensity of the lightest color in the palette.
reverse : bool
If True, the palette will go from dark to light.
as_cmap : bool
If True, return a :class:`matplotlib.colors.ListedColormap`.
Returns
-------
palette
list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
See Also
--------
choose_cubehelix_palette : Launch an interactive widget to select cubehelix
palette parameters.
dark_palette : Create a sequential palette with dark low values.
light_palette : Create a sequential palette with bright low values.
References
----------
Green, D. A. (2011). "A colour scheme for the display of astronomical
intensity images". Bulletin of the Astromical Society of India, Vol. 39,
p. 289-295.
Examples
--------
.. include:: ../docstrings/cubehelix_palette.rst
"""
def get_color_function(p0, p1):
# Copied from matplotlib because it lives in private module
def color(x):
# Apply gamma factor to emphasise low or high intensity values
xg = x ** gamma
# Calculate amplitude and angle of deviation from the black
# to white diagonal in the plane of constant
# perceived intensity.
a = hue * xg * (1 - xg) / 2
phi = 2 * np.pi * (start / 3 + rot * x)
return xg + a * (p0 * np.cos(phi) + p1 * np.sin(phi))
return color
cdict = {
"red": get_color_function(-0.14861, 1.78277),
"green": get_color_function(-0.29227, -0.90649),
"blue": get_color_function(1.97294, 0.0),
}
cmap = mpl.colors.LinearSegmentedColormap("cubehelix", cdict)
x = np.linspace(light, dark, int(n_colors))
pal = cmap(x)[:, :3].tolist()
if reverse:
pal = pal[::-1]
if as_cmap:
x_256 = np.linspace(light, dark, 256)
if reverse:
x_256 = x_256[::-1]
pal_256 = cmap(x_256)
cmap = mpl.colors.ListedColormap(pal_256, "seaborn_cubehelix")
return cmap
else:
return _ColorPalette(pal)
|
Make a sequential palette from the cubehelix system.
This produces a colormap with linearly-decreasing (or increasing)
brightness. That means that information will be preserved if printed to
black and white or viewed by someone who is colorblind. "cubehelix" is
also available as a matplotlib-based palette, but this function gives the
user more control over the look of the palette and has a different set of
defaults.
In addition to using this function, it is also possible to generate a
cubehelix palette generally in seaborn using a string starting with
`ch:` and containing other parameters (e.g. `"ch:s=.25,r=-.5"`).
Parameters
----------
n_colors : int
Number of colors in the palette.
start : float, 0 <= start <= 3
The hue value at the start of the helix.
rot : float
Rotations around the hue wheel over the range of the palette.
gamma : float 0 <= gamma
Nonlinearity to emphasize dark (gamma < 1) or light (gamma > 1) colors.
hue : float, 0 <= hue <= 1
Saturation of the colors.
dark : float 0 <= dark <= 1
Intensity of the darkest color in the palette.
light : float 0 <= light <= 1
Intensity of the lightest color in the palette.
reverse : bool
If True, the palette will go from dark to light.
as_cmap : bool
If True, return a :class:`matplotlib.colors.ListedColormap`.
Returns
-------
palette
list of RGB tuples or :class:`matplotlib.colors.ListedColormap`
See Also
--------
choose_cubehelix_palette : Launch an interactive widget to select cubehelix
palette parameters.
dark_palette : Create a sequential palette with dark low values.
light_palette : Create a sequential palette with bright low values.
References
----------
Green, D. A. (2011). "A colour scheme for the display of astronomical
intensity images". Bulletin of the Astromical Society of India, Vol. 39,
p. 289-295.
Examples
--------
.. include:: ../docstrings/cubehelix_palette.rst
|
cubehelix_palette
|
python
|
mwaskom/seaborn
|
seaborn/palettes.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
|
BSD-3-Clause
|
def _parse_cubehelix_args(argstr):
"""Turn stringified cubehelix params into args/kwargs."""
if argstr.startswith("ch:"):
argstr = argstr[3:]
if argstr.endswith("_r"):
reverse = True
argstr = argstr[:-2]
else:
reverse = False
if not argstr:
return [], {"reverse": reverse}
all_args = argstr.split(",")
args = [float(a.strip(" ")) for a in all_args if "=" not in a]
kwargs = [a.split("=") for a in all_args if "=" in a]
kwargs = {k.strip(" "): float(v.strip(" ")) for k, v in kwargs}
kwarg_map = dict(
s="start", r="rot", g="gamma",
h="hue", l="light", d="dark", # noqa: E741
)
kwargs = {kwarg_map.get(k, k): v for k, v in kwargs.items()}
if reverse:
kwargs["reverse"] = True
return args, kwargs
|
Turn stringified cubehelix params into args/kwargs.
|
_parse_cubehelix_args
|
python
|
mwaskom/seaborn
|
seaborn/palettes.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
|
BSD-3-Clause
|
def set_color_codes(palette="deep"):
"""Change how matplotlib color shorthands are interpreted.
Calling this will change how shorthand codes like "b" or "g"
are interpreted by matplotlib in subsequent plots.
Parameters
----------
palette : {deep, muted, pastel, dark, bright, colorblind}
Named seaborn palette to use as the source of colors.
See Also
--------
set : Color codes can be set through the high-level seaborn style
manager.
set_palette : Color codes can also be set through the function that
sets the matplotlib color cycle.
"""
if palette == "reset":
colors = [
(0., 0., 1.),
(0., .5, 0.),
(1., 0., 0.),
(.75, 0., .75),
(.75, .75, 0.),
(0., .75, .75),
(0., 0., 0.)
]
elif not isinstance(palette, str):
err = "set_color_codes requires a named seaborn palette"
raise TypeError(err)
elif palette in SEABORN_PALETTES:
if not palette.endswith("6"):
palette = palette + "6"
colors = SEABORN_PALETTES[palette] + [(.1, .1, .1)]
else:
err = f"Cannot set colors with palette '{palette}'"
raise ValueError(err)
for code, color in zip("bgrmyck", colors):
rgb = mpl.colors.colorConverter.to_rgb(color)
mpl.colors.colorConverter.colors[code] = rgb
|
Change how matplotlib color shorthands are interpreted.
Calling this will change how shorthand codes like "b" or "g"
are interpreted by matplotlib in subsequent plots.
Parameters
----------
palette : {deep, muted, pastel, dark, bright, colorblind}
Named seaborn palette to use as the source of colors.
See Also
--------
set : Color codes can be set through the high-level seaborn style
manager.
set_palette : Color codes can also be set through the function that
sets the matplotlib color cycle.
|
set_color_codes
|
python
|
mwaskom/seaborn
|
seaborn/palettes.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
|
BSD-3-Clause
|
def set_theme(context="notebook", style="darkgrid", palette="deep",
font="sans-serif", font_scale=1, color_codes=True, rc=None):
"""
Set aspects of the visual theme for all matplotlib and seaborn plots.
This function changes the global defaults for all plots using the
matplotlib rcParams system. The themeing is decomposed into several distinct
sets of parameter values.
The options are illustrated in the :doc:`aesthetics <../tutorial/aesthetics>`
and :doc:`color palette <../tutorial/color_palettes>` tutorials.
Parameters
----------
context : string or dict
Scaling parameters, see :func:`plotting_context`.
style : string or dict
Axes style parameters, see :func:`axes_style`.
palette : string or sequence
Color palette, see :func:`color_palette`.
font : string
Font family, see matplotlib font manager.
font_scale : float, optional
Separate scaling factor to independently scale the size of the
font elements.
color_codes : bool
If ``True`` and ``palette`` is a seaborn palette, remap the shorthand
color codes (e.g. "b", "g", "r", etc.) to the colors from this palette.
rc : dict or None
Dictionary of rc parameter mappings to override the above.
Examples
--------
.. include:: ../docstrings/set_theme.rst
"""
set_context(context, font_scale)
set_style(style, rc={"font.family": font})
set_palette(palette, color_codes=color_codes)
if rc is not None:
mpl.rcParams.update(rc)
|
Set aspects of the visual theme for all matplotlib and seaborn plots.
This function changes the global defaults for all plots using the
matplotlib rcParams system. The themeing is decomposed into several distinct
sets of parameter values.
The options are illustrated in the :doc:`aesthetics <../tutorial/aesthetics>`
and :doc:`color palette <../tutorial/color_palettes>` tutorials.
Parameters
----------
context : string or dict
Scaling parameters, see :func:`plotting_context`.
style : string or dict
Axes style parameters, see :func:`axes_style`.
palette : string or sequence
Color palette, see :func:`color_palette`.
font : string
Font family, see matplotlib font manager.
font_scale : float, optional
Separate scaling factor to independently scale the size of the
font elements.
color_codes : bool
If ``True`` and ``palette`` is a seaborn palette, remap the shorthand
color codes (e.g. "b", "g", "r", etc.) to the colors from this palette.
rc : dict or None
Dictionary of rc parameter mappings to override the above.
Examples
--------
.. include:: ../docstrings/set_theme.rst
|
set_theme
|
python
|
mwaskom/seaborn
|
seaborn/rcmod.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/rcmod.py
|
BSD-3-Clause
|
def axes_style(style=None, rc=None):
"""
Get the parameters that control the general style of the plots.
The style parameters control properties like the color of the background and
whether a grid is enabled by default. This is accomplished using the
matplotlib rcParams system.
The options are illustrated in the
:doc:`aesthetics tutorial <../tutorial/aesthetics>`.
This function can also be used as a context manager to temporarily
alter the global defaults. See :func:`set_theme` or :func:`set_style`
to modify the global defaults for all plots.
Parameters
----------
style : None, dict, or one of {darkgrid, whitegrid, dark, white, ticks}
A dictionary of parameters or the name of a preconfigured style.
rc : dict, optional
Parameter mappings to override the values in the preset seaborn
style dictionaries. This only updates parameters that are
considered part of the style definition.
Examples
--------
.. include:: ../docstrings/axes_style.rst
"""
if style is None:
style_dict = {k: mpl.rcParams[k] for k in _style_keys}
elif isinstance(style, dict):
style_dict = style
else:
styles = ["white", "dark", "whitegrid", "darkgrid", "ticks"]
if style not in styles:
raise ValueError(f"style must be one of {', '.join(styles)}")
# Define colors here
dark_gray = ".15"
light_gray = ".8"
# Common parameters
style_dict = {
"figure.facecolor": "white",
"axes.labelcolor": dark_gray,
"xtick.direction": "out",
"ytick.direction": "out",
"xtick.color": dark_gray,
"ytick.color": dark_gray,
"axes.axisbelow": True,
"grid.linestyle": "-",
"text.color": dark_gray,
"font.family": ["sans-serif"],
"font.sans-serif": ["Arial", "DejaVu Sans", "Liberation Sans",
"Bitstream Vera Sans", "sans-serif"],
"lines.solid_capstyle": "round",
"patch.edgecolor": "w",
"patch.force_edgecolor": True,
"image.cmap": "rocket",
"xtick.top": False,
"ytick.right": False,
}
# Set grid on or off
if "grid" in style:
style_dict.update({
"axes.grid": True,
})
else:
style_dict.update({
"axes.grid": False,
})
# Set the color of the background, spines, and grids
if style.startswith("dark"):
style_dict.update({
"axes.facecolor": "#EAEAF2",
"axes.edgecolor": "white",
"grid.color": "white",
"axes.spines.left": True,
"axes.spines.bottom": True,
"axes.spines.right": True,
"axes.spines.top": True,
})
elif style == "whitegrid":
style_dict.update({
"axes.facecolor": "white",
"axes.edgecolor": light_gray,
"grid.color": light_gray,
"axes.spines.left": True,
"axes.spines.bottom": True,
"axes.spines.right": True,
"axes.spines.top": True,
})
elif style in ["white", "ticks"]:
style_dict.update({
"axes.facecolor": "white",
"axes.edgecolor": dark_gray,
"grid.color": light_gray,
"axes.spines.left": True,
"axes.spines.bottom": True,
"axes.spines.right": True,
"axes.spines.top": True,
})
# Show or hide the axes ticks
if style == "ticks":
style_dict.update({
"xtick.bottom": True,
"ytick.left": True,
})
else:
style_dict.update({
"xtick.bottom": False,
"ytick.left": False,
})
# Remove entries that are not defined in the base list of valid keys
# This lets us handle matplotlib <=/> 2.0
style_dict = {k: v for k, v in style_dict.items() if k in _style_keys}
# Override these settings with the provided rc dictionary
if rc is not None:
rc = {k: v for k, v in rc.items() if k in _style_keys}
style_dict.update(rc)
# Wrap in an _AxesStyle object so this can be used in a with statement
style_object = _AxesStyle(style_dict)
return style_object
|
Get the parameters that control the general style of the plots.
The style parameters control properties like the color of the background and
whether a grid is enabled by default. This is accomplished using the
matplotlib rcParams system.
The options are illustrated in the
:doc:`aesthetics tutorial <../tutorial/aesthetics>`.
This function can also be used as a context manager to temporarily
alter the global defaults. See :func:`set_theme` or :func:`set_style`
to modify the global defaults for all plots.
Parameters
----------
style : None, dict, or one of {darkgrid, whitegrid, dark, white, ticks}
A dictionary of parameters or the name of a preconfigured style.
rc : dict, optional
Parameter mappings to override the values in the preset seaborn
style dictionaries. This only updates parameters that are
considered part of the style definition.
Examples
--------
.. include:: ../docstrings/axes_style.rst
|
axes_style
|
python
|
mwaskom/seaborn
|
seaborn/rcmod.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/rcmod.py
|
BSD-3-Clause
|
def plotting_context(context=None, font_scale=1, rc=None):
"""
Get the parameters that control the scaling of plot elements.
These parameters correspond to label size, line thickness, etc. For more
information, see the :doc:`aesthetics tutorial <../tutorial/aesthetics>`.
The base context is "notebook", and the other contexts are "paper", "talk",
and "poster", which are version of the notebook parameters scaled by different
values. Font elements can also be scaled independently of (but relative to)
the other values.
This function can also be used as a context manager to temporarily
alter the global defaults. See :func:`set_theme` or :func:`set_context`
to modify the global defaults for all plots.
Parameters
----------
context : None, dict, or one of {paper, notebook, talk, poster}
A dictionary of parameters or the name of a preconfigured set.
font_scale : float, optional
Separate scaling factor to independently scale the size of the
font elements.
rc : dict, optional
Parameter mappings to override the values in the preset seaborn
context dictionaries. This only updates parameters that are
considered part of the context definition.
Examples
--------
.. include:: ../docstrings/plotting_context.rst
"""
if context is None:
context_dict = {k: mpl.rcParams[k] for k in _context_keys}
elif isinstance(context, dict):
context_dict = context
else:
contexts = ["paper", "notebook", "talk", "poster"]
if context not in contexts:
raise ValueError(f"context must be in {', '.join(contexts)}")
# Set up dictionary of default parameters
texts_base_context = {
"font.size": 12,
"axes.labelsize": 12,
"axes.titlesize": 12,
"xtick.labelsize": 11,
"ytick.labelsize": 11,
"legend.fontsize": 11,
"legend.title_fontsize": 12,
}
base_context = {
"axes.linewidth": 1.25,
"grid.linewidth": 1,
"lines.linewidth": 1.5,
"lines.markersize": 6,
"patch.linewidth": 1,
"xtick.major.width": 1.25,
"ytick.major.width": 1.25,
"xtick.minor.width": 1,
"ytick.minor.width": 1,
"xtick.major.size": 6,
"ytick.major.size": 6,
"xtick.minor.size": 4,
"ytick.minor.size": 4,
}
base_context.update(texts_base_context)
# Scale all the parameters by the same factor depending on the context
scaling = dict(paper=.8, notebook=1, talk=1.5, poster=2)[context]
context_dict = {k: v * scaling for k, v in base_context.items()}
# Now independently scale the fonts
font_keys = texts_base_context.keys()
font_dict = {k: context_dict[k] * font_scale for k in font_keys}
context_dict.update(font_dict)
# Override these settings with the provided rc dictionary
if rc is not None:
rc = {k: v for k, v in rc.items() if k in _context_keys}
context_dict.update(rc)
# Wrap in a _PlottingContext object so this can be used in a with statement
context_object = _PlottingContext(context_dict)
return context_object
|
Get the parameters that control the scaling of plot elements.
These parameters correspond to label size, line thickness, etc. For more
information, see the :doc:`aesthetics tutorial <../tutorial/aesthetics>`.
The base context is "notebook", and the other contexts are "paper", "talk",
and "poster", which are version of the notebook parameters scaled by different
values. Font elements can also be scaled independently of (but relative to)
the other values.
This function can also be used as a context manager to temporarily
alter the global defaults. See :func:`set_theme` or :func:`set_context`
to modify the global defaults for all plots.
Parameters
----------
context : None, dict, or one of {paper, notebook, talk, poster}
A dictionary of parameters or the name of a preconfigured set.
font_scale : float, optional
Separate scaling factor to independently scale the size of the
font elements.
rc : dict, optional
Parameter mappings to override the values in the preset seaborn
context dictionaries. This only updates parameters that are
considered part of the context definition.
Examples
--------
.. include:: ../docstrings/plotting_context.rst
|
plotting_context
|
python
|
mwaskom/seaborn
|
seaborn/rcmod.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/rcmod.py
|
BSD-3-Clause
|
def set_palette(palette, n_colors=None, desat=None, color_codes=False):
"""Set the matplotlib color cycle using a seaborn palette.
Parameters
----------
palette : seaborn color palette | matplotlib colormap | hls | husl
Palette definition. Should be something :func:`color_palette` can process.
n_colors : int
Number of colors in the cycle. The default number of colors will depend
on the format of ``palette``, see the :func:`color_palette`
documentation for more information.
desat : float
Proportion to desaturate each color by.
color_codes : bool
If ``True`` and ``palette`` is a seaborn palette, remap the shorthand
color codes (e.g. "b", "g", "r", etc.) to the colors from this palette.
See Also
--------
color_palette : build a color palette or set the color cycle temporarily
in a ``with`` statement.
set_context : set parameters to scale plot elements
set_style : set the default parameters for figure style
"""
colors = palettes.color_palette(palette, n_colors, desat)
cyl = cycler('color', colors)
mpl.rcParams['axes.prop_cycle'] = cyl
if color_codes:
try:
palettes.set_color_codes(palette)
except (ValueError, TypeError):
pass
|
Set the matplotlib color cycle using a seaborn palette.
Parameters
----------
palette : seaborn color palette | matplotlib colormap | hls | husl
Palette definition. Should be something :func:`color_palette` can process.
n_colors : int
Number of colors in the cycle. The default number of colors will depend
on the format of ``palette``, see the :func:`color_palette`
documentation for more information.
desat : float
Proportion to desaturate each color by.
color_codes : bool
If ``True`` and ``palette`` is a seaborn palette, remap the shorthand
color codes (e.g. "b", "g", "r", etc.) to the colors from this palette.
See Also
--------
color_palette : build a color palette or set the color cycle temporarily
in a ``with`` statement.
set_context : set parameters to scale plot elements
set_style : set the default parameters for figure style
|
set_palette
|
python
|
mwaskom/seaborn
|
seaborn/rcmod.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/rcmod.py
|
BSD-3-Clause
|
def establish_variables(self, data, **kws):
"""Extract variables from data or use directly."""
self.data = data
# Validate the inputs
any_strings = any([isinstance(v, str) for v in kws.values()])
if any_strings and data is None:
raise ValueError("Must pass `data` if using named variables.")
# Set the variables
for var, val in kws.items():
if isinstance(val, str):
vector = data[val]
elif isinstance(val, list):
vector = np.asarray(val)
else:
vector = val
if vector is not None and vector.shape != (1,):
vector = np.squeeze(vector)
if np.ndim(vector) > 1:
err = "regplot inputs must be 1d"
raise ValueError(err)
setattr(self, var, vector)
|
Extract variables from data or use directly.
|
establish_variables
|
python
|
mwaskom/seaborn
|
seaborn/regression.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/regression.py
|
BSD-3-Clause
|
def scatter_data(self):
"""Data where each observation is a point."""
x_j = self.x_jitter
if x_j is None:
x = self.x
else:
x = self.x + np.random.uniform(-x_j, x_j, len(self.x))
y_j = self.y_jitter
if y_j is None:
y = self.y
else:
y = self.y + np.random.uniform(-y_j, y_j, len(self.y))
return x, y
|
Data where each observation is a point.
|
scatter_data
|
python
|
mwaskom/seaborn
|
seaborn/regression.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/regression.py
|
BSD-3-Clause
|
def estimate_data(self):
"""Data with a point estimate and CI for each discrete x value."""
x, y = self.x_discrete, self.y
vals = sorted(np.unique(x))
points, cis = [], []
for val in vals:
# Get the point estimate of the y variable
_y = y[x == val]
est = self.x_estimator(_y)
points.append(est)
# Compute the confidence interval for this estimate
if self.x_ci is None:
cis.append(None)
else:
units = None
if self.x_ci == "sd":
sd = np.std(_y)
_ci = est - sd, est + sd
else:
if self.units is not None:
units = self.units[x == val]
boots = algo.bootstrap(_y,
func=self.x_estimator,
n_boot=self.n_boot,
units=units,
seed=self.seed)
_ci = utils.ci(boots, self.x_ci)
cis.append(_ci)
return vals, points, cis
|
Data with a point estimate and CI for each discrete x value.
|
estimate_data
|
python
|
mwaskom/seaborn
|
seaborn/regression.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/regression.py
|
BSD-3-Clause
|
def _check_statsmodels(self):
"""Check whether statsmodels is installed if any boolean options require it."""
options = "logistic", "robust", "lowess"
err = "`{}=True` requires statsmodels, an optional dependency, to be installed."
for option in options:
if getattr(self, option) and not _has_statsmodels:
raise RuntimeError(err.format(option))
|
Check whether statsmodels is installed if any boolean options require it.
|
_check_statsmodels
|
python
|
mwaskom/seaborn
|
seaborn/regression.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/regression.py
|
BSD-3-Clause
|
def fit_fast(self, grid):
"""Low-level regression and prediction using linear algebra."""
def reg_func(_x, _y):
return np.linalg.pinv(_x).dot(_y)
X, y = np.c_[np.ones(len(self.x)), self.x], self.y
grid = np.c_[np.ones(len(grid)), grid]
yhat = grid.dot(reg_func(X, y))
if self.ci is None:
return yhat, None
beta_boots = algo.bootstrap(X, y,
func=reg_func,
n_boot=self.n_boot,
units=self.units,
seed=self.seed).T
yhat_boots = grid.dot(beta_boots).T
return yhat, yhat_boots
|
Low-level regression and prediction using linear algebra.
|
fit_fast
|
python
|
mwaskom/seaborn
|
seaborn/regression.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/regression.py
|
BSD-3-Clause
|
def fit_poly(self, grid, order):
"""Regression using numpy polyfit for higher-order trends."""
def reg_func(_x, _y):
return np.polyval(np.polyfit(_x, _y, order), grid)
x, y = self.x, self.y
yhat = reg_func(x, y)
if self.ci is None:
return yhat, None
yhat_boots = algo.bootstrap(x, y,
func=reg_func,
n_boot=self.n_boot,
units=self.units,
seed=self.seed)
return yhat, yhat_boots
|
Regression using numpy polyfit for higher-order trends.
|
fit_poly
|
python
|
mwaskom/seaborn
|
seaborn/regression.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/regression.py
|
BSD-3-Clause
|
def fit_statsmodels(self, grid, model, **kwargs):
"""More general regression function using statsmodels objects."""
import statsmodels.tools.sm_exceptions as sme
X, y = np.c_[np.ones(len(self.x)), self.x], self.y
grid = np.c_[np.ones(len(grid)), grid]
def reg_func(_x, _y):
err_classes = (sme.PerfectSeparationError,)
try:
with warnings.catch_warnings():
if hasattr(sme, "PerfectSeparationWarning"):
# statsmodels>=0.14.0
warnings.simplefilter("error", sme.PerfectSeparationWarning)
err_classes = (*err_classes, sme.PerfectSeparationWarning)
yhat = model(_y, _x, **kwargs).fit().predict(grid)
except err_classes:
yhat = np.empty(len(grid))
yhat.fill(np.nan)
return yhat
yhat = reg_func(X, y)
if self.ci is None:
return yhat, None
yhat_boots = algo.bootstrap(X, y,
func=reg_func,
n_boot=self.n_boot,
units=self.units,
seed=self.seed)
return yhat, yhat_boots
|
More general regression function using statsmodels objects.
|
fit_statsmodels
|
python
|
mwaskom/seaborn
|
seaborn/regression.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/regression.py
|
BSD-3-Clause
|
def fit_lowess(self):
"""Fit a locally-weighted regression, which returns its own grid."""
from statsmodels.nonparametric.smoothers_lowess import lowess
grid, yhat = lowess(self.y, self.x).T
return grid, yhat
|
Fit a locally-weighted regression, which returns its own grid.
|
fit_lowess
|
python
|
mwaskom/seaborn
|
seaborn/regression.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/regression.py
|
BSD-3-Clause
|
def fit_logx(self, grid):
"""Fit the model in log-space."""
X, y = np.c_[np.ones(len(self.x)), self.x], self.y
grid = np.c_[np.ones(len(grid)), np.log(grid)]
def reg_func(_x, _y):
_x = np.c_[_x[:, 0], np.log(_x[:, 1])]
return np.linalg.pinv(_x).dot(_y)
yhat = grid.dot(reg_func(X, y))
if self.ci is None:
return yhat, None
beta_boots = algo.bootstrap(X, y,
func=reg_func,
n_boot=self.n_boot,
units=self.units,
seed=self.seed).T
yhat_boots = grid.dot(beta_boots).T
return yhat, yhat_boots
|
Fit the model in log-space.
|
fit_logx
|
python
|
mwaskom/seaborn
|
seaborn/regression.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/regression.py
|
BSD-3-Clause
|
def bin_predictor(self, bins):
"""Discretize a predictor by assigning value to closest bin."""
x = np.asarray(self.x)
if np.isscalar(bins):
percentiles = np.linspace(0, 100, bins + 2)[1:-1]
bins = np.percentile(x, percentiles)
else:
bins = np.ravel(bins)
dist = np.abs(np.subtract.outer(x, bins))
x_binned = bins[np.argmin(dist, axis=1)].ravel()
return x_binned, bins
|
Discretize a predictor by assigning value to closest bin.
|
bin_predictor
|
python
|
mwaskom/seaborn
|
seaborn/regression.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/regression.py
|
BSD-3-Clause
|
def plot(self, ax, kws):
"""Draw the plot onto an axes, passing matplotlib kwargs."""
# Draw a test plot, using the passed in kwargs. The goal here is to
# honor both (a) the current state of the plot cycler and (b) the
# specified kwargs on all the lines we will draw, overriding when
# relevant with the data semantics. Note that we won't cycle
# internally; in other words, if `hue` is not used, all elements will
# have the same color, but they will have the color that you would have
# gotten from the corresponding matplotlib function, and calling the
# function will advance the axes property cycle.
kws = normalize_kwargs(kws, mpl.lines.Line2D)
kws.setdefault("markeredgewidth", 0.75)
kws.setdefault("markeredgecolor", "w")
# Set default error kwargs
err_kws = self.err_kws.copy()
if self.err_style == "band":
err_kws.setdefault("alpha", .2)
elif self.err_style == "bars":
pass
elif self.err_style is not None:
err = "`err_style` must be 'band' or 'bars', not {}"
raise ValueError(err.format(self.err_style))
# Initialize the aggregation object
weighted = "weight" in self.plot_data
agg = (WeightedAggregator if weighted else EstimateAggregator)(
self.estimator, self.errorbar, n_boot=self.n_boot, seed=self.seed,
)
# TODO abstract variable to aggregate over here-ish. Better name?
orient = self.orient
if orient not in {"x", "y"}:
err = f"`orient` must be either 'x' or 'y', not {orient!r}."
raise ValueError(err)
other = {"x": "y", "y": "x"}[orient]
# TODO How to handle NA? We don't want NA to propagate through to the
# estimate/CI when some values are present, but we would also like
# matplotlib to show "gaps" in the line when all values are missing.
# This is straightforward absent aggregation, but complicated with it.
# If we want to use nas, we need to conditionalize dropna in iter_data.
# Loop over the semantic subsets and add to the plot
grouping_vars = "hue", "size", "style"
for sub_vars, sub_data in self.iter_data(grouping_vars, from_comp_data=True):
if self.sort:
sort_vars = ["units", orient, other]
sort_cols = [var for var in sort_vars if var in self.variables]
sub_data = sub_data.sort_values(sort_cols)
if (
self.estimator is not None
and sub_data[orient].value_counts().max() > 1
):
if "units" in self.variables:
# TODO eventually relax this constraint
err = "estimator must be None when specifying units"
raise ValueError(err)
grouped = sub_data.groupby(orient, sort=self.sort)
# Could pass as_index=False instead of reset_index,
# but that fails on a corner case with older pandas.
sub_data = (
grouped
.apply(agg, other, **groupby_apply_include_groups(False))
.reset_index()
)
else:
sub_data[f"{other}min"] = np.nan
sub_data[f"{other}max"] = np.nan
# Apply inverse axis scaling
for var in "xy":
_, inv = _get_transform_functions(ax, var)
for col in sub_data.filter(regex=f"^{var}"):
sub_data[col] = inv(sub_data[col])
# --- Draw the main line(s)
if "units" in self.variables: # XXX why not add to grouping variables?
lines = []
for _, unit_data in sub_data.groupby("units"):
lines.extend(ax.plot(unit_data["x"], unit_data["y"], **kws))
else:
lines = ax.plot(sub_data["x"], sub_data["y"], **kws)
for line in lines:
if "hue" in sub_vars:
line.set_color(self._hue_map(sub_vars["hue"]))
if "size" in sub_vars:
line.set_linewidth(self._size_map(sub_vars["size"]))
if "style" in sub_vars:
attributes = self._style_map(sub_vars["style"])
if "dashes" in attributes:
line.set_dashes(attributes["dashes"])
if "marker" in attributes:
line.set_marker(attributes["marker"])
line_color = line.get_color()
line_alpha = line.get_alpha()
line_capstyle = line.get_solid_capstyle()
# --- Draw the confidence intervals
if self.estimator is not None and self.errorbar is not None:
# TODO handling of orientation will need to happen here
if self.err_style == "band":
func = {"x": ax.fill_between, "y": ax.fill_betweenx}[orient]
func(
sub_data[orient],
sub_data[f"{other}min"], sub_data[f"{other}max"],
color=line_color, **err_kws
)
elif self.err_style == "bars":
error_param = {
f"{other}err": (
sub_data[other] - sub_data[f"{other}min"],
sub_data[f"{other}max"] - sub_data[other],
)
}
ebars = ax.errorbar(
sub_data["x"], sub_data["y"], **error_param,
linestyle="", color=line_color, alpha=line_alpha,
**err_kws
)
# Set the capstyle properly on the error bars
for obj in ebars.get_children():
if isinstance(obj, mpl.collections.LineCollection):
obj.set_capstyle(line_capstyle)
# Finalize the axes details
self._add_axis_labels(ax)
if self.legend:
legend_artist = partial(mpl.lines.Line2D, xdata=[], ydata=[])
attrs = {"hue": "color", "size": "linewidth", "style": None}
self.add_legend_data(ax, legend_artist, kws, attrs)
handles, _ = ax.get_legend_handles_labels()
if handles:
legend = ax.legend(title=self.legend_title)
adjust_legend_subtitles(legend)
|
Draw the plot onto an axes, passing matplotlib kwargs.
|
plot
|
python
|
mwaskom/seaborn
|
seaborn/relational.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/relational.py
|
BSD-3-Clause
|
def _draw_figure(fig):
"""Force draw of a matplotlib figure, accounting for back-compat."""
# See https://github.com/matplotlib/matplotlib/issues/19197 for context
fig.canvas.draw()
if fig.stale:
try:
fig.draw(fig.canvas.get_renderer())
except AttributeError:
pass
|
Force draw of a matplotlib figure, accounting for back-compat.
|
_draw_figure
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def _default_color(method, hue, color, kws, saturation=1):
"""If needed, get a default color by using the matplotlib property cycle."""
if hue is not None:
# This warning is probably user-friendly, but it's currently triggered
# in a FacetGrid context and I don't want to mess with that logic right now
# if color is not None:
# msg = "`color` is ignored when `hue` is assigned."
# warnings.warn(msg)
return None
kws = kws.copy()
kws.pop("label", None)
if color is not None:
if saturation < 1:
color = desaturate(color, saturation)
return color
elif method.__name__ == "plot":
color = normalize_kwargs(kws, mpl.lines.Line2D).get("color")
scout, = method([], [], scalex=False, scaley=False, color=color)
color = scout.get_color()
scout.remove()
elif method.__name__ == "scatter":
# Matplotlib will raise if the size of x/y don't match s/c,
# and the latter might be in the kws dict
scout_size = max(
np.atleast_1d(kws.get(key, [])).shape[0]
for key in ["s", "c", "fc", "facecolor", "facecolors"]
)
scout_x = scout_y = np.full(scout_size, np.nan)
scout = method(scout_x, scout_y, **kws)
facecolors = scout.get_facecolors()
if not len(facecolors):
# Handle bug in matplotlib <= 3.2 (I think)
# This will limit the ability to use non color= kwargs to specify
# a color in versions of matplotlib with the bug, but trying to
# work out what the user wanted by re-implementing the broken logic
# of inspecting the kwargs is probably too brittle.
single_color = False
else:
single_color = np.unique(facecolors, axis=0).shape[0] == 1
# Allow the user to specify an array of colors through various kwargs
if "c" not in kws and single_color:
color = to_rgb(facecolors[0])
scout.remove()
elif method.__name__ == "bar":
# bar() needs masked, not empty data, to generate a patch
scout, = method([np.nan], [np.nan], **kws)
color = to_rgb(scout.get_facecolor())
scout.remove()
# Axes.bar adds both a patch and a container
method.__self__.containers.pop(-1)
elif method.__name__ == "fill_between":
kws = normalize_kwargs(kws, mpl.collections.PolyCollection)
scout = method([], [], **kws)
facecolor = scout.get_facecolor()
color = to_rgb(facecolor[0])
scout.remove()
if saturation < 1:
color = desaturate(color, saturation)
return color
|
If needed, get a default color by using the matplotlib property cycle.
|
_default_color
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def desaturate(color, prop):
"""Decrease the saturation channel of a color by some percent.
Parameters
----------
color : matplotlib color
hex, rgb-tuple, or html color name
prop : float
saturation channel of color will be multiplied by this value
Returns
-------
new_color : rgb tuple
desaturated color code in RGB tuple representation
"""
# Check inputs
if not 0 <= prop <= 1:
raise ValueError("prop must be between 0 and 1")
# Get rgb tuple rep
rgb = to_rgb(color)
# Short circuit to avoid floating point issues
if prop == 1:
return rgb
# Convert to hls
h, l, s = colorsys.rgb_to_hls(*rgb)
# Desaturate the saturation channel
s *= prop
# Convert back to rgb
new_color = colorsys.hls_to_rgb(h, l, s)
return new_color
|
Decrease the saturation channel of a color by some percent.
Parameters
----------
color : matplotlib color
hex, rgb-tuple, or html color name
prop : float
saturation channel of color will be multiplied by this value
Returns
-------
new_color : rgb tuple
desaturated color code in RGB tuple representation
|
desaturate
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def set_hls_values(color, h=None, l=None, s=None): # noqa
"""Independently manipulate the h, l, or s channels of a color.
Parameters
----------
color : matplotlib color
hex, rgb-tuple, or html color name
h, l, s : floats between 0 and 1, or None
new values for each channel in hls space
Returns
-------
new_color : rgb tuple
new color code in RGB tuple representation
"""
# Get an RGB tuple representation
rgb = to_rgb(color)
vals = list(colorsys.rgb_to_hls(*rgb))
for i, val in enumerate([h, l, s]):
if val is not None:
vals[i] = val
rgb = colorsys.hls_to_rgb(*vals)
return rgb
|
Independently manipulate the h, l, or s channels of a color.
Parameters
----------
color : matplotlib color
hex, rgb-tuple, or html color name
h, l, s : floats between 0 and 1, or None
new values for each channel in hls space
Returns
-------
new_color : rgb tuple
new color code in RGB tuple representation
|
set_hls_values
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def axlabel(xlabel, ylabel, **kwargs):
"""Grab current axis and label it.
DEPRECATED: will be removed in a future version.
"""
msg = "This function is deprecated and will be removed in a future version"
warnings.warn(msg, FutureWarning)
ax = plt.gca()
ax.set_xlabel(xlabel, **kwargs)
ax.set_ylabel(ylabel, **kwargs)
|
Grab current axis and label it.
DEPRECATED: will be removed in a future version.
|
axlabel
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def get_color_cycle():
"""Return the list of colors in the current matplotlib color cycle
Parameters
----------
None
Returns
-------
colors : list
List of matplotlib colors in the current cycle, or dark gray if
the current color cycle is empty.
"""
cycler = mpl.rcParams['axes.prop_cycle']
return cycler.by_key()['color'] if 'color' in cycler.keys else [".15"]
|
Return the list of colors in the current matplotlib color cycle
Parameters
----------
None
Returns
-------
colors : list
List of matplotlib colors in the current cycle, or dark gray if
the current color cycle is empty.
|
get_color_cycle
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def move_legend(obj, loc, **kwargs):
"""
Recreate a plot's legend at a new location.
The name is a slight misnomer. Matplotlib legends do not expose public
control over their position parameters. So this function creates a new legend,
copying over the data from the original object, which is then removed.
Parameters
----------
obj : the object with the plot
This argument can be either a seaborn or matplotlib object:
- :class:`seaborn.FacetGrid` or :class:`seaborn.PairGrid`
- :class:`matplotlib.axes.Axes` or :class:`matplotlib.figure.Figure`
loc : str or int
Location argument, as in :meth:`matplotlib.axes.Axes.legend`.
kwargs
Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.legend`.
Examples
--------
.. include:: ../docstrings/move_legend.rst
"""
# This is a somewhat hackish solution that will hopefully be obviated by
# upstream improvements to matplotlib legends that make them easier to
# modify after creation.
from seaborn.axisgrid import Grid # Avoid circular import
# Locate the legend object and a method to recreate the legend
if isinstance(obj, Grid):
old_legend = obj.legend
legend_func = obj.figure.legend
elif isinstance(obj, mpl.axes.Axes):
old_legend = obj.legend_
legend_func = obj.legend
elif isinstance(obj, mpl.figure.Figure):
if obj.legends:
old_legend = obj.legends[-1]
else:
old_legend = None
legend_func = obj.legend
else:
err = "`obj` must be a seaborn Grid or matplotlib Axes or Figure instance."
raise TypeError(err)
if old_legend is None:
err = f"{obj} has no legend attached."
raise ValueError(err)
# Extract the components of the legend we need to reuse
# Import here to avoid a circular import
from seaborn._compat import get_legend_handles
handles = get_legend_handles(old_legend)
labels = [t.get_text() for t in old_legend.get_texts()]
# Handle the case where the user is trying to override the labels
if (new_labels := kwargs.pop("labels", None)) is not None:
if len(new_labels) != len(labels):
err = "Length of new labels does not match existing legend."
raise ValueError(err)
labels = new_labels
# Extract legend properties that can be passed to the recreation method
# (Vexingly, these don't all round-trip)
legend_kws = inspect.signature(mpl.legend.Legend).parameters
props = {k: v for k, v in old_legend.properties().items() if k in legend_kws}
# Delegate default bbox_to_anchor rules to matplotlib
props.pop("bbox_to_anchor")
# Try to propagate the existing title and font properties; respect new ones too
title = props.pop("title")
if "title" in kwargs:
title.set_text(kwargs.pop("title"))
title_kwargs = {k: v for k, v in kwargs.items() if k.startswith("title_")}
for key, val in title_kwargs.items():
title.set(**{key[6:]: val})
kwargs.pop(key)
# Try to respect the frame visibility
kwargs.setdefault("frameon", old_legend.legendPatch.get_visible())
# Remove the old legend and create the new one
props.update(kwargs)
old_legend.remove()
new_legend = legend_func(handles, labels, loc=loc, **props)
new_legend.set_title(title.get_text(), title.get_fontproperties())
# Let the Grid object continue to track the correct legend object
if isinstance(obj, Grid):
obj._legend = new_legend
|
Recreate a plot's legend at a new location.
The name is a slight misnomer. Matplotlib legends do not expose public
control over their position parameters. So this function creates a new legend,
copying over the data from the original object, which is then removed.
Parameters
----------
obj : the object with the plot
This argument can be either a seaborn or matplotlib object:
- :class:`seaborn.FacetGrid` or :class:`seaborn.PairGrid`
- :class:`matplotlib.axes.Axes` or :class:`matplotlib.figure.Figure`
loc : str or int
Location argument, as in :meth:`matplotlib.axes.Axes.legend`.
kwargs
Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.legend`.
Examples
--------
.. include:: ../docstrings/move_legend.rst
|
move_legend
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def _kde_support(data, bw, gridsize, cut, clip):
"""Establish support for a kernel density estimate."""
support_min = max(data.min() - bw * cut, clip[0])
support_max = min(data.max() + bw * cut, clip[1])
support = np.linspace(support_min, support_max, gridsize)
return support
|
Establish support for a kernel density estimate.
|
_kde_support
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def ci(a, which=95, axis=None):
"""Return a percentile range from an array of values."""
p = 50 - which / 2, 50 + which / 2
return np.nanpercentile(a, p, axis)
|
Return a percentile range from an array of values.
|
ci
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def get_dataset_names():
"""Report available example datasets, useful for reporting issues.
Requires an internet connection.
"""
with urlopen(DATASET_NAMES_URL) as resp:
txt = resp.read()
dataset_names = [name.strip() for name in txt.decode().split("\n")]
return list(filter(None, dataset_names))
|
Report available example datasets, useful for reporting issues.
Requires an internet connection.
|
get_dataset_names
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def get_data_home(data_home=None):
"""Return a path to the cache directory for example datasets.
This directory is used by :func:`load_dataset`.
If the ``data_home`` argument is not provided, it will use a directory
specified by the `SEABORN_DATA` environment variable (if it exists)
or otherwise default to an OS-appropriate user cache location.
"""
if data_home is None:
data_home = os.environ.get("SEABORN_DATA", user_cache_dir("seaborn"))
data_home = os.path.expanduser(data_home)
if not os.path.exists(data_home):
os.makedirs(data_home)
return data_home
|
Return a path to the cache directory for example datasets.
This directory is used by :func:`load_dataset`.
If the ``data_home`` argument is not provided, it will use a directory
specified by the `SEABORN_DATA` environment variable (if it exists)
or otherwise default to an OS-appropriate user cache location.
|
get_data_home
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def load_dataset(name, cache=True, data_home=None, **kws):
"""Load an example dataset from the online repository (requires internet).
This function provides quick access to a small number of example datasets
that are useful for documenting seaborn or generating reproducible examples
for bug reports. It is not necessary for normal usage.
Note that some of the datasets have a small amount of preprocessing applied
to define a proper ordering for categorical variables.
Use :func:`get_dataset_names` to see a list of available datasets.
Parameters
----------
name : str
Name of the dataset (``{name}.csv`` on
https://github.com/mwaskom/seaborn-data).
cache : boolean, optional
If True, try to load from the local cache first, and save to the cache
if a download is required.
data_home : string, optional
The directory in which to cache data; see :func:`get_data_home`.
kws : keys and values, optional
Additional keyword arguments are passed to passed through to
:func:`pandas.read_csv`.
Returns
-------
df : :class:`pandas.DataFrame`
Tabular data, possibly with some preprocessing applied.
"""
# A common beginner mistake is to assume that one's personal data needs
# to be passed through this function to be usable with seaborn.
# Let's provide a more helpful error than you would otherwise get.
if isinstance(name, pd.DataFrame):
err = (
"This function accepts only strings (the name of an example dataset). "
"You passed a pandas DataFrame. If you have your own dataset, "
"it is not necessary to use this function before plotting."
)
raise TypeError(err)
url = f"{DATASET_SOURCE}/{name}.csv"
if cache:
cache_path = os.path.join(get_data_home(data_home), os.path.basename(url))
if not os.path.exists(cache_path):
if name not in get_dataset_names():
raise ValueError(f"'{name}' is not one of the example datasets.")
urlretrieve(url, cache_path)
full_path = cache_path
else:
full_path = url
df = pd.read_csv(full_path, **kws)
if df.iloc[-1].isnull().all():
df = df.iloc[:-1]
# Set some columns as a categorical type with ordered levels
if name == "tips":
df["day"] = pd.Categorical(df["day"], ["Thur", "Fri", "Sat", "Sun"])
df["sex"] = pd.Categorical(df["sex"], ["Male", "Female"])
df["time"] = pd.Categorical(df["time"], ["Lunch", "Dinner"])
df["smoker"] = pd.Categorical(df["smoker"], ["Yes", "No"])
elif name == "flights":
months = df["month"].str[:3]
df["month"] = pd.Categorical(months, months.unique())
elif name == "exercise":
df["time"] = pd.Categorical(df["time"], ["1 min", "15 min", "30 min"])
df["kind"] = pd.Categorical(df["kind"], ["rest", "walking", "running"])
df["diet"] = pd.Categorical(df["diet"], ["no fat", "low fat"])
elif name == "titanic":
df["class"] = pd.Categorical(df["class"], ["First", "Second", "Third"])
df["deck"] = pd.Categorical(df["deck"], list("ABCDEFG"))
elif name == "penguins":
df["sex"] = df["sex"].str.title()
elif name == "diamonds":
df["color"] = pd.Categorical(
df["color"], ["D", "E", "F", "G", "H", "I", "J"],
)
df["clarity"] = pd.Categorical(
df["clarity"], ["IF", "VVS1", "VVS2", "VS1", "VS2", "SI1", "SI2", "I1"],
)
df["cut"] = pd.Categorical(
df["cut"], ["Ideal", "Premium", "Very Good", "Good", "Fair"],
)
elif name == "taxis":
df["pickup"] = pd.to_datetime(df["pickup"])
df["dropoff"] = pd.to_datetime(df["dropoff"])
elif name == "seaice":
df["Date"] = pd.to_datetime(df["Date"])
elif name == "dowjones":
df["Date"] = pd.to_datetime(df["Date"])
return df
|
Load an example dataset from the online repository (requires internet).
This function provides quick access to a small number of example datasets
that are useful for documenting seaborn or generating reproducible examples
for bug reports. It is not necessary for normal usage.
Note that some of the datasets have a small amount of preprocessing applied
to define a proper ordering for categorical variables.
Use :func:`get_dataset_names` to see a list of available datasets.
Parameters
----------
name : str
Name of the dataset (``{name}.csv`` on
https://github.com/mwaskom/seaborn-data).
cache : boolean, optional
If True, try to load from the local cache first, and save to the cache
if a download is required.
data_home : string, optional
The directory in which to cache data; see :func:`get_data_home`.
kws : keys and values, optional
Additional keyword arguments are passed to passed through to
:func:`pandas.read_csv`.
Returns
-------
df : :class:`pandas.DataFrame`
Tabular data, possibly with some preprocessing applied.
|
load_dataset
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def axis_ticklabels_overlap(labels):
"""Return a boolean for whether the list of ticklabels have overlaps.
Parameters
----------
labels : list of matplotlib ticklabels
Returns
-------
overlap : boolean
True if any of the labels overlap.
"""
if not labels:
return False
try:
bboxes = [l.get_window_extent() for l in labels]
overlaps = [b.count_overlaps(bboxes) for b in bboxes]
return max(overlaps) > 1
except RuntimeError:
# Issue on macos backend raises an error in the above code
return False
|
Return a boolean for whether the list of ticklabels have overlaps.
Parameters
----------
labels : list of matplotlib ticklabels
Returns
-------
overlap : boolean
True if any of the labels overlap.
|
axis_ticklabels_overlap
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def locator_to_legend_entries(locator, limits, dtype):
"""Return levels and formatted levels for brief numeric legends."""
raw_levels = locator.tick_values(*limits).astype(dtype)
# The locator can return ticks outside the limits, clip them here
raw_levels = [l for l in raw_levels if l >= limits[0] and l <= limits[1]]
class dummy_axis:
def get_view_interval(self):
return limits
if isinstance(locator, mpl.ticker.LogLocator):
formatter = mpl.ticker.LogFormatter()
else:
formatter = mpl.ticker.ScalarFormatter()
# Avoid having an offset/scientific notation which we don't currently
# have any way of representing in the legend
formatter.set_useOffset(False)
formatter.set_scientific(False)
formatter.axis = dummy_axis()
formatted_levels = formatter.format_ticks(raw_levels)
return raw_levels, formatted_levels
|
Return levels and formatted levels for brief numeric legends.
|
locator_to_legend_entries
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def relative_luminance(color):
"""Calculate the relative luminance of a color according to W3C standards
Parameters
----------
color : matplotlib color or sequence of matplotlib colors
Hex code, rgb-tuple, or html color name.
Returns
-------
luminance : float(s) between 0 and 1
"""
rgb = mpl.colors.colorConverter.to_rgba_array(color)[:, :3]
rgb = np.where(rgb <= .03928, rgb / 12.92, ((rgb + .055) / 1.055) ** 2.4)
lum = rgb.dot([.2126, .7152, .0722])
try:
return lum.item()
except ValueError:
return lum
|
Calculate the relative luminance of a color according to W3C standards
Parameters
----------
color : matplotlib color or sequence of matplotlib colors
Hex code, rgb-tuple, or html color name.
Returns
-------
luminance : float(s) between 0 and 1
|
relative_luminance
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def to_utf8(obj):
"""Return a string representing a Python object.
Strings (i.e. type ``str``) are returned unchanged.
Byte strings (i.e. type ``bytes``) are returned as UTF-8-decoded strings.
For other objects, the method ``__str__()`` is called, and the result is
returned as a string.
Parameters
----------
obj : object
Any Python object
Returns
-------
s : str
UTF-8-decoded string representation of ``obj``
"""
if isinstance(obj, str):
return obj
try:
return obj.decode(encoding="utf-8")
except AttributeError: # obj is not bytes-like
return str(obj)
|
Return a string representing a Python object.
Strings (i.e. type ``str``) are returned unchanged.
Byte strings (i.e. type ``bytes``) are returned as UTF-8-decoded strings.
For other objects, the method ``__str__()`` is called, and the result is
returned as a string.
Parameters
----------
obj : object
Any Python object
Returns
-------
s : str
UTF-8-decoded string representation of ``obj``
|
to_utf8
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def _check_argument(param, options, value, prefix=False):
"""Raise if value for param is not in options."""
if prefix and value is not None:
failure = not any(value.startswith(p) for p in options if isinstance(p, str))
else:
failure = value not in options
if failure:
raise ValueError(
f"The value for `{param}` must be one of {options}, "
f"but {repr(value)} was passed."
)
return value
|
Raise if value for param is not in options.
|
_check_argument
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def _assign_default_kwargs(kws, call_func, source_func):
"""Assign default kwargs for call_func using values from source_func."""
# This exists so that axes-level functions and figure-level functions can
# both call a Plotter method while having the default kwargs be defined in
# the signature of the axes-level function.
# An alternative would be to have a decorator on the method that sets its
# defaults based on those defined in the axes-level function.
# Then the figure-level function would not need to worry about defaults.
# I am not sure which is better.
needed = inspect.signature(call_func).parameters
defaults = inspect.signature(source_func).parameters
for param in needed:
if param in defaults and param not in kws:
kws[param] = defaults[param].default
return kws
|
Assign default kwargs for call_func using values from source_func.
|
_assign_default_kwargs
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def adjust_legend_subtitles(legend):
"""
Make invisible-handle "subtitles" entries look more like titles.
Note: This function is not part of the public API and may be changed or removed.
"""
# Legend title not in rcParams until 3.0
font_size = plt.rcParams.get("legend.title_fontsize", None)
hpackers = legend.findobj(mpl.offsetbox.VPacker)[0].get_children()
for hpack in hpackers:
draw_area, text_area = hpack.get_children()
handles = draw_area.get_children()
if not all(artist.get_visible() for artist in handles):
draw_area.set_width(0)
for text in text_area.get_children():
if font_size is not None:
text.set_size(font_size)
|
Make invisible-handle "subtitles" entries look more like titles.
Note: This function is not part of the public API and may be changed or removed.
|
adjust_legend_subtitles
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def _deprecate_ci(errorbar, ci):
"""
Warn on usage of ci= and convert to appropriate errorbar= arg.
ci was deprecated when errorbar was added in 0.12. It should not be removed
completely for some time, but it can be moved out of function definitions
(and extracted from kwargs) after one cycle.
"""
if ci is not deprecated and ci != "deprecated":
if ci is None:
errorbar = None
elif ci == "sd":
errorbar = "sd"
else:
errorbar = ("ci", ci)
msg = (
"\n\nThe `ci` parameter is deprecated. "
f"Use `errorbar={repr(errorbar)}` for the same effect.\n"
)
warnings.warn(msg, FutureWarning, stacklevel=3)
return errorbar
|
Warn on usage of ci= and convert to appropriate errorbar= arg.
ci was deprecated when errorbar was added in 0.12. It should not be removed
completely for some time, but it can be moved out of function definitions
(and extracted from kwargs) after one cycle.
|
_deprecate_ci
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def _get_transform_functions(ax, axis):
"""Return the forward and inverse transforms for a given axis."""
axis_obj = getattr(ax, f"{axis}axis")
transform = axis_obj.get_transform()
return transform.transform, transform.inverted().transform
|
Return the forward and inverse transforms for a given axis.
|
_get_transform_functions
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def _disable_autolayout():
"""Context manager for preventing rc-controlled auto-layout behavior."""
# This is a workaround for an issue in matplotlib, for details see
# https://github.com/mwaskom/seaborn/issues/2914
# The only affect of this rcParam is to set the default value for
# layout= in plt.figure, so we could just do that instead.
# But then we would need to own the complexity of the transition
# from tight_layout=True -> layout="tight". This seems easier,
# but can be removed when (if) that is simpler on the matplotlib side,
# or if the layout algorithms are improved to handle figure legends.
orig_val = mpl.rcParams["figure.autolayout"]
try:
mpl.rcParams["figure.autolayout"] = False
yield
finally:
mpl.rcParams["figure.autolayout"] = orig_val
|
Context manager for preventing rc-controlled auto-layout behavior.
|
_disable_autolayout
|
python
|
mwaskom/seaborn
|
seaborn/utils.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/utils.py
|
BSD-3-Clause
|
def _init_mutable_colormap():
"""Create a matplotlib colormap that will be updated by the widgets."""
greys = color_palette("Greys", 256)
cmap = LinearSegmentedColormap.from_list("interactive", greys)
cmap._init()
cmap._set_extremes()
return cmap
|
Create a matplotlib colormap that will be updated by the widgets.
|
_init_mutable_colormap
|
python
|
mwaskom/seaborn
|
seaborn/widgets.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/widgets.py
|
BSD-3-Clause
|
def choose_colorbrewer_palette(data_type, as_cmap=False):
"""Select a palette from the ColorBrewer set.
These palettes are built into matplotlib and can be used by name in
many seaborn functions, or by passing the object returned by this function.
Parameters
----------
data_type : {'sequential', 'diverging', 'qualitative'}
This describes the kind of data you want to visualize. See the seaborn
color palette docs for more information about how to choose this value.
Note that you can pass substrings (e.g. 'q' for 'qualitative.
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
dark_palette : Create a sequential palette with dark low values.
light_palette : Create a sequential palette with bright low values.
diverging_palette : Create a diverging palette from selected colors.
cubehelix_palette : Create a sequential palette or colormap using the
cubehelix system.
"""
if data_type.startswith("q") and as_cmap:
raise ValueError("Qualitative palettes cannot be colormaps.")
pal = []
if as_cmap:
cmap = _init_mutable_colormap()
if data_type.startswith("s"):
opts = ["Greys", "Reds", "Greens", "Blues", "Oranges", "Purples",
"BuGn", "BuPu", "GnBu", "OrRd", "PuBu", "PuRd", "RdPu", "YlGn",
"PuBuGn", "YlGnBu", "YlOrBr", "YlOrRd"]
variants = ["regular", "reverse", "dark"]
@interact
def choose_sequential(name=opts, n=(2, 18),
desat=FloatSlider(min=0, max=1, value=1),
variant=variants):
if variant == "reverse":
name += "_r"
elif variant == "dark":
name += "_d"
if as_cmap:
colors = color_palette(name, 256, desat)
_update_lut(cmap, np.c_[colors, np.ones(256)])
_show_cmap(cmap)
else:
pal[:] = color_palette(name, n, desat)
palplot(pal)
elif data_type.startswith("d"):
opts = ["RdBu", "RdGy", "PRGn", "PiYG", "BrBG",
"RdYlBu", "RdYlGn", "Spectral"]
variants = ["regular", "reverse"]
@interact
def choose_diverging(name=opts, n=(2, 16),
desat=FloatSlider(min=0, max=1, value=1),
variant=variants):
if variant == "reverse":
name += "_r"
if as_cmap:
colors = color_palette(name, 256, desat)
_update_lut(cmap, np.c_[colors, np.ones(256)])
_show_cmap(cmap)
else:
pal[:] = color_palette(name, n, desat)
palplot(pal)
elif data_type.startswith("q"):
opts = ["Set1", "Set2", "Set3", "Paired", "Accent",
"Pastel1", "Pastel2", "Dark2"]
@interact
def choose_qualitative(name=opts, n=(2, 16),
desat=FloatSlider(min=0, max=1, value=1)):
pal[:] = color_palette(name, n, desat)
palplot(pal)
if as_cmap:
return cmap
return pal
|
Select a palette from the ColorBrewer set.
These palettes are built into matplotlib and can be used by name in
many seaborn functions, or by passing the object returned by this function.
Parameters
----------
data_type : {'sequential', 'diverging', 'qualitative'}
This describes the kind of data you want to visualize. See the seaborn
color palette docs for more information about how to choose this value.
Note that you can pass substrings (e.g. 'q' for 'qualitative.
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
dark_palette : Create a sequential palette with dark low values.
light_palette : Create a sequential palette with bright low values.
diverging_palette : Create a diverging palette from selected colors.
cubehelix_palette : Create a sequential palette or colormap using the
cubehelix system.
|
choose_colorbrewer_palette
|
python
|
mwaskom/seaborn
|
seaborn/widgets.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/widgets.py
|
BSD-3-Clause
|
def choose_dark_palette(input="husl", as_cmap=False):
"""Launch an interactive widget to create a dark sequential palette.
This corresponds with the :func:`dark_palette` function. This kind
of palette is good for data that range between relatively uninteresting
low values and interesting high values.
Requires IPython 2+ and must be used in the notebook.
Parameters
----------
input : {'husl', 'hls', 'rgb'}
Color space for defining the seed value. Note that the default is
different than the default input for :func:`dark_palette`.
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
dark_palette : Create a sequential palette with dark low values.
light_palette : Create a sequential palette with bright low values.
cubehelix_palette : Create a sequential palette or colormap using the
cubehelix system.
"""
pal = []
if as_cmap:
cmap = _init_mutable_colormap()
if input == "rgb":
@interact
def choose_dark_palette_rgb(r=(0., 1.),
g=(0., 1.),
b=(0., 1.),
n=(3, 17)):
color = r, g, b
if as_cmap:
colors = dark_palette(color, 256, input="rgb")
_update_lut(cmap, colors)
_show_cmap(cmap)
else:
pal[:] = dark_palette(color, n, input="rgb")
palplot(pal)
elif input == "hls":
@interact
def choose_dark_palette_hls(h=(0., 1.),
l=(0., 1.), # noqa: E741
s=(0., 1.),
n=(3, 17)):
color = h, l, s
if as_cmap:
colors = dark_palette(color, 256, input="hls")
_update_lut(cmap, colors)
_show_cmap(cmap)
else:
pal[:] = dark_palette(color, n, input="hls")
palplot(pal)
elif input == "husl":
@interact
def choose_dark_palette_husl(h=(0, 359),
s=(0, 99),
l=(0, 99), # noqa: E741
n=(3, 17)):
color = h, s, l
if as_cmap:
colors = dark_palette(color, 256, input="husl")
_update_lut(cmap, colors)
_show_cmap(cmap)
else:
pal[:] = dark_palette(color, n, input="husl")
palplot(pal)
if as_cmap:
return cmap
return pal
|
Launch an interactive widget to create a dark sequential palette.
This corresponds with the :func:`dark_palette` function. This kind
of palette is good for data that range between relatively uninteresting
low values and interesting high values.
Requires IPython 2+ and must be used in the notebook.
Parameters
----------
input : {'husl', 'hls', 'rgb'}
Color space for defining the seed value. Note that the default is
different than the default input for :func:`dark_palette`.
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
dark_palette : Create a sequential palette with dark low values.
light_palette : Create a sequential palette with bright low values.
cubehelix_palette : Create a sequential palette or colormap using the
cubehelix system.
|
choose_dark_palette
|
python
|
mwaskom/seaborn
|
seaborn/widgets.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/widgets.py
|
BSD-3-Clause
|
def choose_light_palette(input="husl", as_cmap=False):
"""Launch an interactive widget to create a light sequential palette.
This corresponds with the :func:`light_palette` function. This kind
of palette is good for data that range between relatively uninteresting
low values and interesting high values.
Requires IPython 2+ and must be used in the notebook.
Parameters
----------
input : {'husl', 'hls', 'rgb'}
Color space for defining the seed value. Note that the default is
different than the default input for :func:`light_palette`.
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
light_palette : Create a sequential palette with bright low values.
dark_palette : Create a sequential palette with dark low values.
cubehelix_palette : Create a sequential palette or colormap using the
cubehelix system.
"""
pal = []
if as_cmap:
cmap = _init_mutable_colormap()
if input == "rgb":
@interact
def choose_light_palette_rgb(r=(0., 1.),
g=(0., 1.),
b=(0., 1.),
n=(3, 17)):
color = r, g, b
if as_cmap:
colors = light_palette(color, 256, input="rgb")
_update_lut(cmap, colors)
_show_cmap(cmap)
else:
pal[:] = light_palette(color, n, input="rgb")
palplot(pal)
elif input == "hls":
@interact
def choose_light_palette_hls(h=(0., 1.),
l=(0., 1.), # noqa: E741
s=(0., 1.),
n=(3, 17)):
color = h, l, s
if as_cmap:
colors = light_palette(color, 256, input="hls")
_update_lut(cmap, colors)
_show_cmap(cmap)
else:
pal[:] = light_palette(color, n, input="hls")
palplot(pal)
elif input == "husl":
@interact
def choose_light_palette_husl(h=(0, 359),
s=(0, 99),
l=(0, 99), # noqa: E741
n=(3, 17)):
color = h, s, l
if as_cmap:
colors = light_palette(color, 256, input="husl")
_update_lut(cmap, colors)
_show_cmap(cmap)
else:
pal[:] = light_palette(color, n, input="husl")
palplot(pal)
if as_cmap:
return cmap
return pal
|
Launch an interactive widget to create a light sequential palette.
This corresponds with the :func:`light_palette` function. This kind
of palette is good for data that range between relatively uninteresting
low values and interesting high values.
Requires IPython 2+ and must be used in the notebook.
Parameters
----------
input : {'husl', 'hls', 'rgb'}
Color space for defining the seed value. Note that the default is
different than the default input for :func:`light_palette`.
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
light_palette : Create a sequential palette with bright low values.
dark_palette : Create a sequential palette with dark low values.
cubehelix_palette : Create a sequential palette or colormap using the
cubehelix system.
|
choose_light_palette
|
python
|
mwaskom/seaborn
|
seaborn/widgets.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/widgets.py
|
BSD-3-Clause
|
def choose_diverging_palette(as_cmap=False):
"""Launch an interactive widget to choose a diverging color palette.
This corresponds with the :func:`diverging_palette` function. This kind
of palette is good for data that range between interesting low values
and interesting high values with a meaningful midpoint. (For example,
change scores relative to some baseline value).
Requires IPython 2+ and must be used in the notebook.
Parameters
----------
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
diverging_palette : Create a diverging color palette or colormap.
choose_colorbrewer_palette : Interactively choose palettes from the
colorbrewer set, including diverging palettes.
"""
pal = []
if as_cmap:
cmap = _init_mutable_colormap()
@interact
def choose_diverging_palette(
h_neg=IntSlider(min=0,
max=359,
value=220),
h_pos=IntSlider(min=0,
max=359,
value=10),
s=IntSlider(min=0, max=99, value=74),
l=IntSlider(min=0, max=99, value=50), # noqa: E741
sep=IntSlider(min=1, max=50, value=10),
n=(2, 16),
center=["light", "dark"]
):
if as_cmap:
colors = diverging_palette(h_neg, h_pos, s, l, sep, 256, center)
_update_lut(cmap, colors)
_show_cmap(cmap)
else:
pal[:] = diverging_palette(h_neg, h_pos, s, l, sep, n, center)
palplot(pal)
if as_cmap:
return cmap
return pal
|
Launch an interactive widget to choose a diverging color palette.
This corresponds with the :func:`diverging_palette` function. This kind
of palette is good for data that range between interesting low values
and interesting high values with a meaningful midpoint. (For example,
change scores relative to some baseline value).
Requires IPython 2+ and must be used in the notebook.
Parameters
----------
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
diverging_palette : Create a diverging color palette or colormap.
choose_colorbrewer_palette : Interactively choose palettes from the
colorbrewer set, including diverging palettes.
|
choose_diverging_palette
|
python
|
mwaskom/seaborn
|
seaborn/widgets.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/widgets.py
|
BSD-3-Clause
|
def choose_cubehelix_palette(as_cmap=False):
"""Launch an interactive widget to create a sequential cubehelix palette.
This corresponds with the :func:`cubehelix_palette` function. This kind
of palette is good for data that range between relatively uninteresting
low values and interesting high values. The cubehelix system allows the
palette to have more hue variance across the range, which can be helpful
for distinguishing a wider range of values.
Requires IPython 2+ and must be used in the notebook.
Parameters
----------
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
cubehelix_palette : Create a sequential palette or colormap using the
cubehelix system.
"""
pal = []
if as_cmap:
cmap = _init_mutable_colormap()
@interact
def choose_cubehelix(n_colors=IntSlider(min=2, max=16, value=9),
start=FloatSlider(min=0, max=3, value=0),
rot=FloatSlider(min=-1, max=1, value=.4),
gamma=FloatSlider(min=0, max=5, value=1),
hue=FloatSlider(min=0, max=1, value=.8),
light=FloatSlider(min=0, max=1, value=.85),
dark=FloatSlider(min=0, max=1, value=.15),
reverse=False):
if as_cmap:
colors = cubehelix_palette(256, start, rot, gamma,
hue, light, dark, reverse)
_update_lut(cmap, np.c_[colors, np.ones(256)])
_show_cmap(cmap)
else:
pal[:] = cubehelix_palette(n_colors, start, rot, gamma,
hue, light, dark, reverse)
palplot(pal)
if as_cmap:
return cmap
return pal
|
Launch an interactive widget to create a sequential cubehelix palette.
This corresponds with the :func:`cubehelix_palette` function. This kind
of palette is good for data that range between relatively uninteresting
low values and interesting high values. The cubehelix system allows the
palette to have more hue variance across the range, which can be helpful
for distinguishing a wider range of values.
Requires IPython 2+ and must be used in the notebook.
Parameters
----------
as_cmap : bool
If True, the return value is a matplotlib colormap rather than a
list of discrete colors.
Returns
-------
pal or cmap : list of colors or matplotlib colormap
Object that can be passed to plotting functions.
See Also
--------
cubehelix_palette : Create a sequential palette or colormap using the
cubehelix system.
|
choose_cubehelix_palette
|
python
|
mwaskom/seaborn
|
seaborn/widgets.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/widgets.py
|
BSD-3-Clause
|
def _check_list_length(self, levels, values, variable):
"""Input check when values are provided as a list."""
# Copied from _core/properties; eventually will be replaced for that.
message = ""
if len(levels) > len(values):
message = " ".join([
f"\nThe {variable} list has fewer values ({len(values)})",
f"than needed ({len(levels)}) and will cycle, which may",
"produce an uninterpretable plot."
])
values = [x for _, x in zip(levels, itertools.cycle(values))]
elif len(values) > len(levels):
message = " ".join([
f"The {variable} list has more values ({len(values)})",
f"than needed ({len(levels)}), which may not be intended.",
])
values = values[:len(levels)]
if message:
warnings.warn(message, UserWarning, stacklevel=6)
return values
|
Input check when values are provided as a list.
|
_check_list_length
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def __call__(self, key, *args, **kwargs):
"""Get the attribute(s) values for the data key."""
if isinstance(key, (list, np.ndarray, pd.Series)):
return [self._lookup_single(k, *args, **kwargs) for k in key]
else:
return self._lookup_single(key, *args, **kwargs)
|
Get the attribute(s) values for the data key.
|
__call__
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def __init__(
self, plotter, palette=None, order=None, norm=None, saturation=1,
):
"""Map the levels of the `hue` variable to distinct colors.
Parameters
----------
# TODO add generic parameters
"""
super().__init__(plotter)
data = plotter.plot_data.get("hue", pd.Series(dtype=float))
if isinstance(palette, np.ndarray):
msg = (
"Numpy array is not a supported type for `palette`. "
"Please convert your palette to a list. "
"This will become an error in v0.14"
)
warnings.warn(msg, stacklevel=4)
palette = palette.tolist()
if data.isna().all():
if palette is not None:
msg = "Ignoring `palette` because no `hue` variable has been assigned."
warnings.warn(msg, stacklevel=4)
else:
map_type = self.infer_map_type(
palette, norm, plotter.input_format, plotter.var_types["hue"]
)
# Our goal is to end up with a dictionary mapping every unique
# value in `data` to a color. We will also keep track of the
# metadata about this mapping we will need for, e.g., a legend
# --- Option 1: numeric mapping with a matplotlib colormap
if map_type == "numeric":
data = pd.to_numeric(data)
levels, lookup_table, norm, cmap = self.numeric_mapping(
data, palette, norm,
)
# --- Option 2: categorical mapping using seaborn palette
elif map_type == "categorical":
cmap = norm = None
levels, lookup_table = self.categorical_mapping(
data, palette, order,
)
# --- Option 3: datetime mapping
else:
# TODO this needs actual implementation
cmap = norm = None
levels, lookup_table = self.categorical_mapping(
# Casting data to list to handle differences in the way
# pandas and numpy represent datetime64 data
list(data), palette, order,
)
self.saturation = saturation
self.map_type = map_type
self.lookup_table = lookup_table
self.palette = palette
self.levels = levels
self.norm = norm
self.cmap = cmap
|
Map the levels of the `hue` variable to distinct colors.
Parameters
----------
# TODO add generic parameters
|
__init__
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def _lookup_single(self, key):
"""Get the color for a single value, using colormap to interpolate."""
try:
# Use a value that's in the original data vector
value = self.lookup_table[key]
except KeyError:
if self.norm is None:
# Currently we only get here in scatterplot with hue_order,
# because scatterplot does not consider hue a grouping variable
# So unused hue levels are in the data, but not the lookup table
return (0, 0, 0, 0)
# Use the colormap to interpolate between existing datapoints
# (e.g. in the context of making a continuous legend)
try:
normed = self.norm(key)
except TypeError as err:
if np.isnan(key):
value = (0, 0, 0, 0)
else:
raise err
else:
if np.ma.is_masked(normed):
normed = np.nan
value = self.cmap(normed)
if self.saturation < 1:
value = desaturate(value, self.saturation)
return value
|
Get the color for a single value, using colormap to interpolate.
|
_lookup_single
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def infer_map_type(self, palette, norm, input_format, var_type):
"""Determine how to implement the mapping."""
if palette in QUAL_PALETTES:
map_type = "categorical"
elif norm is not None:
map_type = "numeric"
elif isinstance(palette, (dict, list)):
map_type = "categorical"
elif input_format == "wide":
map_type = "categorical"
else:
map_type = var_type
return map_type
|
Determine how to implement the mapping.
|
infer_map_type
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def categorical_mapping(self, data, palette, order):
"""Determine colors when the hue mapping is categorical."""
# -- Identify the order and name of the levels
levels = categorical_order(data, order)
n_colors = len(levels)
# -- Identify the set of colors to use
if isinstance(palette, dict):
missing = set(levels) - set(palette)
if any(missing):
err = "The palette dictionary is missing keys: {}"
raise ValueError(err.format(missing))
lookup_table = palette
else:
if palette is None:
if n_colors <= len(get_color_cycle()):
colors = color_palette(None, n_colors)
else:
colors = color_palette("husl", n_colors)
elif isinstance(palette, list):
colors = self._check_list_length(levels, palette, "palette")
else:
colors = color_palette(palette, n_colors)
lookup_table = dict(zip(levels, colors))
return levels, lookup_table
|
Determine colors when the hue mapping is categorical.
|
categorical_mapping
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def numeric_mapping(self, data, palette, norm):
"""Determine colors when the hue variable is quantitative."""
if isinstance(palette, dict):
# The presence of a norm object overrides a dictionary of hues
# in specifying a numeric mapping, so we need to process it here.
levels = list(sorted(palette))
colors = [palette[k] for k in sorted(palette)]
cmap = mpl.colors.ListedColormap(colors)
lookup_table = palette.copy()
else:
# The levels are the sorted unique values in the data
levels = list(np.sort(remove_na(data.unique())))
# --- Sort out the colormap to use from the palette argument
# Default numeric palette is our default cubehelix palette
# TODO do we want to do something complicated to ensure contrast?
palette = "ch:" if palette is None else palette
if isinstance(palette, mpl.colors.Colormap):
cmap = palette
else:
cmap = color_palette(palette, as_cmap=True)
# Now sort out the data normalization
if norm is None:
norm = mpl.colors.Normalize()
elif isinstance(norm, tuple):
norm = mpl.colors.Normalize(*norm)
elif not isinstance(norm, mpl.colors.Normalize):
err = "``hue_norm`` must be None, tuple, or Normalize object."
raise ValueError(err)
if not norm.scaled():
norm(np.asarray(data.dropna()))
lookup_table = dict(zip(levels, cmap(norm(levels))))
return levels, lookup_table, norm, cmap
|
Determine colors when the hue variable is quantitative.
|
numeric_mapping
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def __init__(
self, plotter, sizes=None, order=None, norm=None,
):
"""Map the levels of the `size` variable to distinct values.
Parameters
----------
# TODO add generic parameters
"""
super().__init__(plotter)
data = plotter.plot_data.get("size", pd.Series(dtype=float))
if data.notna().any():
map_type = self.infer_map_type(
norm, sizes, plotter.var_types["size"]
)
# --- Option 1: numeric mapping
if map_type == "numeric":
levels, lookup_table, norm, size_range = self.numeric_mapping(
data, sizes, norm,
)
# --- Option 2: categorical mapping
elif map_type == "categorical":
levels, lookup_table = self.categorical_mapping(
data, sizes, order,
)
size_range = None
# --- Option 3: datetime mapping
# TODO this needs an actual implementation
else:
levels, lookup_table = self.categorical_mapping(
# Casting data to list to handle differences in the way
# pandas and numpy represent datetime64 data
list(data), sizes, order,
)
size_range = None
self.map_type = map_type
self.levels = levels
self.norm = norm
self.sizes = sizes
self.size_range = size_range
self.lookup_table = lookup_table
|
Map the levels of the `size` variable to distinct values.
Parameters
----------
# TODO add generic parameters
|
__init__
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def __init__(self, plotter, markers=None, dashes=None, order=None):
"""Map the levels of the `style` variable to distinct values.
Parameters
----------
# TODO add generic parameters
"""
super().__init__(plotter)
data = plotter.plot_data.get("style", pd.Series(dtype=float))
if data.notna().any():
# Cast to list to handle numpy/pandas datetime quirks
if variable_type(data) == "datetime":
data = list(data)
# Find ordered unique values
levels = categorical_order(data, order)
markers = self._map_attributes(
markers, levels, unique_markers(len(levels)), "markers",
)
dashes = self._map_attributes(
dashes, levels, unique_dashes(len(levels)), "dashes",
)
# Build the paths matplotlib will use to draw the markers
paths = {}
filled_markers = []
for k, m in markers.items():
if not isinstance(m, mpl.markers.MarkerStyle):
m = mpl.markers.MarkerStyle(m)
paths[k] = m.get_path().transformed(m.get_transform())
filled_markers.append(m.is_filled())
# Mixture of filled and unfilled markers will show line art markers
# in the edge color, which defaults to white. This can be handled,
# but there would be additional complexity with specifying the
# weight of the line art markers without overwhelming the filled
# ones with the edges. So for now, we will disallow mixtures.
if any(filled_markers) and not all(filled_markers):
err = "Filled and line art markers cannot be mixed"
raise ValueError(err)
lookup_table = {}
for key in levels:
lookup_table[key] = {}
if markers:
lookup_table[key]["marker"] = markers[key]
lookup_table[key]["path"] = paths[key]
if dashes:
lookup_table[key]["dashes"] = dashes[key]
self.levels = levels
self.lookup_table = lookup_table
|
Map the levels of the `style` variable to distinct values.
Parameters
----------
# TODO add generic parameters
|
__init__
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def _lookup_single(self, key, attr=None):
"""Get attribute(s) for a given data point."""
if attr is None:
value = self.lookup_table[key]
else:
value = self.lookup_table[key][attr]
return value
|
Get attribute(s) for a given data point.
|
_lookup_single
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def _map_attributes(self, arg, levels, defaults, attr):
"""Handle the specification for a given style attribute."""
if arg is True:
lookup_table = dict(zip(levels, defaults))
elif isinstance(arg, dict):
missing = set(levels) - set(arg)
if missing:
err = f"These `{attr}` levels are missing values: {missing}"
raise ValueError(err)
lookup_table = arg
elif isinstance(arg, Sequence):
arg = self._check_list_length(levels, arg, attr)
lookup_table = dict(zip(levels, arg))
elif arg:
err = f"This `{attr}` argument was not understood: {arg}"
raise ValueError(err)
else:
lookup_table = {}
return lookup_table
|
Handle the specification for a given style attribute.
|
_map_attributes
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def var_levels(self):
"""Property interface to ordered list of variables levels.
Each time it's accessed, it updates the var_levels dictionary with the
list of levels in the current semantic mappers. But it also allows the
dictionary to persist, so it can be used to set levels by a key. This is
used to track the list of col/row levels using an attached FacetGrid
object, but it's kind of messy and ideally fixed by improving the
faceting logic so it interfaces better with the modern approach to
tracking plot variables.
"""
for var in self.variables:
if (map_obj := getattr(self, f"_{var}_map", None)) is not None:
self._var_levels[var] = map_obj.levels
return self._var_levels
|
Property interface to ordered list of variables levels.
Each time it's accessed, it updates the var_levels dictionary with the
list of levels in the current semantic mappers. But it also allows the
dictionary to persist, so it can be used to set levels by a key. This is
used to track the list of col/row levels using an attached FacetGrid
object, but it's kind of messy and ideally fixed by improving the
faceting logic so it interfaces better with the modern approach to
tracking plot variables.
|
var_levels
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def assign_variables(self, data=None, variables={}):
"""Define plot variables, optionally using lookup from `data`."""
x = variables.get("x", None)
y = variables.get("y", None)
if x is None and y is None:
self.input_format = "wide"
frame, names = self._assign_variables_wideform(data, **variables)
else:
# When dealing with long-form input, use the newer PlotData
# object (internal but introduced for the objects interface)
# to centralize / standardize data consumption logic.
self.input_format = "long"
plot_data = PlotData(data, variables)
frame = plot_data.frame
names = plot_data.names
self.plot_data = frame
self.variables = names
self.var_types = {
v: variable_type(
frame[v],
boolean_type="numeric" if v in "xy" else "categorical"
)
for v in names
}
return self
|
Define plot variables, optionally using lookup from `data`.
|
assign_variables
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def _assign_variables_wideform(self, data=None, **kwargs):
"""Define plot variables given wide-form data.
Parameters
----------
data : flat vector or collection of vectors
Data can be a vector or mapping that is coerceable to a Series
or a sequence- or mapping-based collection of such vectors, or a
rectangular numpy array, or a Pandas DataFrame.
kwargs : variable -> data mappings
Behavior with keyword arguments is currently undefined.
Returns
-------
plot_data : :class:`pandas.DataFrame`
Long-form data object mapping seaborn variables (x, y, hue, ...)
to data vectors.
variables : dict
Keys are defined seaborn variables; values are names inferred from
the inputs (or None when no name can be determined).
"""
# Raise if semantic or other variables are assigned in wide-form mode
assigned = [k for k, v in kwargs.items() if v is not None]
if any(assigned):
s = "s" if len(assigned) > 1 else ""
err = f"The following variable{s} cannot be assigned with wide-form data: "
err += ", ".join(f"`{v}`" for v in assigned)
raise ValueError(err)
# Determine if the data object actually has any data in it
empty = data is None or not len(data)
# Then, determine if we have "flat" data (a single vector)
if isinstance(data, dict):
values = data.values()
else:
values = np.atleast_1d(np.asarray(data, dtype=object))
flat = not any(
isinstance(v, Iterable) and not isinstance(v, (str, bytes))
for v in values
)
if empty:
# Make an object with the structure of plot_data, but empty
plot_data = pd.DataFrame()
variables = {}
elif flat:
# Handle flat data by converting to pandas Series and using the
# index and/or values to define x and/or y
# (Could be accomplished with a more general to_series() interface)
flat_data = pd.Series(data).copy()
names = {
"@values": flat_data.name,
"@index": flat_data.index.name
}
plot_data = {}
variables = {}
for var in ["x", "y"]:
if var in self.flat_structure:
attr = self.flat_structure[var]
plot_data[var] = getattr(flat_data, attr[1:])
variables[var] = names[self.flat_structure[var]]
plot_data = pd.DataFrame(plot_data)
else:
# Otherwise assume we have some collection of vectors.
# Handle Python sequences such that entries end up in the columns,
# not in the rows, of the intermediate wide DataFrame.
# One way to accomplish this is to convert to a dict of Series.
if isinstance(data, Sequence):
data_dict = {}
for i, var in enumerate(data):
key = getattr(var, "name", i)
# TODO is there a safer/more generic way to ensure Series?
# sort of like np.asarray, but for pandas?
data_dict[key] = pd.Series(var)
data = data_dict
# Pandas requires that dict values either be Series objects
# or all have the same length, but we want to allow "ragged" inputs
if isinstance(data, Mapping):
data = {key: pd.Series(val) for key, val in data.items()}
# Otherwise, delegate to the pandas DataFrame constructor
# This is where we'd prefer to use a general interface that says
# "give me this data as a pandas DataFrame", so we can accept
# DataFrame objects from other libraries
wide_data = pd.DataFrame(data, copy=True)
# At this point we should reduce the dataframe to numeric cols
numeric_cols = [
k for k, v in wide_data.items() if variable_type(v) == "numeric"
]
wide_data = wide_data[numeric_cols]
# Now melt the data to long form
melt_kws = {"var_name": "@columns", "value_name": "@values"}
use_index = "@index" in self.wide_structure.values()
if use_index:
melt_kws["id_vars"] = "@index"
try:
orig_categories = wide_data.columns.categories
orig_ordered = wide_data.columns.ordered
wide_data.columns = wide_data.columns.add_categories("@index")
except AttributeError:
category_columns = False
else:
category_columns = True
wide_data["@index"] = wide_data.index.to_series()
plot_data = wide_data.melt(**melt_kws)
if use_index and category_columns:
plot_data["@columns"] = pd.Categorical(plot_data["@columns"],
orig_categories,
orig_ordered)
# Assign names corresponding to plot semantics
for var, attr in self.wide_structure.items():
plot_data[var] = plot_data[attr]
# Define the variable names
variables = {}
for var, attr in self.wide_structure.items():
obj = getattr(wide_data, attr[1:])
variables[var] = getattr(obj, "name", None)
# Remove redundant columns from plot_data
plot_data = plot_data[list(variables)]
return plot_data, variables
|
Define plot variables given wide-form data.
Parameters
----------
data : flat vector or collection of vectors
Data can be a vector or mapping that is coerceable to a Series
or a sequence- or mapping-based collection of such vectors, or a
rectangular numpy array, or a Pandas DataFrame.
kwargs : variable -> data mappings
Behavior with keyword arguments is currently undefined.
Returns
-------
plot_data : :class:`pandas.DataFrame`
Long-form data object mapping seaborn variables (x, y, hue, ...)
to data vectors.
variables : dict
Keys are defined seaborn variables; values are names inferred from
the inputs (or None when no name can be determined).
|
_assign_variables_wideform
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def iter_data(
self, grouping_vars=None, *,
reverse=False, from_comp_data=False,
by_facet=True, allow_empty=False, dropna=True,
):
"""Generator for getting subsets of data defined by semantic variables.
Also injects "col" and "row" into grouping semantics.
Parameters
----------
grouping_vars : string or list of strings
Semantic variables that define the subsets of data.
reverse : bool
If True, reverse the order of iteration.
from_comp_data : bool
If True, use self.comp_data rather than self.plot_data
by_facet : bool
If True, add faceting variables to the set of grouping variables.
allow_empty : bool
If True, yield an empty dataframe when no observations exist for
combinations of grouping variables.
dropna : bool
If True, remove rows with missing data.
Yields
------
sub_vars : dict
Keys are semantic names, values are the level of that semantic.
sub_data : :class:`pandas.DataFrame`
Subset of ``plot_data`` for this combination of semantic values.
"""
# TODO should this default to using all (non x/y?) semantics?
# or define grouping vars somewhere?
if grouping_vars is None:
grouping_vars = []
elif isinstance(grouping_vars, str):
grouping_vars = [grouping_vars]
elif isinstance(grouping_vars, tuple):
grouping_vars = list(grouping_vars)
# Always insert faceting variables
if by_facet:
facet_vars = {"col", "row"}
grouping_vars.extend(
facet_vars & set(self.variables) - set(grouping_vars)
)
# Reduce to the semantics used in this plot
grouping_vars = [var for var in grouping_vars if var in self.variables]
if from_comp_data:
data = self.comp_data
else:
data = self.plot_data
if dropna:
data = data.dropna()
levels = self.var_levels.copy()
if from_comp_data:
for axis in {"x", "y"} & set(grouping_vars):
converter = self.converters[axis].iloc[0]
if self.var_types[axis] == "categorical":
if self._var_ordered[axis]:
# If the axis is ordered, then the axes in a possible
# facet grid are by definition "shared", or there is a
# single axis with a unique cat -> idx mapping.
# So we can just take the first converter object.
levels[axis] = converter.convert_units(levels[axis])
else:
# Otherwise, the mappings may not be unique, but we can
# use the unique set of index values in comp_data.
levels[axis] = np.sort(data[axis].unique())
else:
transform = converter.get_transform().transform
levels[axis] = transform(converter.convert_units(levels[axis]))
if grouping_vars:
grouped_data = data.groupby(
grouping_vars, sort=False, as_index=False, observed=False,
)
grouping_keys = []
for var in grouping_vars:
key = levels.get(var)
grouping_keys.append([] if key is None else key)
iter_keys = itertools.product(*grouping_keys)
if reverse:
iter_keys = reversed(list(iter_keys))
for key in iter_keys:
pd_key = (
key[0] if len(key) == 1 and _version_predates(pd, "2.2.0") else key
)
try:
data_subset = grouped_data.get_group(pd_key)
except KeyError:
# XXX we are adding this to allow backwards compatibility
# with the empty artists that old categorical plots would
# add (before 0.12), which we may decide to break, in which
# case this option could be removed
data_subset = data.loc[[]]
if data_subset.empty and not allow_empty:
continue
sub_vars = dict(zip(grouping_vars, key))
yield sub_vars, data_subset.copy()
else:
yield {}, data.copy()
|
Generator for getting subsets of data defined by semantic variables.
Also injects "col" and "row" into grouping semantics.
Parameters
----------
grouping_vars : string or list of strings
Semantic variables that define the subsets of data.
reverse : bool
If True, reverse the order of iteration.
from_comp_data : bool
If True, use self.comp_data rather than self.plot_data
by_facet : bool
If True, add faceting variables to the set of grouping variables.
allow_empty : bool
If True, yield an empty dataframe when no observations exist for
combinations of grouping variables.
dropna : bool
If True, remove rows with missing data.
Yields
------
sub_vars : dict
Keys are semantic names, values are the level of that semantic.
sub_data : :class:`pandas.DataFrame`
Subset of ``plot_data`` for this combination of semantic values.
|
iter_data
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def comp_data(self):
"""Dataframe with numeric x and y, after unit conversion and log scaling."""
if not hasattr(self, "ax"):
# Probably a good idea, but will need a bunch of tests updated
# Most of these tests should just use the external interface
# Then this can be re-enabled.
# raise AttributeError("No Axes attached to plotter")
return self.plot_data
if not hasattr(self, "_comp_data"):
comp_data = (
self.plot_data
.copy(deep=False)
.drop(["x", "y"], axis=1, errors="ignore")
)
for var in "yx":
if var not in self.variables:
continue
parts = []
grouped = self.plot_data[var].groupby(self.converters[var], sort=False)
for converter, orig in grouped:
orig = orig.mask(orig.isin([np.inf, -np.inf]), np.nan)
orig = orig.dropna()
if var in self.var_levels:
# TODO this should happen in some centralized location
# it is similar to GH2419, but more complicated because
# supporting `order` in categorical plots is tricky
orig = orig[orig.isin(self.var_levels[var])]
comp = pd.to_numeric(converter.convert_units(orig)).astype(float)
transform = converter.get_transform().transform
parts.append(pd.Series(transform(comp), orig.index, name=orig.name))
if parts:
comp_col = pd.concat(parts)
else:
comp_col = pd.Series(dtype=float, name=var)
comp_data.insert(0, var, comp_col)
self._comp_data = comp_data
return self._comp_data
|
Dataframe with numeric x and y, after unit conversion and log scaling.
|
comp_data
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def _get_axes(self, sub_vars):
"""Return an Axes object based on existence of row/col variables."""
row = sub_vars.get("row", None)
col = sub_vars.get("col", None)
if row is not None and col is not None:
return self.facets.axes_dict[(row, col)]
elif row is not None:
return self.facets.axes_dict[row]
elif col is not None:
return self.facets.axes_dict[col]
elif self.ax is None:
return self.facets.ax
else:
return self.ax
|
Return an Axes object based on existence of row/col variables.
|
_get_axes
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def _attach(
self,
obj,
allowed_types=None,
log_scale=None,
):
"""Associate the plotter with an Axes manager and initialize its units.
Parameters
----------
obj : :class:`matplotlib.axes.Axes` or :class:'FacetGrid`
Structural object that we will eventually plot onto.
allowed_types : str or list of str
If provided, raise when either the x or y variable does not have
one of the declared seaborn types.
log_scale : bool, number, or pair of bools or numbers
If not False, set the axes to use log scaling, with the given
base or defaulting to 10. If a tuple, interpreted as separate
arguments for the x and y axes.
"""
from .axisgrid import FacetGrid
if isinstance(obj, FacetGrid):
self.ax = None
self.facets = obj
ax_list = obj.axes.flatten()
if obj.col_names is not None:
self.var_levels["col"] = obj.col_names
if obj.row_names is not None:
self.var_levels["row"] = obj.row_names
else:
self.ax = obj
self.facets = None
ax_list = [obj]
# Identify which "axis" variables we have defined
axis_variables = set("xy").intersection(self.variables)
# -- Verify the types of our x and y variables here.
# This doesn't really make complete sense being here here, but it's a fine
# place for it, given the current system.
# (Note that for some plots, there might be more complicated restrictions)
# e.g. the categorical plots have their own check that as specific to the
# non-categorical axis.
if allowed_types is None:
allowed_types = ["numeric", "datetime", "categorical"]
elif isinstance(allowed_types, str):
allowed_types = [allowed_types]
for var in axis_variables:
var_type = self.var_types[var]
if var_type not in allowed_types:
err = (
f"The {var} variable is {var_type}, but one of "
f"{allowed_types} is required"
)
raise TypeError(err)
# -- Get axis objects for each row in plot_data for type conversions and scaling
facet_dim = {"x": "col", "y": "row"}
self.converters = {}
for var in axis_variables:
other_var = {"x": "y", "y": "x"}[var]
converter = pd.Series(index=self.plot_data.index, name=var, dtype=object)
share_state = getattr(self.facets, f"_share{var}", True)
# Simplest cases are that we have a single axes, all axes are shared,
# or sharing is only on the orthogonal facet dimension. In these cases,
# all datapoints get converted the same way, so use the first axis
if share_state is True or share_state == facet_dim[other_var]:
converter.loc[:] = getattr(ax_list[0], f"{var}axis")
else:
# Next simplest case is when no axes are shared, and we can
# use the axis objects within each facet
if share_state is False:
for axes_vars, axes_data in self.iter_data():
ax = self._get_axes(axes_vars)
converter.loc[axes_data.index] = getattr(ax, f"{var}axis")
# In the more complicated case, the axes are shared within each
# "file" of the facetgrid. In that case, we need to subset the data
# for that file and assign it the first axis in the slice of the grid
else:
names = getattr(self.facets, f"{share_state}_names")
for i, level in enumerate(names):
idx = (i, 0) if share_state == "row" else (0, i)
axis = getattr(self.facets.axes[idx], f"{var}axis")
converter.loc[self.plot_data[share_state] == level] = axis
# Store the converter vector, which we use elsewhere (e.g comp_data)
self.converters[var] = converter
# Now actually update the matplotlib objects to do the conversion we want
grouped = self.plot_data[var].groupby(self.converters[var], sort=False)
for converter, seed_data in grouped:
if self.var_types[var] == "categorical":
if self._var_ordered[var]:
order = self.var_levels[var]
else:
order = None
seed_data = categorical_order(seed_data, order)
converter.update_units(seed_data)
# -- Set numerical axis scales
# First unpack the log_scale argument
if log_scale is None:
scalex = scaley = False
else:
# Allow single value or x, y tuple
try:
scalex, scaley = log_scale
except TypeError:
scalex = log_scale if self.var_types.get("x") == "numeric" else False
scaley = log_scale if self.var_types.get("y") == "numeric" else False
# Now use it
for axis, scale in zip("xy", (scalex, scaley)):
if scale:
for ax in ax_list:
set_scale = getattr(ax, f"set_{axis}scale")
if scale is True:
set_scale("log", nonpositive="mask")
else:
set_scale("log", base=scale, nonpositive="mask")
# For categorical y, we want the "first" level to be at the top of the axis
if self.var_types.get("y", None) == "categorical":
for ax in ax_list:
ax.yaxis.set_inverted(True)
# TODO -- Add axes labels
|
Associate the plotter with an Axes manager and initialize its units.
Parameters
----------
obj : :class:`matplotlib.axes.Axes` or :class:'FacetGrid`
Structural object that we will eventually plot onto.
allowed_types : str or list of str
If provided, raise when either the x or y variable does not have
one of the declared seaborn types.
log_scale : bool, number, or pair of bools or numbers
If not False, set the axes to use log scaling, with the given
base or defaulting to 10. If a tuple, interpreted as separate
arguments for the x and y axes.
|
_attach
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def _get_scale_transforms(self, axis):
"""Return a function implementing the scale transform (or its inverse)."""
if self.ax is None:
axis_list = [getattr(ax, f"{axis}axis") for ax in self.facets.axes.flat]
scales = {axis.get_scale() for axis in axis_list}
if len(scales) > 1:
# It is a simplifying assumption that faceted axes will always have
# the same scale (even if they are unshared and have distinct limits).
# Nothing in the seaborn API allows you to create a FacetGrid with
# a mixture of scales, although it's possible via matplotlib.
# This is constraining, but no more so than previous behavior that
# only (properly) handled log scales, and there are some places where
# it would be much too complicated to use axes-specific transforms.
err = "Cannot determine transform with mixed scales on faceted axes."
raise RuntimeError(err)
transform_obj = axis_list[0].get_transform()
else:
# This case is more straightforward
transform_obj = getattr(self.ax, f"{axis}axis").get_transform()
return transform_obj.transform, transform_obj.inverted().transform
|
Return a function implementing the scale transform (or its inverse).
|
_get_scale_transforms
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def _add_axis_labels(self, ax, default_x="", default_y=""):
"""Add axis labels if not present, set visibility to match ticklabels."""
# TODO ax could default to None and use attached axes if present
# but what to do about the case of facets? Currently using FacetGrid's
# set_axis_labels method, which doesn't add labels to the interior even
# when the axes are not shared. Maybe that makes sense?
if not ax.get_xlabel():
x_visible = any(t.get_visible() for t in ax.get_xticklabels())
ax.set_xlabel(self.variables.get("x", default_x), visible=x_visible)
if not ax.get_ylabel():
y_visible = any(t.get_visible() for t in ax.get_yticklabels())
ax.set_ylabel(self.variables.get("y", default_y), visible=y_visible)
|
Add axis labels if not present, set visibility to match ticklabels.
|
_add_axis_labels
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def add_legend_data(
self, ax, func, common_kws=None, attrs=None, semantic_kws=None,
):
"""Add labeled artists to represent the different plot semantics."""
verbosity = self.legend
if isinstance(verbosity, str) and verbosity not in ["auto", "brief", "full"]:
err = "`legend` must be 'auto', 'brief', 'full', or a boolean."
raise ValueError(err)
elif verbosity is True:
verbosity = "auto"
keys = []
legend_kws = {}
common_kws = {} if common_kws is None else common_kws.copy()
semantic_kws = {} if semantic_kws is None else semantic_kws.copy()
# Assign a legend title if there is only going to be one sub-legend,
# otherwise, subtitles will be inserted into the texts list with an
# invisible handle (which is a hack)
titles = {
title for title in
(self.variables.get(v, None) for v in ["hue", "size", "style"])
if title is not None
}
title = "" if len(titles) != 1 else titles.pop()
title_kws = dict(
visible=False, color="w", s=0, linewidth=0, marker="", dashes=""
)
def update(var_name, val_name, **kws):
key = var_name, val_name
if key in legend_kws:
legend_kws[key].update(**kws)
else:
keys.append(key)
legend_kws[key] = dict(**kws)
if attrs is None:
attrs = {"hue": "color", "size": ["linewidth", "s"], "style": None}
for var, names in attrs.items():
self._update_legend_data(
update, var, verbosity, title, title_kws, names, semantic_kws.get(var),
)
legend_data = {}
legend_order = []
# Don't allow color=None so we can set a neutral color for size/style legends
if common_kws.get("color", False) is None:
common_kws.pop("color")
for key in keys:
_, label = key
kws = legend_kws[key]
level_kws = {}
use_attrs = [
*self._legend_attributes,
*common_kws,
*[attr for var_attrs in semantic_kws.values() for attr in var_attrs],
]
for attr in use_attrs:
if attr in kws:
level_kws[attr] = kws[attr]
artist = func(label=label, **{"color": ".2", **common_kws, **level_kws})
if _version_predates(mpl, "3.5.0"):
if isinstance(artist, mpl.lines.Line2D):
ax.add_line(artist)
elif isinstance(artist, mpl.patches.Patch):
ax.add_patch(artist)
elif isinstance(artist, mpl.collections.Collection):
ax.add_collection(artist)
else:
ax.add_artist(artist)
legend_data[key] = artist
legend_order.append(key)
self.legend_title = title
self.legend_data = legend_data
self.legend_order = legend_order
|
Add labeled artists to represent the different plot semantics.
|
add_legend_data
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def _update_legend_data(
self,
update,
var,
verbosity,
title,
title_kws,
attr_names,
other_props,
):
"""Generate legend tick values and formatted labels."""
brief_ticks = 6
mapper = getattr(self, f"_{var}_map", None)
if mapper is None:
return
brief = mapper.map_type == "numeric" and (
verbosity == "brief"
or (verbosity == "auto" and len(mapper.levels) > brief_ticks)
)
if brief:
if isinstance(mapper.norm, mpl.colors.LogNorm):
locator = mpl.ticker.LogLocator(numticks=brief_ticks)
else:
locator = mpl.ticker.MaxNLocator(nbins=brief_ticks)
limits = min(mapper.levels), max(mapper.levels)
levels, formatted_levels = locator_to_legend_entries(
locator, limits, self.plot_data[var].infer_objects().dtype
)
elif mapper.levels is None:
levels = formatted_levels = []
else:
levels = formatted_levels = mapper.levels
if not title and self.variables.get(var, None) is not None:
update((self.variables[var], "title"), self.variables[var], **title_kws)
other_props = {} if other_props is None else other_props
for level, formatted_level in zip(levels, formatted_levels):
if level is not None:
attr = mapper(level)
if isinstance(attr_names, list):
attr = {name: attr for name in attr_names}
elif attr_names is not None:
attr = {attr_names: attr}
attr.update({k: v[level] for k, v in other_props.items() if level in v})
update(self.variables[var], formatted_level, **attr)
|
Generate legend tick values and formatted labels.
|
_update_legend_data
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def scale_categorical(self, axis, order=None, formatter=None):
"""
Enforce categorical (fixed-scale) rules for the data on given axis.
Parameters
----------
axis : "x" or "y"
Axis of the plot to operate on.
order : list
Order that unique values should appear in.
formatter : callable
Function mapping values to a string representation.
Returns
-------
self
"""
# This method both modifies the internal representation of the data
# (converting it to string) and sets some attributes on self. It might be
# a good idea to have a separate object attached to self that contains the
# information in those attributes (i.e. whether to enforce variable order
# across facets, the order to use) similar to the SemanticMapping objects
# we have for semantic variables. That object could also hold the converter
# objects that get used, if we can decouple those from an existing axis
# (cf. https://github.com/matplotlib/matplotlib/issues/19229).
# There are some interactions with faceting information that would need
# to be thought through, since the converts to use depend on facets.
# If we go that route, these methods could become "borrowed" methods similar
# to what happens with the alternate semantic mapper constructors, although
# that approach is kind of fussy and confusing.
# TODO this method could also set the grid state? Since we like to have no
# grid on the categorical axis by default. Again, a case where we'll need to
# store information until we use it, so best to have a way to collect the
# attributes that this method sets.
# TODO if we are going to set visual properties of the axes with these methods,
# then we could do the steps currently in CategoricalPlotter._adjust_cat_axis
# TODO another, and distinct idea, is to expose a cut= param here
_check_argument("axis", ["x", "y"], axis)
# Categorical plots can be "univariate" in which case they get an anonymous
# category label on the opposite axis.
if axis not in self.variables:
self.variables[axis] = None
self.var_types[axis] = "categorical"
self.plot_data[axis] = ""
# If the "categorical" variable has a numeric type, sort the rows so that
# the default result from categorical_order has those values sorted after
# they have been coerced to strings. The reason for this is so that later
# we can get facet-wise orders that are correct.
# XXX Should this also sort datetimes?
# It feels more consistent, but technically will be a default change
# If so, should also change categorical_order to behave that way
if self.var_types[axis] == "numeric":
self.plot_data = self.plot_data.sort_values(axis, kind="mergesort")
# Now get a reference to the categorical data vector and remove na values
cat_data = self.plot_data[axis].dropna()
# Get the initial categorical order, which we do before string
# conversion to respect the original types of the order list.
# Track whether the order is given explicitly so that we can know
# whether or not to use the order constructed here downstream
self._var_ordered[axis] = order is not None or cat_data.dtype.name == "category"
order = pd.Index(categorical_order(cat_data, order), name=axis)
# Then convert data to strings. This is because in matplotlib,
# "categorical" data really mean "string" data, so doing this artists
# will be drawn on the categorical axis with a fixed scale.
# TODO implement formatter here; check that it returns strings?
if formatter is not None:
cat_data = cat_data.map(formatter)
order = order.map(formatter)
else:
cat_data = cat_data.astype(str)
order = order.astype(str)
# Update the levels list with the type-converted order variable
self.var_levels[axis] = order
# Now ensure that seaborn will use categorical rules internally
self.var_types[axis] = "categorical"
# Put the string-typed categorical vector back into the plot_data structure
self.plot_data[axis] = cat_data
return self
|
Enforce categorical (fixed-scale) rules for the data on given axis.
Parameters
----------
axis : "x" or "y"
Axis of the plot to operate on.
order : list
Order that unique values should appear in.
formatter : callable
Function mapping values to a string representation.
Returns
-------
self
|
scale_categorical
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def variable_type(vector, boolean_type="numeric"):
"""
Determine whether a vector contains numeric, categorical, or datetime data.
This function differs from the pandas typing API in two ways:
- Python sequences or object-typed PyData objects are considered numeric if
all of their entries are numeric.
- String or mixed-type data are considered categorical even if not
explicitly represented as a :class:`pandas.api.types.CategoricalDtype`.
Parameters
----------
vector : :func:`pandas.Series`, :func:`numpy.ndarray`, or Python sequence
Input data to test.
boolean_type : 'numeric' or 'categorical'
Type to use for vectors containing only 0s and 1s (and NAs).
Returns
-------
var_type : 'numeric', 'categorical', or 'datetime'
Name identifying the type of data in the vector.
"""
vector = pd.Series(vector)
# If a categorical dtype is set, infer categorical
if isinstance(vector.dtype, pd.CategoricalDtype):
return VariableType("categorical")
# Special-case all-na data, which is always "numeric"
if pd.isna(vector).all():
return VariableType("numeric")
# At this point, drop nans to simplify further type inference
vector = vector.dropna()
# Special-case binary/boolean data, allow caller to determine
# This triggers a numpy warning when vector has strings/objects
# https://github.com/numpy/numpy/issues/6784
# Because we reduce with .all(), we are agnostic about whether the
# comparison returns a scalar or vector, so we will ignore the warning.
# It triggers a separate DeprecationWarning when the vector has datetimes:
# https://github.com/numpy/numpy/issues/13548
# This is considered a bug by numpy and will likely go away.
with warnings.catch_warnings():
warnings.simplefilter(
action='ignore', category=(FutureWarning, DeprecationWarning)
)
try:
if np.isin(vector, [0, 1]).all():
return VariableType(boolean_type)
except TypeError:
# .isin comparison is not guaranteed to be possible under NumPy
# casting rules, depending on the (unknown) dtype of 'vector'
pass
# Defer to positive pandas tests
if pd.api.types.is_numeric_dtype(vector):
return VariableType("numeric")
if pd.api.types.is_datetime64_dtype(vector):
return VariableType("datetime")
# --- If we get to here, we need to check the entries
# Check for a collection where everything is a number
def all_numeric(x):
for x_i in x:
if not isinstance(x_i, Number):
return False
return True
if all_numeric(vector):
return VariableType("numeric")
# Check for a collection where everything is a datetime
def all_datetime(x):
for x_i in x:
if not isinstance(x_i, (datetime, np.datetime64)):
return False
return True
if all_datetime(vector):
return VariableType("datetime")
# Otherwise, our final fallback is to consider things categorical
return VariableType("categorical")
|
Determine whether a vector contains numeric, categorical, or datetime data.
This function differs from the pandas typing API in two ways:
- Python sequences or object-typed PyData objects are considered numeric if
all of their entries are numeric.
- String or mixed-type data are considered categorical even if not
explicitly represented as a :class:`pandas.api.types.CategoricalDtype`.
Parameters
----------
vector : :func:`pandas.Series`, :func:`numpy.ndarray`, or Python sequence
Input data to test.
boolean_type : 'numeric' or 'categorical'
Type to use for vectors containing only 0s and 1s (and NAs).
Returns
-------
var_type : 'numeric', 'categorical', or 'datetime'
Name identifying the type of data in the vector.
|
variable_type
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def infer_orient(x=None, y=None, orient=None, require_numeric=True):
"""Determine how the plot should be oriented based on the data.
For historical reasons, the convention is to call a plot "horizontally"
or "vertically" oriented based on the axis representing its dependent
variable. Practically, this is used when determining the axis for
numerical aggregation.
Parameters
----------
x, y : Vector data or None
Positional data vectors for the plot.
orient : string or None
Specified orientation. If not None, can be "x" or "y", or otherwise
must start with "v" or "h".
require_numeric : bool
If set, raise when the implied dependent variable is not numeric.
Returns
-------
orient : "x" or "y"
Raises
------
ValueError: When `orient` is an unknown string.
TypeError: When dependent variable is not numeric, with `require_numeric`
"""
x_type = None if x is None else variable_type(x)
y_type = None if y is None else variable_type(y)
nonnumeric_dv_error = "{} orientation requires numeric `{}` variable."
single_var_warning = "{} orientation ignored with only `{}` specified."
if x is None:
if str(orient).startswith("h"):
warnings.warn(single_var_warning.format("Horizontal", "y"))
if require_numeric and y_type != "numeric":
raise TypeError(nonnumeric_dv_error.format("Vertical", "y"))
return "x"
elif y is None:
if str(orient).startswith("v"):
warnings.warn(single_var_warning.format("Vertical", "x"))
if require_numeric and x_type != "numeric":
raise TypeError(nonnumeric_dv_error.format("Horizontal", "x"))
return "y"
elif str(orient).startswith("v") or orient == "x":
if require_numeric and y_type != "numeric":
raise TypeError(nonnumeric_dv_error.format("Vertical", "y"))
return "x"
elif str(orient).startswith("h") or orient == "y":
if require_numeric and x_type != "numeric":
raise TypeError(nonnumeric_dv_error.format("Horizontal", "x"))
return "y"
elif orient is not None:
err = (
"`orient` must start with 'v' or 'h' or be None, "
f"but `{repr(orient)}` was passed."
)
raise ValueError(err)
elif x_type != "categorical" and y_type == "categorical":
return "y"
elif x_type != "numeric" and y_type == "numeric":
return "x"
elif x_type == "numeric" and y_type != "numeric":
return "y"
elif require_numeric and "numeric" not in (x_type, y_type):
err = "Neither the `x` nor `y` variable appears to be numeric."
raise TypeError(err)
else:
return "x"
|
Determine how the plot should be oriented based on the data.
For historical reasons, the convention is to call a plot "horizontally"
or "vertically" oriented based on the axis representing its dependent
variable. Practically, this is used when determining the axis for
numerical aggregation.
Parameters
----------
x, y : Vector data or None
Positional data vectors for the plot.
orient : string or None
Specified orientation. If not None, can be "x" or "y", or otherwise
must start with "v" or "h".
require_numeric : bool
If set, raise when the implied dependent variable is not numeric.
Returns
-------
orient : "x" or "y"
Raises
------
ValueError: When `orient` is an unknown string.
TypeError: When dependent variable is not numeric, with `require_numeric`
|
infer_orient
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def unique_dashes(n):
"""Build an arbitrarily long list of unique dash styles for lines.
Parameters
----------
n : int
Number of unique dash specs to generate.
Returns
-------
dashes : list of strings or tuples
Valid arguments for the ``dashes`` parameter on
:class:`matplotlib.lines.Line2D`. The first spec is a solid
line (``""``), the remainder are sequences of long and short
dashes.
"""
# Start with dash specs that are well distinguishable
dashes = [
"",
(4, 1.5),
(1, 1),
(3, 1.25, 1.5, 1.25),
(5, 1, 1, 1),
]
# Now programmatically build as many as we need
p = 3
while len(dashes) < n:
# Take combinations of long and short dashes
a = itertools.combinations_with_replacement([3, 1.25], p)
b = itertools.combinations_with_replacement([4, 1], p)
# Interleave the combinations, reversing one of the streams
segment_list = itertools.chain(*zip(
list(a)[1:-1][::-1],
list(b)[1:-1]
))
# Now insert the gaps
for segments in segment_list:
gap = min(segments)
spec = tuple(itertools.chain(*((seg, gap) for seg in segments)))
dashes.append(spec)
p += 1
return dashes[:n]
|
Build an arbitrarily long list of unique dash styles for lines.
Parameters
----------
n : int
Number of unique dash specs to generate.
Returns
-------
dashes : list of strings or tuples
Valid arguments for the ``dashes`` parameter on
:class:`matplotlib.lines.Line2D`. The first spec is a solid
line (``""``), the remainder are sequences of long and short
dashes.
|
unique_dashes
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def unique_markers(n):
"""Build an arbitrarily long list of unique marker styles for points.
Parameters
----------
n : int
Number of unique marker specs to generate.
Returns
-------
markers : list of string or tuples
Values for defining :class:`matplotlib.markers.MarkerStyle` objects.
All markers will be filled.
"""
# Start with marker specs that are well distinguishable
markers = [
"o",
"X",
(4, 0, 45),
"P",
(4, 0, 0),
(4, 1, 0),
"^",
(4, 1, 45),
"v",
]
# Now generate more from regular polygons of increasing order
s = 5
while len(markers) < n:
a = 360 / (s + 1) / 2
markers.extend([
(s + 1, 1, a),
(s + 1, 0, a),
(s, 1, 0),
(s, 0, 0),
])
s += 1
# Convert to MarkerStyle object, using only exactly what we need
# markers = [mpl.markers.MarkerStyle(m) for m in markers[:n]]
return markers[:n]
|
Build an arbitrarily long list of unique marker styles for points.
Parameters
----------
n : int
Number of unique marker specs to generate.
Returns
-------
markers : list of string or tuples
Values for defining :class:`matplotlib.markers.MarkerStyle` objects.
All markers will be filled.
|
unique_markers
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def categorical_order(vector, order=None):
"""Return a list of unique data values.
Determine an ordered list of levels in ``values``.
Parameters
----------
vector : list, array, Categorical, or Series
Vector of "categorical" values
order : list-like, optional
Desired order of category levels to override the order determined
from the ``values`` object.
Returns
-------
order : list
Ordered list of category levels not including null values.
"""
if order is None:
if hasattr(vector, "categories"):
order = vector.categories
else:
try:
order = vector.cat.categories
except (TypeError, AttributeError):
order = pd.Series(vector).unique()
if variable_type(vector) == "numeric":
order = np.sort(order)
order = filter(pd.notnull, order)
return list(order)
|
Return a list of unique data values.
Determine an ordered list of levels in ``values``.
Parameters
----------
vector : list, array, Categorical, or Series
Vector of "categorical" values
order : list-like, optional
Desired order of category levels to override the order determined
from the ``values`` object.
Returns
-------
order : list
Ordered list of category levels not including null values.
|
categorical_order
|
python
|
mwaskom/seaborn
|
seaborn/_base.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_base.py
|
BSD-3-Clause
|
def get_colormap(name):
"""Handle changes to matplotlib colormap interface in 3.6."""
try:
return mpl.colormaps[name]
except AttributeError:
return mpl.cm.get_cmap(name)
|
Handle changes to matplotlib colormap interface in 3.6.
|
get_colormap
|
python
|
mwaskom/seaborn
|
seaborn/_compat.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_compat.py
|
BSD-3-Clause
|
def register_colormap(name, cmap):
"""Handle changes to matplotlib colormap interface in 3.6."""
try:
if name not in mpl.colormaps:
mpl.colormaps.register(cmap, name=name)
except AttributeError:
mpl.cm.register_cmap(name, cmap)
|
Handle changes to matplotlib colormap interface in 3.6.
|
register_colormap
|
python
|
mwaskom/seaborn
|
seaborn/_compat.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_compat.py
|
BSD-3-Clause
|
def set_layout_engine(
fig: Figure,
engine: Literal["constrained", "compressed", "tight", "none"],
) -> None:
"""Handle changes to auto layout engine interface in 3.6"""
if hasattr(fig, "set_layout_engine"):
fig.set_layout_engine(engine)
else:
# _version_predates(mpl, 3.6)
if engine == "tight":
fig.set_tight_layout(True) # type: ignore # predates typing
elif engine == "constrained":
fig.set_constrained_layout(True) # type: ignore
elif engine == "none":
fig.set_tight_layout(False) # type: ignore
fig.set_constrained_layout(False) # type: ignore
|
Handle changes to auto layout engine interface in 3.6
|
set_layout_engine
|
python
|
mwaskom/seaborn
|
seaborn/_compat.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_compat.py
|
BSD-3-Clause
|
def get_layout_engine(fig: Figure) -> mpl.layout_engine.LayoutEngine | None:
"""Handle changes to auto layout engine interface in 3.6"""
if hasattr(fig, "get_layout_engine"):
return fig.get_layout_engine()
else:
# _version_predates(mpl, 3.6)
return None
|
Handle changes to auto layout engine interface in 3.6
|
get_layout_engine
|
python
|
mwaskom/seaborn
|
seaborn/_compat.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_compat.py
|
BSD-3-Clause
|
def share_axis(ax0, ax1, which):
"""Handle changes to post-hoc axis sharing."""
if _version_predates(mpl, "3.5"):
group = getattr(ax0, f"get_shared_{which}_axes")()
group.join(ax1, ax0)
else:
getattr(ax1, f"share{which}")(ax0)
|
Handle changes to post-hoc axis sharing.
|
share_axis
|
python
|
mwaskom/seaborn
|
seaborn/_compat.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_compat.py
|
BSD-3-Clause
|
def __init__(self, comp_dict, strip_whitespace=True):
"""Read entries from a dict, optionally stripping outer whitespace."""
if strip_whitespace:
entries = {}
for key, val in comp_dict.items():
m = re.match(self.regexp, val)
if m is None:
entries[key] = val
else:
entries[key] = m.group(1)
else:
entries = comp_dict.copy()
self.entries = entries
|
Read entries from a dict, optionally stripping outer whitespace.
|
__init__
|
python
|
mwaskom/seaborn
|
seaborn/_docstrings.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_docstrings.py
|
BSD-3-Clause
|
def __getattr__(self, attr):
"""Provide dot access to entries for clean raw docstrings."""
if attr in self.entries:
return self.entries[attr]
else:
try:
return self.__getattribute__(attr)
except AttributeError as err:
# If Python is run with -OO, it will strip docstrings and our lookup
# from self.entries will fail. We check for __debug__, which is actually
# set to False by -O (it is True for normal execution).
# But we only want to see an error when building the docs;
# not something users should see, so this slight inconsistency is fine.
if __debug__:
raise err
else:
pass
|
Provide dot access to entries for clean raw docstrings.
|
__getattr__
|
python
|
mwaskom/seaborn
|
seaborn/_docstrings.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_docstrings.py
|
BSD-3-Clause
|
def from_function_params(cls, func):
"""Use the numpydoc parser to extract components from existing func."""
params = NumpyDocString(pydoc.getdoc(func))["Parameters"]
comp_dict = {}
for p in params:
name = p.name
type = p.type
desc = "\n ".join(p.desc)
comp_dict[name] = f"{name} : {type}\n {desc}"
return cls(comp_dict)
|
Use the numpydoc parser to extract components from existing func.
|
from_function_params
|
python
|
mwaskom/seaborn
|
seaborn/_docstrings.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_docstrings.py
|
BSD-3-Clause
|
def _define_support_grid(self, x, bw, cut, clip, gridsize):
"""Create the grid of evaluation points depending for vector x."""
clip_lo = -np.inf if clip[0] is None else clip[0]
clip_hi = +np.inf if clip[1] is None else clip[1]
gridmin = max(x.min() - bw * cut, clip_lo)
gridmax = min(x.max() + bw * cut, clip_hi)
return np.linspace(gridmin, gridmax, gridsize)
|
Create the grid of evaluation points depending for vector x.
|
_define_support_grid
|
python
|
mwaskom/seaborn
|
seaborn/_statistics.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py
|
BSD-3-Clause
|
def define_support(self, x1, x2=None, weights=None, cache=True):
"""Create the evaluation grid for a given data set."""
if x2 is None:
support = self._define_support_univariate(x1, weights)
else:
support = self._define_support_bivariate(x1, x2, weights)
if cache:
self.support = support
return support
|
Create the evaluation grid for a given data set.
|
define_support
|
python
|
mwaskom/seaborn
|
seaborn/_statistics.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py
|
BSD-3-Clause
|
def _fit(self, fit_data, weights=None):
"""Fit the scipy kde while adding bw_adjust logic and version check."""
fit_kws = {"bw_method": self.bw_method}
if weights is not None:
fit_kws["weights"] = weights
kde = gaussian_kde(fit_data, **fit_kws)
kde.set_bandwidth(kde.factor * self.bw_adjust)
return kde
|
Fit the scipy kde while adding bw_adjust logic and version check.
|
_fit
|
python
|
mwaskom/seaborn
|
seaborn/_statistics.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py
|
BSD-3-Clause
|
def _eval_univariate(self, x, weights=None):
"""Fit and evaluate a univariate on univariate data."""
support = self.support
if support is None:
support = self.define_support(x, cache=False)
kde = self._fit(x, weights)
if self.cumulative:
s_0 = support[0]
density = np.array([
kde.integrate_box_1d(s_0, s_i) for s_i in support
])
else:
density = kde(support)
return density, support
|
Fit and evaluate a univariate on univariate data.
|
_eval_univariate
|
python
|
mwaskom/seaborn
|
seaborn/_statistics.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py
|
BSD-3-Clause
|
def _eval_bivariate(self, x1, x2, weights=None):
"""Fit and evaluate a univariate on bivariate data."""
support = self.support
if support is None:
support = self.define_support(x1, x2, cache=False)
kde = self._fit([x1, x2], weights)
if self.cumulative:
grid1, grid2 = support
density = np.zeros((grid1.size, grid2.size))
p0 = grid1.min(), grid2.min()
for i, xi in enumerate(grid1):
for j, xj in enumerate(grid2):
density[i, j] = kde.integrate_box(p0, (xi, xj))
else:
xx1, xx2 = np.meshgrid(*support)
density = kde([xx1.ravel(), xx2.ravel()]).reshape(xx1.shape)
return density, support
|
Fit and evaluate a univariate on bivariate data.
|
_eval_bivariate
|
python
|
mwaskom/seaborn
|
seaborn/_statistics.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py
|
BSD-3-Clause
|
def __call__(self, x1, x2=None, weights=None):
"""Fit and evaluate on univariate or bivariate data."""
if x2 is None:
return self._eval_univariate(x1, weights)
else:
return self._eval_bivariate(x1, x2, weights)
|
Fit and evaluate on univariate or bivariate data.
|
__call__
|
python
|
mwaskom/seaborn
|
seaborn/_statistics.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py
|
BSD-3-Clause
|
def __init__(
self,
stat="count",
bins="auto",
binwidth=None,
binrange=None,
discrete=False,
cumulative=False,
):
"""Initialize the estimator with its parameters.
Parameters
----------
stat : str
Aggregate statistic to compute in each bin.
- `count`: show the number of observations in each bin
- `frequency`: show the number of observations divided by the bin width
- `probability` or `proportion`: normalize such that bar heights sum to 1
- `percent`: normalize such that bar heights sum to 100
- `density`: normalize such that the total area of the histogram equals 1
bins : str, number, vector, or a pair of such values
Generic bin parameter that can be the name of a reference rule,
the number of bins, or the breaks of the bins.
Passed to :func:`numpy.histogram_bin_edges`.
binwidth : number or pair of numbers
Width of each bin, overrides ``bins`` but can be used with
``binrange``.
binrange : pair of numbers or a pair of pairs
Lowest and highest value for bin edges; can be used either
with ``bins`` or ``binwidth``. Defaults to data extremes.
discrete : bool or pair of bools
If True, set ``binwidth`` and ``binrange`` such that bin
edges cover integer values in the dataset.
cumulative : bool
If True, return the cumulative statistic.
"""
stat_choices = [
"count", "frequency", "density", "probability", "proportion", "percent",
]
_check_argument("stat", stat_choices, stat)
self.stat = stat
self.bins = bins
self.binwidth = binwidth
self.binrange = binrange
self.discrete = discrete
self.cumulative = cumulative
self.bin_kws = None
|
Initialize the estimator with its parameters.
Parameters
----------
stat : str
Aggregate statistic to compute in each bin.
- `count`: show the number of observations in each bin
- `frequency`: show the number of observations divided by the bin width
- `probability` or `proportion`: normalize such that bar heights sum to 1
- `percent`: normalize such that bar heights sum to 100
- `density`: normalize such that the total area of the histogram equals 1
bins : str, number, vector, or a pair of such values
Generic bin parameter that can be the name of a reference rule,
the number of bins, or the breaks of the bins.
Passed to :func:`numpy.histogram_bin_edges`.
binwidth : number or pair of numbers
Width of each bin, overrides ``bins`` but can be used with
``binrange``.
binrange : pair of numbers or a pair of pairs
Lowest and highest value for bin edges; can be used either
with ``bins`` or ``binwidth``. Defaults to data extremes.
discrete : bool or pair of bools
If True, set ``binwidth`` and ``binrange`` such that bin
edges cover integer values in the dataset.
cumulative : bool
If True, return the cumulative statistic.
|
__init__
|
python
|
mwaskom/seaborn
|
seaborn/_statistics.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py
|
BSD-3-Clause
|
def _define_bin_edges(self, x, weights, bins, binwidth, binrange, discrete):
"""Inner function that takes bin parameters as arguments."""
if binrange is None:
start, stop = x.min(), x.max()
else:
start, stop = binrange
if discrete:
bin_edges = np.arange(start - .5, stop + 1.5)
elif binwidth is not None:
step = binwidth
bin_edges = np.arange(start, stop + step, step)
# Handle roundoff error (maybe there is a less clumsy way?)
if bin_edges.max() < stop or len(bin_edges) < 2:
bin_edges = np.append(bin_edges, bin_edges.max() + step)
else:
bin_edges = np.histogram_bin_edges(
x, bins, binrange, weights,
)
return bin_edges
|
Inner function that takes bin parameters as arguments.
|
_define_bin_edges
|
python
|
mwaskom/seaborn
|
seaborn/_statistics.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py
|
BSD-3-Clause
|
def define_bin_params(self, x1, x2=None, weights=None, cache=True):
"""Given data, return numpy.histogram parameters to define bins."""
if x2 is None:
bin_edges = self._define_bin_edges(
x1, weights, self.bins, self.binwidth, self.binrange, self.discrete,
)
if isinstance(self.bins, (str, Number)):
n_bins = len(bin_edges) - 1
bin_range = bin_edges.min(), bin_edges.max()
bin_kws = dict(bins=n_bins, range=bin_range)
else:
bin_kws = dict(bins=bin_edges)
else:
bin_edges = []
for i, x in enumerate([x1, x2]):
# Resolve out whether bin parameters are shared
# or specific to each variable
bins = self.bins
if not bins or isinstance(bins, (str, Number)):
pass
elif isinstance(bins[i], str):
bins = bins[i]
elif len(bins) == 2:
bins = bins[i]
binwidth = self.binwidth
if binwidth is None:
pass
elif not isinstance(binwidth, Number):
binwidth = binwidth[i]
binrange = self.binrange
if binrange is None:
pass
elif not isinstance(binrange[0], Number):
binrange = binrange[i]
discrete = self.discrete
if not isinstance(discrete, bool):
discrete = discrete[i]
# Define the bins for this variable
bin_edges.append(self._define_bin_edges(
x, weights, bins, binwidth, binrange, discrete,
))
bin_kws = dict(bins=tuple(bin_edges))
if cache:
self.bin_kws = bin_kws
return bin_kws
|
Given data, return numpy.histogram parameters to define bins.
|
define_bin_params
|
python
|
mwaskom/seaborn
|
seaborn/_statistics.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py
|
BSD-3-Clause
|
def _eval_bivariate(self, x1, x2, weights):
"""Inner function for histogram of two variables."""
bin_kws = self.bin_kws
if bin_kws is None:
bin_kws = self.define_bin_params(x1, x2, cache=False)
density = self.stat == "density"
hist, *bin_edges = np.histogram2d(
x1, x2, **bin_kws, weights=weights, density=density
)
area = np.outer(
np.diff(bin_edges[0]),
np.diff(bin_edges[1]),
)
if self.stat == "probability" or self.stat == "proportion":
hist = hist.astype(float) / hist.sum()
elif self.stat == "percent":
hist = hist.astype(float) / hist.sum() * 100
elif self.stat == "frequency":
hist = hist.astype(float) / area
if self.cumulative:
if self.stat in ["density", "frequency"]:
hist = (hist * area).cumsum(axis=0).cumsum(axis=1)
else:
hist = hist.cumsum(axis=0).cumsum(axis=1)
return hist, bin_edges
|
Inner function for histogram of two variables.
|
_eval_bivariate
|
python
|
mwaskom/seaborn
|
seaborn/_statistics.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py
|
BSD-3-Clause
|
def _eval_univariate(self, x, weights):
"""Inner function for histogram of one variable."""
bin_kws = self.bin_kws
if bin_kws is None:
bin_kws = self.define_bin_params(x, weights=weights, cache=False)
density = self.stat == "density"
hist, bin_edges = np.histogram(
x, **bin_kws, weights=weights, density=density,
)
if self.stat == "probability" or self.stat == "proportion":
hist = hist.astype(float) / hist.sum()
elif self.stat == "percent":
hist = hist.astype(float) / hist.sum() * 100
elif self.stat == "frequency":
hist = hist.astype(float) / np.diff(bin_edges)
if self.cumulative:
if self.stat in ["density", "frequency"]:
hist = (hist * np.diff(bin_edges)).cumsum()
else:
hist = hist.cumsum()
return hist, bin_edges
|
Inner function for histogram of one variable.
|
_eval_univariate
|
python
|
mwaskom/seaborn
|
seaborn/_statistics.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py
|
BSD-3-Clause
|
def __call__(self, x1, x2=None, weights=None):
"""Count the occurrences in each bin, maybe normalize."""
if x2 is None:
return self._eval_univariate(x1, weights)
else:
return self._eval_bivariate(x1, x2, weights)
|
Count the occurrences in each bin, maybe normalize.
|
__call__
|
python
|
mwaskom/seaborn
|
seaborn/_statistics.py
|
https://github.com/mwaskom/seaborn/blob/master/seaborn/_statistics.py
|
BSD-3-Clause
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.