nwo
stringlengths
10
28
sha
stringlengths
40
40
path
stringlengths
11
97
identifier
stringlengths
1
64
parameters
stringlengths
2
2.24k
return_statement
stringlengths
0
2.17k
docstring
stringlengths
0
5.45k
docstring_summary
stringlengths
0
3.83k
func_begin
int64
1
13.4k
func_end
int64
2
13.4k
function
stringlengths
28
56.4k
url
stringlengths
106
209
project
int64
1
48
executed_lines
list
executed_lines_pc
float64
0
153
missing_lines
list
missing_lines_pc
float64
0
100
covered
bool
2 classes
filecoverage
float64
2.53
100
function_lines
int64
2
1.46k
mccabe
int64
1
253
coverage
float64
0
100
docstring_lines
int64
0
112
function_nodoc
stringlengths
9
56.4k
id
int64
0
29.8k
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
FacetGrid._inner_axes
(self)
Return a flat array of the inner axes.
Return a flat array of the inner axes.
1,096
1,111
def _inner_axes(self): """Return a flat array of the inner axes.""" if self._col_wrap is None: return self.axes[:-1, 1:].flat else: axes = [] n_empty = self._nrow * self._ncol - self._n_facets for i, ax in enumerate(self.axes): append = ( i % self._ncol and i < (self._ncol * (self._nrow - 1)) and i < (self._ncol * (self._nrow - 1) - n_empty) ) if append: axes.append(ax) return np.array(axes, object).flat
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1096-L1111
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15 ]
93.75
[ 14 ]
6.25
false
96.911197
16
6
93.75
1
def _inner_axes(self): if self._col_wrap is None: return self.axes[:-1, 1:].flat else: axes = [] n_empty = self._nrow * self._ncol - self._n_facets for i, ax in enumerate(self.axes): append = ( i % self._ncol and i < (self._ncol * (self._nrow - 1)) and i < (self._ncol * (self._nrow - 1) - n_empty) ) if append: axes.append(ax) return np.array(axes, object).flat
18,987
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
FacetGrid._left_axes
(self)
Return a flat array of the left column of axes.
Return a flat array of the left column of axes.
1,114
1,123
def _left_axes(self): """Return a flat array of the left column of axes.""" if self._col_wrap is None: return self.axes[:, 0].flat else: axes = [] for i, ax in enumerate(self.axes): if not i % self._ncol: axes.append(ax) return np.array(axes, object).flat
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1114-L1123
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
96.911197
10
4
100
1
def _left_axes(self): if self._col_wrap is None: return self.axes[:, 0].flat else: axes = [] for i, ax in enumerate(self.axes): if not i % self._ncol: axes.append(ax) return np.array(axes, object).flat
18,988
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
FacetGrid._not_left_axes
(self)
Return a flat array of axes that aren't on the left column.
Return a flat array of axes that aren't on the left column.
1,126
1,135
def _not_left_axes(self): """Return a flat array of axes that aren't on the left column.""" if self._col_wrap is None: return self.axes[:, 1:].flat else: axes = [] for i, ax in enumerate(self.axes): if i % self._ncol: axes.append(ax) return np.array(axes, object).flat
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1126-L1135
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
96.911197
10
4
100
1
def _not_left_axes(self): if self._col_wrap is None: return self.axes[:, 1:].flat else: axes = [] for i, ax in enumerate(self.axes): if i % self._ncol: axes.append(ax) return np.array(axes, object).flat
18,989
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
FacetGrid._bottom_axes
(self)
Return a flat array of the bottom row of axes.
Return a flat array of the bottom row of axes.
1,138
1,152
def _bottom_axes(self): """Return a flat array of the bottom row of axes.""" if self._col_wrap is None: return self.axes[-1, :].flat else: axes = [] n_empty = self._nrow * self._ncol - self._n_facets for i, ax in enumerate(self.axes): append = ( i >= (self._ncol * (self._nrow - 1)) or i >= (self._ncol * (self._nrow - 1) - n_empty) ) if append: axes.append(ax) return np.array(axes, object).flat
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1138-L1152
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
96.911197
15
5
100
1
def _bottom_axes(self): if self._col_wrap is None: return self.axes[-1, :].flat else: axes = [] n_empty = self._nrow * self._ncol - self._n_facets for i, ax in enumerate(self.axes): append = ( i >= (self._ncol * (self._nrow - 1)) or i >= (self._ncol * (self._nrow - 1) - n_empty) ) if append: axes.append(ax) return np.array(axes, object).flat
18,990
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
FacetGrid._not_bottom_axes
(self)
Return a flat array of axes that aren't on the bottom row.
Return a flat array of axes that aren't on the bottom row.
1,155
1,169
def _not_bottom_axes(self): """Return a flat array of axes that aren't on the bottom row.""" if self._col_wrap is None: return self.axes[:-1, :].flat else: axes = [] n_empty = self._nrow * self._ncol - self._n_facets for i, ax in enumerate(self.axes): append = ( i < (self._ncol * (self._nrow - 1)) and i < (self._ncol * (self._nrow - 1) - n_empty) ) if append: axes.append(ax) return np.array(axes, object).flat
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1155-L1169
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
96.911197
15
5
100
1
def _not_bottom_axes(self): if self._col_wrap is None: return self.axes[:-1, :].flat else: axes = [] n_empty = self._nrow * self._ncol - self._n_facets for i, ax in enumerate(self.axes): append = ( i < (self._ncol * (self._nrow - 1)) and i < (self._ncol * (self._nrow - 1) - n_empty) ) if append: axes.append(ax) return np.array(axes, object).flat
18,991
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
PairGrid.__init__
( self, data, *, hue=None, vars=None, x_vars=None, y_vars=None, hue_order=None, palette=None, hue_kws=None, corner=False, diag_sharey=True, height=2.5, aspect=1, layout_pad=.5, despine=True, dropna=False, )
Initialize the plot figure and PairGrid object. Parameters ---------- data : DataFrame Tidy (long-form) dataframe where each column is a variable and each row is an observation. hue : string (variable name) Variable in ``data`` to map plot aspects to different colors. This variable will be excluded from the default x and y variables. vars : list of variable names Variables within ``data`` to use, otherwise use every column with a numeric datatype. {x, y}_vars : lists of variable names Variables within ``data`` to use separately for the rows and columns of the figure; i.e. to make a non-square plot. hue_order : list of strings Order for the levels of the hue variable in the palette palette : dict or seaborn color palette Set of colors for mapping the ``hue`` variable. If a dict, keys should be values in the ``hue`` variable. hue_kws : dictionary of param -> list of values mapping Other keyword arguments to insert into the plotting call to let other plot attributes vary across levels of the hue variable (e.g. the markers in a scatterplot). corner : bool If True, don't add axes to the upper (off-diagonal) triangle of the grid, making this a "corner" plot. height : scalar Height (in inches) of each facet. aspect : scalar Aspect * height gives the width (in inches) of each facet. layout_pad : scalar Padding between axes; passed to ``fig.tight_layout``. despine : boolean Remove the top and right spines from the plots. dropna : boolean Drop missing values from the data before plotting. See Also -------- pairplot : Easily drawing common uses of :class:`PairGrid`. FacetGrid : Subplot grid for plotting conditional relationships. Examples -------- .. include:: ../docstrings/PairGrid.rst
Initialize the plot figure and PairGrid object.
1,186
1,358
def __init__( self, data, *, hue=None, vars=None, x_vars=None, y_vars=None, hue_order=None, palette=None, hue_kws=None, corner=False, diag_sharey=True, height=2.5, aspect=1, layout_pad=.5, despine=True, dropna=False, ): """Initialize the plot figure and PairGrid object. Parameters ---------- data : DataFrame Tidy (long-form) dataframe where each column is a variable and each row is an observation. hue : string (variable name) Variable in ``data`` to map plot aspects to different colors. This variable will be excluded from the default x and y variables. vars : list of variable names Variables within ``data`` to use, otherwise use every column with a numeric datatype. {x, y}_vars : lists of variable names Variables within ``data`` to use separately for the rows and columns of the figure; i.e. to make a non-square plot. hue_order : list of strings Order for the levels of the hue variable in the palette palette : dict or seaborn color palette Set of colors for mapping the ``hue`` variable. If a dict, keys should be values in the ``hue`` variable. hue_kws : dictionary of param -> list of values mapping Other keyword arguments to insert into the plotting call to let other plot attributes vary across levels of the hue variable (e.g. the markers in a scatterplot). corner : bool If True, don't add axes to the upper (off-diagonal) triangle of the grid, making this a "corner" plot. height : scalar Height (in inches) of each facet. aspect : scalar Aspect * height gives the width (in inches) of each facet. layout_pad : scalar Padding between axes; passed to ``fig.tight_layout``. despine : boolean Remove the top and right spines from the plots. dropna : boolean Drop missing values from the data before plotting. See Also -------- pairplot : Easily drawing common uses of :class:`PairGrid`. FacetGrid : Subplot grid for plotting conditional relationships. Examples -------- .. include:: ../docstrings/PairGrid.rst """ super().__init__() # Sort out the variables that define the grid numeric_cols = self._find_numeric_cols(data) if hue in numeric_cols: numeric_cols.remove(hue) if vars is not None: x_vars = list(vars) y_vars = list(vars) if x_vars is None: x_vars = numeric_cols if y_vars is None: y_vars = numeric_cols if np.isscalar(x_vars): x_vars = [x_vars] if np.isscalar(y_vars): y_vars = [y_vars] self.x_vars = x_vars = list(x_vars) self.y_vars = y_vars = list(y_vars) self.square_grid = self.x_vars == self.y_vars if not x_vars: raise ValueError("No variables found for grid columns.") if not y_vars: raise ValueError("No variables found for grid rows.") # Create the figure and the array of subplots figsize = len(x_vars) * height * aspect, len(y_vars) * height with _disable_autolayout(): fig = plt.figure(figsize=figsize) axes = fig.subplots(len(y_vars), len(x_vars), sharex="col", sharey="row", squeeze=False) # Possibly remove upper axes to make a corner grid # Note: setting up the axes is usually the most time-intensive part # of using the PairGrid. We are foregoing the speed improvement that # we would get by just not setting up the hidden axes so that we can # avoid implementing fig.subplots ourselves. But worth thinking about. self._corner = corner if corner: hide_indices = np.triu_indices_from(axes, 1) for i, j in zip(*hide_indices): axes[i, j].remove() axes[i, j] = None self._figure = fig self.axes = axes self.data = data # Save what we are going to do with the diagonal self.diag_sharey = diag_sharey self.diag_vars = None self.diag_axes = None self._dropna = dropna # Label the axes self._add_axis_labels() # Sort out the hue variable self._hue_var = hue if hue is None: self.hue_names = hue_order = ["_nolegend_"] self.hue_vals = pd.Series(["_nolegend_"] * len(data), index=data.index) else: # We need hue_order and hue_names because the former is used to control # the order of drawing and the latter is used to control the order of # the legend. hue_names can become string-typed while hue_order must # retain the type of the input data. This is messy but results from # the fact that PairGrid can implement the hue-mapping logic itself # (and was originally written exclusively that way) but now can delegate # to the axes-level functions, while always handling legend creation. # See GH2307 hue_names = hue_order = categorical_order(data[hue], hue_order) if dropna: # Filter NA from the list of unique hue names hue_names = list(filter(pd.notnull, hue_names)) self.hue_names = hue_names self.hue_vals = data[hue] # Additional dict of kwarg -> list of values for mapping the hue var self.hue_kws = hue_kws if hue_kws is not None else {} self._orig_palette = palette self._hue_order = hue_order self.palette = self._get_palette(data, hue, hue_order, palette) self._legend_data = {} # Make the plot look nice for ax in axes[:-1, :].flat: if ax is None: continue for label in ax.get_xticklabels(): label.set_visible(False) ax.xaxis.offsetText.set_visible(False) ax.xaxis.label.set_visible(False) for ax in axes[:, 1:].flat: if ax is None: continue for label in ax.get_yticklabels(): label.set_visible(False) ax.yaxis.offsetText.set_visible(False) ax.yaxis.label.set_visible(False) self._tight_layout_rect = [.01, .01, .99, .99] self._tight_layout_pad = layout_pad self._despine = despine if despine: utils.despine(fig=fig) self.tight_layout(pad=layout_pad)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1186-L1358
26
[ 0, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 84, 85, 86, 87, 88, 89, 90, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 134, 135, 136, 137, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 156, 157, 158, 159, 160, 161, 162, 164, 165, 166, 167, 168, 169, 170, 171, 172 ]
56.069364
[ 71, 82, 138, 155, 163 ]
2.890173
false
96.911197
173
21
97.109827
48
def __init__( self, data, *, hue=None, vars=None, x_vars=None, y_vars=None, hue_order=None, palette=None, hue_kws=None, corner=False, diag_sharey=True, height=2.5, aspect=1, layout_pad=.5, despine=True, dropna=False, ): super().__init__() # Sort out the variables that define the grid numeric_cols = self._find_numeric_cols(data) if hue in numeric_cols: numeric_cols.remove(hue) if vars is not None: x_vars = list(vars) y_vars = list(vars) if x_vars is None: x_vars = numeric_cols if y_vars is None: y_vars = numeric_cols if np.isscalar(x_vars): x_vars = [x_vars] if np.isscalar(y_vars): y_vars = [y_vars] self.x_vars = x_vars = list(x_vars) self.y_vars = y_vars = list(y_vars) self.square_grid = self.x_vars == self.y_vars if not x_vars: raise ValueError("No variables found for grid columns.") if not y_vars: raise ValueError("No variables found for grid rows.") # Create the figure and the array of subplots figsize = len(x_vars) * height * aspect, len(y_vars) * height with _disable_autolayout(): fig = plt.figure(figsize=figsize) axes = fig.subplots(len(y_vars), len(x_vars), sharex="col", sharey="row", squeeze=False) # Possibly remove upper axes to make a corner grid # Note: setting up the axes is usually the most time-intensive part # of using the PairGrid. We are foregoing the speed improvement that # we would get by just not setting up the hidden axes so that we can # avoid implementing fig.subplots ourselves. But worth thinking about. self._corner = corner if corner: hide_indices = np.triu_indices_from(axes, 1) for i, j in zip(*hide_indices): axes[i, j].remove() axes[i, j] = None self._figure = fig self.axes = axes self.data = data # Save what we are going to do with the diagonal self.diag_sharey = diag_sharey self.diag_vars = None self.diag_axes = None self._dropna = dropna # Label the axes self._add_axis_labels() # Sort out the hue variable self._hue_var = hue if hue is None: self.hue_names = hue_order = ["_nolegend_"] self.hue_vals = pd.Series(["_nolegend_"] * len(data), index=data.index) else: # We need hue_order and hue_names because the former is used to control # the order of drawing and the latter is used to control the order of # the legend. hue_names can become string-typed while hue_order must # retain the type of the input data. This is messy but results from # the fact that PairGrid can implement the hue-mapping logic itself # (and was originally written exclusively that way) but now can delegate # to the axes-level functions, while always handling legend creation. # See GH2307 hue_names = hue_order = categorical_order(data[hue], hue_order) if dropna: # Filter NA from the list of unique hue names hue_names = list(filter(pd.notnull, hue_names)) self.hue_names = hue_names self.hue_vals = data[hue] # Additional dict of kwarg -> list of values for mapping the hue var self.hue_kws = hue_kws if hue_kws is not None else {} self._orig_palette = palette self._hue_order = hue_order self.palette = self._get_palette(data, hue, hue_order, palette) self._legend_data = {} # Make the plot look nice for ax in axes[:-1, :].flat: if ax is None: continue for label in ax.get_xticklabels(): label.set_visible(False) ax.xaxis.offsetText.set_visible(False) ax.xaxis.label.set_visible(False) for ax in axes[:, 1:].flat: if ax is None: continue for label in ax.get_yticklabels(): label.set_visible(False) ax.yaxis.offsetText.set_visible(False) ax.yaxis.label.set_visible(False) self._tight_layout_rect = [.01, .01, .99, .99] self._tight_layout_pad = layout_pad self._despine = despine if despine: utils.despine(fig=fig) self.tight_layout(pad=layout_pad)
18,992
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
PairGrid.map
(self, func, **kwargs)
return self
Plot with the same function in every subplot. Parameters ---------- func : callable plotting function Must take x, y arrays as positional arguments and draw onto the "currently active" matplotlib Axes. Also needs to accept kwargs called ``color`` and ``label``.
Plot with the same function in every subplot.
1,360
1,375
def map(self, func, **kwargs): """Plot with the same function in every subplot. Parameters ---------- func : callable plotting function Must take x, y arrays as positional arguments and draw onto the "currently active" matplotlib Axes. Also needs to accept kwargs called ``color`` and ``label``. """ row_indices, col_indices = np.indices(self.axes.shape) indices = zip(row_indices.flat, col_indices.flat) self._map_bivariate(func, indices, **kwargs) return self
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1360-L1375
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
96.911197
16
1
100
8
def map(self, func, **kwargs): row_indices, col_indices = np.indices(self.axes.shape) indices = zip(row_indices.flat, col_indices.flat) self._map_bivariate(func, indices, **kwargs) return self
18,993
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
PairGrid.map_lower
(self, func, **kwargs)
return self
Plot with a bivariate function on the lower diagonal subplots. Parameters ---------- func : callable plotting function Must take x, y arrays as positional arguments and draw onto the "currently active" matplotlib Axes. Also needs to accept kwargs called ``color`` and ``label``.
Plot with a bivariate function on the lower diagonal subplots.
1,377
1,390
def map_lower(self, func, **kwargs): """Plot with a bivariate function on the lower diagonal subplots. Parameters ---------- func : callable plotting function Must take x, y arrays as positional arguments and draw onto the "currently active" matplotlib Axes. Also needs to accept kwargs called ``color`` and ``label``. """ indices = zip(*np.tril_indices_from(self.axes, -1)) self._map_bivariate(func, indices, **kwargs) return self
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1377-L1390
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
96.911197
14
1
100
8
def map_lower(self, func, **kwargs): indices = zip(*np.tril_indices_from(self.axes, -1)) self._map_bivariate(func, indices, **kwargs) return self
18,994
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
PairGrid.map_upper
(self, func, **kwargs)
return self
Plot with a bivariate function on the upper diagonal subplots. Parameters ---------- func : callable plotting function Must take x, y arrays as positional arguments and draw onto the "currently active" matplotlib Axes. Also needs to accept kwargs called ``color`` and ``label``.
Plot with a bivariate function on the upper diagonal subplots.
1,392
1,405
def map_upper(self, func, **kwargs): """Plot with a bivariate function on the upper diagonal subplots. Parameters ---------- func : callable plotting function Must take x, y arrays as positional arguments and draw onto the "currently active" matplotlib Axes. Also needs to accept kwargs called ``color`` and ``label``. """ indices = zip(*np.triu_indices_from(self.axes, 1)) self._map_bivariate(func, indices, **kwargs) return self
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1392-L1405
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
96.911197
14
1
100
8
def map_upper(self, func, **kwargs): indices = zip(*np.triu_indices_from(self.axes, 1)) self._map_bivariate(func, indices, **kwargs) return self
18,995
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
PairGrid.map_offdiag
(self, func, **kwargs)
return self
Plot with a bivariate function on the off-diagonal subplots. Parameters ---------- func : callable plotting function Must take x, y arrays as positional arguments and draw onto the "currently active" matplotlib Axes. Also needs to accept kwargs called ``color`` and ``label``.
Plot with a bivariate function on the off-diagonal subplots.
1,407
1,429
def map_offdiag(self, func, **kwargs): """Plot with a bivariate function on the off-diagonal subplots. Parameters ---------- func : callable plotting function Must take x, y arrays as positional arguments and draw onto the "currently active" matplotlib Axes. Also needs to accept kwargs called ``color`` and ``label``. """ if self.square_grid: self.map_lower(func, **kwargs) if not self._corner: self.map_upper(func, **kwargs) else: indices = [] for i, (y_var) in enumerate(self.y_vars): for j, (x_var) in enumerate(self.x_vars): if x_var != y_var: indices.append((i, j)) self._map_bivariate(func, indices, **kwargs) return self
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1407-L1429
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
100
[]
0
true
96.911197
23
6
100
8
def map_offdiag(self, func, **kwargs): if self.square_grid: self.map_lower(func, **kwargs) if not self._corner: self.map_upper(func, **kwargs) else: indices = [] for i, (y_var) in enumerate(self.y_vars): for j, (x_var) in enumerate(self.x_vars): if x_var != y_var: indices.append((i, j)) self._map_bivariate(func, indices, **kwargs) return self
18,996
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
PairGrid.map_diag
(self, func, **kwargs)
return self
Plot with a univariate function on each diagonal subplot. Parameters ---------- func : callable plotting function Must take an x array as a positional argument and draw onto the "currently active" matplotlib Axes. Also needs to accept kwargs called ``color`` and ``label``.
Plot with a univariate function on each diagonal subplot.
1,431
1,511
def map_diag(self, func, **kwargs): """Plot with a univariate function on each diagonal subplot. Parameters ---------- func : callable plotting function Must take an x array as a positional argument and draw onto the "currently active" matplotlib Axes. Also needs to accept kwargs called ``color`` and ``label``. """ # Add special diagonal axes for the univariate plot if self.diag_axes is None: diag_vars = [] diag_axes = [] for i, y_var in enumerate(self.y_vars): for j, x_var in enumerate(self.x_vars): if x_var == y_var: # Make the density axes diag_vars.append(x_var) ax = self.axes[i, j] diag_ax = ax.twinx() diag_ax.set_axis_off() diag_axes.append(diag_ax) # Work around matplotlib bug # https://github.com/matplotlib/matplotlib/issues/15188 if not plt.rcParams.get("ytick.left", True): for tick in ax.yaxis.majorTicks: tick.tick1line.set_visible(False) # Remove main y axis from density axes in a corner plot if self._corner: ax.yaxis.set_visible(False) if self._despine: utils.despine(ax=ax, left=True) # TODO add optional density ticks (on the right) # when drawing a corner plot? if self.diag_sharey and diag_axes: for ax in diag_axes[1:]: share_axis(diag_axes[0], ax, "y") self.diag_vars = np.array(diag_vars, np.object_) self.diag_axes = np.array(diag_axes, np.object_) if "hue" not in signature(func).parameters: return self._map_diag_iter_hue(func, **kwargs) # Loop over diagonal variables and axes, making one plot in each for var, ax in zip(self.diag_vars, self.diag_axes): plot_kwargs = kwargs.copy() if str(func.__module__).startswith("seaborn"): plot_kwargs["ax"] = ax else: plt.sca(ax) vector = self.data[var] if self._hue_var is not None: hue = self.data[self._hue_var] else: hue = None if self._dropna: not_na = vector.notna() if hue is not None: not_na &= hue.notna() vector = vector[not_na] if hue is not None: hue = hue[not_na] plot_kwargs.setdefault("hue", hue) plot_kwargs.setdefault("hue_order", self._hue_order) plot_kwargs.setdefault("palette", self._orig_palette) func(x=vector, **plot_kwargs) ax.legend_ = None self._add_axis_labels() return self
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1431-L1511
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 69, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80 ]
96.296296
[ 57, 68, 71 ]
3.703704
false
96.911197
81
19
96.296296
8
def map_diag(self, func, **kwargs): # Add special diagonal axes for the univariate plot if self.diag_axes is None: diag_vars = [] diag_axes = [] for i, y_var in enumerate(self.y_vars): for j, x_var in enumerate(self.x_vars): if x_var == y_var: # Make the density axes diag_vars.append(x_var) ax = self.axes[i, j] diag_ax = ax.twinx() diag_ax.set_axis_off() diag_axes.append(diag_ax) # Work around matplotlib bug # https://github.com/matplotlib/matplotlib/issues/15188 if not plt.rcParams.get("ytick.left", True): for tick in ax.yaxis.majorTicks: tick.tick1line.set_visible(False) # Remove main y axis from density axes in a corner plot if self._corner: ax.yaxis.set_visible(False) if self._despine: utils.despine(ax=ax, left=True) # TODO add optional density ticks (on the right) # when drawing a corner plot? if self.diag_sharey and diag_axes: for ax in diag_axes[1:]: share_axis(diag_axes[0], ax, "y") self.diag_vars = np.array(diag_vars, np.object_) self.diag_axes = np.array(diag_axes, np.object_) if "hue" not in signature(func).parameters: return self._map_diag_iter_hue(func, **kwargs) # Loop over diagonal variables and axes, making one plot in each for var, ax in zip(self.diag_vars, self.diag_axes): plot_kwargs = kwargs.copy() if str(func.__module__).startswith("seaborn"): plot_kwargs["ax"] = ax else: plt.sca(ax) vector = self.data[var] if self._hue_var is not None: hue = self.data[self._hue_var] else: hue = None if self._dropna: not_na = vector.notna() if hue is not None: not_na &= hue.notna() vector = vector[not_na] if hue is not None: hue = hue[not_na] plot_kwargs.setdefault("hue", hue) plot_kwargs.setdefault("hue_order", self._hue_order) plot_kwargs.setdefault("palette", self._orig_palette) func(x=vector, **plot_kwargs) ax.legend_ = None self._add_axis_labels() return self
18,997
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
PairGrid._map_diag_iter_hue
(self, func, **kwargs)
return self
Put marginal plot on each diagonal axes, iterating over hue.
Put marginal plot on each diagonal axes, iterating over hue.
1,513
1,550
def _map_diag_iter_hue(self, func, **kwargs): """Put marginal plot on each diagonal axes, iterating over hue.""" # Plot on each of the diagonal axes fixed_color = kwargs.pop("color", None) for var, ax in zip(self.diag_vars, self.diag_axes): hue_grouped = self.data[var].groupby(self.hue_vals) plot_kwargs = kwargs.copy() if str(func.__module__).startswith("seaborn"): plot_kwargs["ax"] = ax else: plt.sca(ax) for k, label_k in enumerate(self._hue_order): # Attempt to get data for this level, allowing for empty try: data_k = hue_grouped.get_group(label_k) except KeyError: data_k = pd.Series([], dtype=float) if fixed_color is None: color = self.palette[k] else: color = fixed_color if self._dropna: data_k = utils.remove_na(data_k) if str(func.__module__).startswith("seaborn"): func(x=data_k, label=label_k, color=color, **plot_kwargs) else: func(data_k, label=label_k, color=color, **plot_kwargs) self._add_axis_labels() return self
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1513-L1550
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37 ]
92.105263
[ 10, 28, 31 ]
7.894737
false
96.911197
38
8
92.105263
1
def _map_diag_iter_hue(self, func, **kwargs): # Plot on each of the diagonal axes fixed_color = kwargs.pop("color", None) for var, ax in zip(self.diag_vars, self.diag_axes): hue_grouped = self.data[var].groupby(self.hue_vals) plot_kwargs = kwargs.copy() if str(func.__module__).startswith("seaborn"): plot_kwargs["ax"] = ax else: plt.sca(ax) for k, label_k in enumerate(self._hue_order): # Attempt to get data for this level, allowing for empty try: data_k = hue_grouped.get_group(label_k) except KeyError: data_k = pd.Series([], dtype=float) if fixed_color is None: color = self.palette[k] else: color = fixed_color if self._dropna: data_k = utils.remove_na(data_k) if str(func.__module__).startswith("seaborn"): func(x=data_k, label=label_k, color=color, **plot_kwargs) else: func(data_k, label=label_k, color=color, **plot_kwargs) self._add_axis_labels() return self
18,998
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
PairGrid._map_bivariate
(self, func, indices, **kwargs)
Draw a bivariate plot on the indicated axes.
Draw a bivariate plot on the indicated axes.
1,552
1,572
def _map_bivariate(self, func, indices, **kwargs): """Draw a bivariate plot on the indicated axes.""" # This is a hack to handle the fact that new distribution plots don't add # their artists onto the axes. This is probably superior in general, but # we'll need a better way to handle it in the axisgrid functions. from .distributions import histplot, kdeplot if func is histplot or func is kdeplot: self._extract_legend_handles = True kws = kwargs.copy() # Use copy as we insert other kwargs for i, j in indices: x_var = self.x_vars[j] y_var = self.y_vars[i] ax = self.axes[i, j] if ax is None: # i.e. we are in corner mode continue self._plot_bivariate(x_var, y_var, ax, func, **kws) self._add_axis_labels() if "hue" in signature(func).parameters: self.hue_names = list(self._legend_data)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1552-L1572
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
100
[]
0
true
96.911197
21
6
100
1
def _map_bivariate(self, func, indices, **kwargs): # This is a hack to handle the fact that new distribution plots don't add # their artists onto the axes. This is probably superior in general, but # we'll need a better way to handle it in the axisgrid functions. from .distributions import histplot, kdeplot if func is histplot or func is kdeplot: self._extract_legend_handles = True kws = kwargs.copy() # Use copy as we insert other kwargs for i, j in indices: x_var = self.x_vars[j] y_var = self.y_vars[i] ax = self.axes[i, j] if ax is None: # i.e. we are in corner mode continue self._plot_bivariate(x_var, y_var, ax, func, **kws) self._add_axis_labels() if "hue" in signature(func).parameters: self.hue_names = list(self._legend_data)
18,999
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
PairGrid._plot_bivariate
(self, x_var, y_var, ax, func, **kwargs)
Draw a bivariate plot on the specified axes.
Draw a bivariate plot on the specified axes.
1,574
1,611
def _plot_bivariate(self, x_var, y_var, ax, func, **kwargs): """Draw a bivariate plot on the specified axes.""" if "hue" not in signature(func).parameters: self._plot_bivariate_iter_hue(x_var, y_var, ax, func, **kwargs) return kwargs = kwargs.copy() if str(func.__module__).startswith("seaborn"): kwargs["ax"] = ax else: plt.sca(ax) if x_var == y_var: axes_vars = [x_var] else: axes_vars = [x_var, y_var] if self._hue_var is not None and self._hue_var not in axes_vars: axes_vars.append(self._hue_var) data = self.data[axes_vars] if self._dropna: data = data.dropna() x = data[x_var] y = data[y_var] if self._hue_var is None: hue = None else: hue = data.get(self._hue_var) if "hue" not in kwargs: kwargs.update({ "hue": hue, "hue_order": self._hue_order, "palette": self._orig_palette, }) func(x=x, y=y, **kwargs) self._update_legend_data(ax)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1574-L1611
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37 ]
97.368421
[ 10 ]
2.631579
false
96.911197
38
9
97.368421
1
def _plot_bivariate(self, x_var, y_var, ax, func, **kwargs): if "hue" not in signature(func).parameters: self._plot_bivariate_iter_hue(x_var, y_var, ax, func, **kwargs) return kwargs = kwargs.copy() if str(func.__module__).startswith("seaborn"): kwargs["ax"] = ax else: plt.sca(ax) if x_var == y_var: axes_vars = [x_var] else: axes_vars = [x_var, y_var] if self._hue_var is not None and self._hue_var not in axes_vars: axes_vars.append(self._hue_var) data = self.data[axes_vars] if self._dropna: data = data.dropna() x = data[x_var] y = data[y_var] if self._hue_var is None: hue = None else: hue = data.get(self._hue_var) if "hue" not in kwargs: kwargs.update({ "hue": hue, "hue_order": self._hue_order, "palette": self._orig_palette, }) func(x=x, y=y, **kwargs) self._update_legend_data(ax)
19,000
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
PairGrid._plot_bivariate_iter_hue
(self, x_var, y_var, ax, func, **kwargs)
Draw a bivariate plot while iterating over hue subsets.
Draw a bivariate plot while iterating over hue subsets.
1,613
1,655
def _plot_bivariate_iter_hue(self, x_var, y_var, ax, func, **kwargs): """Draw a bivariate plot while iterating over hue subsets.""" kwargs = kwargs.copy() if str(func.__module__).startswith("seaborn"): kwargs["ax"] = ax else: plt.sca(ax) if x_var == y_var: axes_vars = [x_var] else: axes_vars = [x_var, y_var] hue_grouped = self.data.groupby(self.hue_vals) for k, label_k in enumerate(self._hue_order): kws = kwargs.copy() # Attempt to get data for this level, allowing for empty try: data_k = hue_grouped.get_group(label_k) except KeyError: data_k = pd.DataFrame(columns=axes_vars, dtype=float) if self._dropna: data_k = data_k[axes_vars].dropna() x = data_k[x_var] y = data_k[y_var] for kw, val_list in self.hue_kws.items(): kws[kw] = val_list[k] kws.setdefault("color", self.palette[k]) if self._hue_var is not None: kws["label"] = label_k if str(func.__module__).startswith("seaborn"): func(x=x, y=y, **kws) else: func(x, y, **kws) self._update_legend_data(ax)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1613-L1655
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 ]
100
[]
0
true
96.911197
43
9
100
1
def _plot_bivariate_iter_hue(self, x_var, y_var, ax, func, **kwargs): kwargs = kwargs.copy() if str(func.__module__).startswith("seaborn"): kwargs["ax"] = ax else: plt.sca(ax) if x_var == y_var: axes_vars = [x_var] else: axes_vars = [x_var, y_var] hue_grouped = self.data.groupby(self.hue_vals) for k, label_k in enumerate(self._hue_order): kws = kwargs.copy() # Attempt to get data for this level, allowing for empty try: data_k = hue_grouped.get_group(label_k) except KeyError: data_k = pd.DataFrame(columns=axes_vars, dtype=float) if self._dropna: data_k = data_k[axes_vars].dropna() x = data_k[x_var] y = data_k[y_var] for kw, val_list in self.hue_kws.items(): kws[kw] = val_list[k] kws.setdefault("color", self.palette[k]) if self._hue_var is not None: kws["label"] = label_k if str(func.__module__).startswith("seaborn"): func(x=x, y=y, **kws) else: func(x, y, **kws) self._update_legend_data(ax)
19,001
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
PairGrid._add_axis_labels
(self)
Add labels to the left and bottom Axes.
Add labels to the left and bottom Axes.
1,657
1,662
def _add_axis_labels(self): """Add labels to the left and bottom Axes.""" for ax, label in zip(self.axes[-1, :], self.x_vars): ax.set_xlabel(label) for ax, label in zip(self.axes[:, 0], self.y_vars): ax.set_ylabel(label)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1657-L1662
26
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
96.911197
6
3
100
1
def _add_axis_labels(self): for ax, label in zip(self.axes[-1, :], self.x_vars): ax.set_xlabel(label) for ax, label in zip(self.axes[:, 0], self.y_vars): ax.set_ylabel(label)
19,002
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
PairGrid._find_numeric_cols
(self, data)
return numeric_cols
Find which variables in a DataFrame are numeric.
Find which variables in a DataFrame are numeric.
1,664
1,670
def _find_numeric_cols(self, data): """Find which variables in a DataFrame are numeric.""" numeric_cols = [] for col in data: if variable_type(data[col]) == "numeric": numeric_cols.append(col) return numeric_cols
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1664-L1670
26
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
96.911197
7
3
100
1
def _find_numeric_cols(self, data): numeric_cols = [] for col in data: if variable_type(data[col]) == "numeric": numeric_cols.append(col) return numeric_cols
19,003
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
JointGrid.__init__
( self, data=None, *, x=None, y=None, hue=None, height=6, ratio=5, space=.2, palette=None, hue_order=None, hue_norm=None, dropna=False, xlim=None, ylim=None, marginal_ticks=False, )
1,681
1,761
def __init__( self, data=None, *, x=None, y=None, hue=None, height=6, ratio=5, space=.2, palette=None, hue_order=None, hue_norm=None, dropna=False, xlim=None, ylim=None, marginal_ticks=False, ): # Set up the subplot grid f = plt.figure(figsize=(height, height)) gs = plt.GridSpec(ratio + 1, ratio + 1) ax_joint = f.add_subplot(gs[1:, :-1]) ax_marg_x = f.add_subplot(gs[0, :-1], sharex=ax_joint) ax_marg_y = f.add_subplot(gs[1:, -1], sharey=ax_joint) self._figure = f self.ax_joint = ax_joint self.ax_marg_x = ax_marg_x self.ax_marg_y = ax_marg_y # Turn off tick visibility for the measure axis on the marginal plots plt.setp(ax_marg_x.get_xticklabels(), visible=False) plt.setp(ax_marg_y.get_yticklabels(), visible=False) plt.setp(ax_marg_x.get_xticklabels(minor=True), visible=False) plt.setp(ax_marg_y.get_yticklabels(minor=True), visible=False) # Turn off the ticks on the density axis for the marginal plots if not marginal_ticks: plt.setp(ax_marg_x.yaxis.get_majorticklines(), visible=False) plt.setp(ax_marg_x.yaxis.get_minorticklines(), visible=False) plt.setp(ax_marg_y.xaxis.get_majorticklines(), visible=False) plt.setp(ax_marg_y.xaxis.get_minorticklines(), visible=False) plt.setp(ax_marg_x.get_yticklabels(), visible=False) plt.setp(ax_marg_y.get_xticklabels(), visible=False) plt.setp(ax_marg_x.get_yticklabels(minor=True), visible=False) plt.setp(ax_marg_y.get_xticklabels(minor=True), visible=False) ax_marg_x.yaxis.grid(False) ax_marg_y.xaxis.grid(False) # Process the input variables p = VectorPlotter(data=data, variables=dict(x=x, y=y, hue=hue)) plot_data = p.plot_data.loc[:, p.plot_data.notna().any()] # Possibly drop NA if dropna: plot_data = plot_data.dropna() def get_var(var): vector = plot_data.get(var, None) if vector is not None: vector = vector.rename(p.variables.get(var, None)) return vector self.x = get_var("x") self.y = get_var("y") self.hue = get_var("hue") for axis in "xy": name = p.variables.get(axis, None) if name is not None: getattr(ax_joint, f"set_{axis}label")(name) if xlim is not None: ax_joint.set_xlim(xlim) if ylim is not None: ax_joint.set_ylim(ylim) # Store the semantic mapping parameters for axes-level functions self._hue_params = dict(palette=palette, hue_order=hue_order, hue_norm=hue_norm) # Make the grid look nice utils.despine(f) if not marginal_ticks: utils.despine(ax=ax_marg_x, left=True) utils.despine(ax=ax_marg_y, bottom=True) for axes in [ax_marg_x, ax_marg_y]: for axis in [axes.xaxis, axes.yaxis]: axis.label.set_visible(False) f.tight_layout() f.subplots_adjust(hspace=space, wspace=space)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1681-L1761
26
[ 0, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80 ]
91.358025
[]
0
false
96.911197
81
12
100
0
def __init__( self, data=None, *, x=None, y=None, hue=None, height=6, ratio=5, space=.2, palette=None, hue_order=None, hue_norm=None, dropna=False, xlim=None, ylim=None, marginal_ticks=False, ): # Set up the subplot grid f = plt.figure(figsize=(height, height)) gs = plt.GridSpec(ratio + 1, ratio + 1) ax_joint = f.add_subplot(gs[1:, :-1]) ax_marg_x = f.add_subplot(gs[0, :-1], sharex=ax_joint) ax_marg_y = f.add_subplot(gs[1:, -1], sharey=ax_joint) self._figure = f self.ax_joint = ax_joint self.ax_marg_x = ax_marg_x self.ax_marg_y = ax_marg_y # Turn off tick visibility for the measure axis on the marginal plots plt.setp(ax_marg_x.get_xticklabels(), visible=False) plt.setp(ax_marg_y.get_yticklabels(), visible=False) plt.setp(ax_marg_x.get_xticklabels(minor=True), visible=False) plt.setp(ax_marg_y.get_yticklabels(minor=True), visible=False) # Turn off the ticks on the density axis for the marginal plots if not marginal_ticks: plt.setp(ax_marg_x.yaxis.get_majorticklines(), visible=False) plt.setp(ax_marg_x.yaxis.get_minorticklines(), visible=False) plt.setp(ax_marg_y.xaxis.get_majorticklines(), visible=False) plt.setp(ax_marg_y.xaxis.get_minorticklines(), visible=False) plt.setp(ax_marg_x.get_yticklabels(), visible=False) plt.setp(ax_marg_y.get_xticklabels(), visible=False) plt.setp(ax_marg_x.get_yticklabels(minor=True), visible=False) plt.setp(ax_marg_y.get_xticklabels(minor=True), visible=False) ax_marg_x.yaxis.grid(False) ax_marg_y.xaxis.grid(False) # Process the input variables p = VectorPlotter(data=data, variables=dict(x=x, y=y, hue=hue)) plot_data = p.plot_data.loc[:, p.plot_data.notna().any()] # Possibly drop NA if dropna: plot_data = plot_data.dropna() def get_var(var): vector = plot_data.get(var, None) if vector is not None: vector = vector.rename(p.variables.get(var, None)) return vector self.x = get_var("x") self.y = get_var("y") self.hue = get_var("hue") for axis in "xy": name = p.variables.get(axis, None) if name is not None: getattr(ax_joint, f"set_{axis}label")(name) if xlim is not None: ax_joint.set_xlim(xlim) if ylim is not None: ax_joint.set_ylim(ylim) # Store the semantic mapping parameters for axes-level functions self._hue_params = dict(palette=palette, hue_order=hue_order, hue_norm=hue_norm) # Make the grid look nice utils.despine(f) if not marginal_ticks: utils.despine(ax=ax_marg_x, left=True) utils.despine(ax=ax_marg_y, bottom=True) for axes in [ax_marg_x, ax_marg_y]: for axis in [axes.xaxis, axes.yaxis]: axis.label.set_visible(False) f.tight_layout() f.subplots_adjust(hspace=space, wspace=space)
19,004
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
JointGrid._inject_kwargs
(self, func, kws, params)
Add params to kws if they are accepted by func.
Add params to kws if they are accepted by func.
1,763
1,768
def _inject_kwargs(self, func, kws, params): """Add params to kws if they are accepted by func.""" func_params = signature(func).parameters for key, val in params.items(): if key in func_params: kws.setdefault(key, val)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1763-L1768
26
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
96.911197
6
3
100
1
def _inject_kwargs(self, func, kws, params): func_params = signature(func).parameters for key, val in params.items(): if key in func_params: kws.setdefault(key, val)
19,005
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
JointGrid.plot
(self, joint_func, marginal_func, **kwargs)
return self
Draw the plot by passing functions for joint and marginal axes. This method passes the ``kwargs`` dictionary to both functions. If you need more control, call :meth:`JointGrid.plot_joint` and :meth:`JointGrid.plot_marginals` directly with specific parameters. Parameters ---------- joint_func, marginal_func : callables Functions to draw the bivariate and univariate plots. See methods referenced above for information about the required characteristics of these functions. kwargs Additional keyword arguments are passed to both functions. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining.
Draw the plot by passing functions for joint and marginal axes.
1,770
1,794
def plot(self, joint_func, marginal_func, **kwargs): """Draw the plot by passing functions for joint and marginal axes. This method passes the ``kwargs`` dictionary to both functions. If you need more control, call :meth:`JointGrid.plot_joint` and :meth:`JointGrid.plot_marginals` directly with specific parameters. Parameters ---------- joint_func, marginal_func : callables Functions to draw the bivariate and univariate plots. See methods referenced above for information about the required characteristics of these functions. kwargs Additional keyword arguments are passed to both functions. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining. """ self.plot_marginals(marginal_func, **kwargs) self.plot_joint(joint_func, **kwargs) return self
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1770-L1794
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 ]
100
[]
0
true
96.911197
25
1
100
19
def plot(self, joint_func, marginal_func, **kwargs): self.plot_marginals(marginal_func, **kwargs) self.plot_joint(joint_func, **kwargs) return self
19,006
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
JointGrid.plot_joint
(self, func, **kwargs)
return self
Draw a bivariate plot on the joint axes of the grid. Parameters ---------- func : plotting callable If a seaborn function, it should accept ``x`` and ``y``. Otherwise, it must accept ``x`` and ``y`` vectors of data as the first two positional arguments, and it must plot on the "current" axes. If ``hue`` was defined in the class constructor, the function must accept ``hue`` as a parameter. kwargs Keyword argument are passed to the plotting function. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining.
Draw a bivariate plot on the joint axes of the grid.
1,796
1,830
def plot_joint(self, func, **kwargs): """Draw a bivariate plot on the joint axes of the grid. Parameters ---------- func : plotting callable If a seaborn function, it should accept ``x`` and ``y``. Otherwise, it must accept ``x`` and ``y`` vectors of data as the first two positional arguments, and it must plot on the "current" axes. If ``hue`` was defined in the class constructor, the function must accept ``hue`` as a parameter. kwargs Keyword argument are passed to the plotting function. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining. """ kwargs = kwargs.copy() if str(func.__module__).startswith("seaborn"): kwargs["ax"] = self.ax_joint else: plt.sca(self.ax_joint) if self.hue is not None: kwargs["hue"] = self.hue self._inject_kwargs(func, kwargs, self._hue_params) if str(func.__module__).startswith("seaborn"): func(x=self.x, y=self.y, **kwargs) else: func(self.x, self.y, **kwargs) return self
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1796-L1830
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34 ]
100
[]
0
true
96.911197
35
4
100
17
def plot_joint(self, func, **kwargs): kwargs = kwargs.copy() if str(func.__module__).startswith("seaborn"): kwargs["ax"] = self.ax_joint else: plt.sca(self.ax_joint) if self.hue is not None: kwargs["hue"] = self.hue self._inject_kwargs(func, kwargs, self._hue_params) if str(func.__module__).startswith("seaborn"): func(x=self.x, y=self.y, **kwargs) else: func(self.x, self.y, **kwargs) return self
19,007
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
JointGrid.plot_marginals
(self, func, **kwargs)
return self
Draw univariate plots on each marginal axes. Parameters ---------- func : plotting callable If a seaborn function, it should accept ``x`` and ``y`` and plot when only one of them is defined. Otherwise, it must accept a vector of data as the first positional argument and determine its orientation using the ``vertical`` parameter, and it must plot on the "current" axes. If ``hue`` was defined in the class constructor, it must accept ``hue`` as a parameter. kwargs Keyword argument are passed to the plotting function. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining.
Draw univariate plots on each marginal axes.
1,832
1,891
def plot_marginals(self, func, **kwargs): """Draw univariate plots on each marginal axes. Parameters ---------- func : plotting callable If a seaborn function, it should accept ``x`` and ``y`` and plot when only one of them is defined. Otherwise, it must accept a vector of data as the first positional argument and determine its orientation using the ``vertical`` parameter, and it must plot on the "current" axes. If ``hue`` was defined in the class constructor, it must accept ``hue`` as a parameter. kwargs Keyword argument are passed to the plotting function. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining. """ seaborn_func = ( str(func.__module__).startswith("seaborn") # deprecated distplot has a legacy API, special case it and not func.__name__ == "distplot" ) func_params = signature(func).parameters kwargs = kwargs.copy() if self.hue is not None: kwargs["hue"] = self.hue self._inject_kwargs(func, kwargs, self._hue_params) if "legend" in func_params: kwargs.setdefault("legend", False) if "orientation" in func_params: # e.g. plt.hist orient_kw_x = {"orientation": "vertical"} orient_kw_y = {"orientation": "horizontal"} elif "vertical" in func_params: # e.g. sns.distplot (also how did this get backwards?) orient_kw_x = {"vertical": False} orient_kw_y = {"vertical": True} if seaborn_func: func(x=self.x, ax=self.ax_marg_x, **kwargs) else: plt.sca(self.ax_marg_x) func(self.x, **orient_kw_x, **kwargs) if seaborn_func: func(y=self.y, ax=self.ax_marg_y, **kwargs) else: plt.sca(self.ax_marg_y) func(self.y, **orient_kw_y, **kwargs) self.ax_marg_x.yaxis.get_label().set_visible(False) self.ax_marg_y.xaxis.get_label().set_visible(False) return self
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1832-L1891
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59 ]
100
[]
0
true
96.911197
60
8
100
18
def plot_marginals(self, func, **kwargs): seaborn_func = ( str(func.__module__).startswith("seaborn") # deprecated distplot has a legacy API, special case it and not func.__name__ == "distplot" ) func_params = signature(func).parameters kwargs = kwargs.copy() if self.hue is not None: kwargs["hue"] = self.hue self._inject_kwargs(func, kwargs, self._hue_params) if "legend" in func_params: kwargs.setdefault("legend", False) if "orientation" in func_params: # e.g. plt.hist orient_kw_x = {"orientation": "vertical"} orient_kw_y = {"orientation": "horizontal"} elif "vertical" in func_params: # e.g. sns.distplot (also how did this get backwards?) orient_kw_x = {"vertical": False} orient_kw_y = {"vertical": True} if seaborn_func: func(x=self.x, ax=self.ax_marg_x, **kwargs) else: plt.sca(self.ax_marg_x) func(self.x, **orient_kw_x, **kwargs) if seaborn_func: func(y=self.y, ax=self.ax_marg_y, **kwargs) else: plt.sca(self.ax_marg_y) func(self.y, **orient_kw_y, **kwargs) self.ax_marg_x.yaxis.get_label().set_visible(False) self.ax_marg_y.xaxis.get_label().set_visible(False) return self
19,008
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
JointGrid.refline
( self, *, x=None, y=None, joint=True, marginal=True, color='.5', linestyle='--', **line_kws )
return self
Add a reference line(s) to joint and/or marginal axes. Parameters ---------- x, y : numeric Value(s) to draw the line(s) at. joint, marginal : bools Whether to add the reference line(s) to the joint/marginal axes. color : :mod:`matplotlib color <matplotlib.colors>` Specifies the color of the reference line(s). linestyle : str Specifies the style of the reference line(s). line_kws : key, value mappings Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline` when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y`` is not None. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining.
Add a reference line(s) to joint and/or marginal axes.
1,893
1,935
def refline( self, *, x=None, y=None, joint=True, marginal=True, color='.5', linestyle='--', **line_kws ): """Add a reference line(s) to joint and/or marginal axes. Parameters ---------- x, y : numeric Value(s) to draw the line(s) at. joint, marginal : bools Whether to add the reference line(s) to the joint/marginal axes. color : :mod:`matplotlib color <matplotlib.colors>` Specifies the color of the reference line(s). linestyle : str Specifies the style of the reference line(s). line_kws : key, value mappings Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.axvline` when ``x`` is not None and :meth:`matplotlib.axes.Axes.axhline` when ``y`` is not None. Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining. """ line_kws['color'] = color line_kws['linestyle'] = linestyle if x is not None: if joint: self.ax_joint.axvline(x, **line_kws) if marginal: self.ax_marg_x.axvline(x, **line_kws) if y is not None: if joint: self.ax_joint.axhline(y, **line_kws) if marginal: self.ax_marg_y.axhline(y, **line_kws) return self
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1893-L1935
26
[ 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 ]
41.860465
[]
0
false
96.911197
43
7
100
21
def refline( self, *, x=None, y=None, joint=True, marginal=True, color='.5', linestyle='--', **line_kws ): line_kws['color'] = color line_kws['linestyle'] = linestyle if x is not None: if joint: self.ax_joint.axvline(x, **line_kws) if marginal: self.ax_marg_x.axvline(x, **line_kws) if y is not None: if joint: self.ax_joint.axhline(y, **line_kws) if marginal: self.ax_marg_y.axhline(y, **line_kws) return self
19,009
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/axisgrid.py
JointGrid.set_axis_labels
(self, xlabel="", ylabel="", **kwargs)
return self
Set axis labels on the bivariate axes. Parameters ---------- xlabel, ylabel : strings Label names for the x and y variables. kwargs : key, value mappings Other keyword arguments are passed to the following functions: - :meth:`matplotlib.axes.Axes.set_xlabel` - :meth:`matplotlib.axes.Axes.set_ylabel` Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining.
Set axis labels on the bivariate axes.
1,937
1,958
def set_axis_labels(self, xlabel="", ylabel="", **kwargs): """Set axis labels on the bivariate axes. Parameters ---------- xlabel, ylabel : strings Label names for the x and y variables. kwargs : key, value mappings Other keyword arguments are passed to the following functions: - :meth:`matplotlib.axes.Axes.set_xlabel` - :meth:`matplotlib.axes.Axes.set_ylabel` Returns ------- :class:`JointGrid` instance Returns ``self`` for easy method chaining. """ self.ax_joint.set_xlabel(xlabel, **kwargs) self.ax_joint.set_ylabel(ylabel, **kwargs) return self
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/axisgrid.py#L1937-L1958
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ]
100
[]
0
true
96.911197
22
1
100
16
def set_axis_labels(self, xlabel="", ylabel="", **kwargs): self.ax_joint.set_xlabel(xlabel, **kwargs) self.ax_joint.set_ylabel(ylabel, **kwargs) return self
19,010
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/rcmod.py
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 aspects of the visual theme for all matplotlib and seaborn plots.
82
123
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)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/rcmod.py#L82-L123
26
[ 0, 36, 37, 38, 39, 40, 41 ]
16.666667
[]
0
false
100
42
2
100
32
def set_theme(context="notebook", style="darkgrid", palette="deep", font="sans-serif", font_scale=1, color_codes=True, rc=None): 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)
19,011
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/rcmod.py
set
(*args, **kwargs)
Alias for :func:`set_theme`, which is the preferred interface. This function may be removed in the future.
Alias for :func:`set_theme`, which is the preferred interface.
126
132
def set(*args, **kwargs): """ Alias for :func:`set_theme`, which is the preferred interface. This function may be removed in the future. """ set_theme(*args, **kwargs)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/rcmod.py#L126-L132
26
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
100
7
1
100
3
def set(*args, **kwargs): set_theme(*args, **kwargs)
19,012
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/rcmod.py
reset_defaults
()
Restore all RC params to default settings.
Restore all RC params to default settings.
135
137
def reset_defaults(): """Restore all RC params to default settings.""" mpl.rcParams.update(mpl.rcParamsDefault)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/rcmod.py#L135-L137
26
[ 0, 1, 2 ]
100
[]
0
true
100
3
1
100
1
def reset_defaults(): mpl.rcParams.update(mpl.rcParamsDefault)
19,013
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/rcmod.py
reset_orig
()
Restore all RC params to original settings (respects custom rc).
Restore all RC params to original settings (respects custom rc).
140
143
def reset_orig(): """Restore all RC params to original settings (respects custom rc).""" from . import _orig_rc_params mpl.rcParams.update(_orig_rc_params)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/rcmod.py#L140-L143
26
[ 0, 1, 2, 3 ]
100
[]
0
true
100
4
1
100
1
def reset_orig(): from . import _orig_rc_params mpl.rcParams.update(_orig_rc_params)
19,014
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/rcmod.py
axes_style
(style=None, rc=None)
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
Get the parameters that control the general style of the plots.
146
300
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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/rcmod.py#L146-L300
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154 ]
100
[]
0
true
100
155
10
100
26
def axes_style(style=None, rc=None): 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
19,015
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/rcmod.py
set_style
(style=None, rc=None)
Set 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>`. See :func:`axes_style` to get the parameter values. Parameters ---------- style : 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/set_style.rst
Set the parameters that control the general style of the plots.
303
332
def set_style(style=None, rc=None): """ Set 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>`. See :func:`axes_style` to get the parameter values. Parameters ---------- style : 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/set_style.rst """ style_object = axes_style(style, rc) mpl.rcParams.update(style_object)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/rcmod.py#L303-L332
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 ]
100
[]
0
true
100
30
1
100
24
def set_style(style=None, rc=None): style_object = axes_style(style, rc) mpl.rcParams.update(style_object)
19,016
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/rcmod.py
plotting_context
(context=None, font_scale=1, rc=None)
return context_object
Get the parameters that control the scaling of plot elements. This affects things like the size of the labels, lines, and other elements of the plot, but not the overall style. This is accomplished using the matplotlib rcParams system. 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
Get the parameters that control the scaling of plot elements.
335
433
def plotting_context(context=None, font_scale=1, rc=None): """ Get the parameters that control the scaling of plot elements. This affects things like the size of the labels, lines, and other elements of the plot, but not the overall style. This is accomplished using the matplotlib rcParams system. 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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/rcmod.py#L335-L433
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98 ]
100
[]
0
true
100
99
5
100
31
def plotting_context(context=None, font_scale=1, rc=None): 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
19,017
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/rcmod.py
set_context
(context=None, font_scale=1, rc=None)
Set the parameters that control the scaling of plot elements. This affects things like the size of the labels, lines, and other elements of the plot, but not the overall style. This is accomplished using the matplotlib rcParams system. 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. See :func:`plotting_context` to get the parameter values. Parameters ---------- context : 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/set_context.rst
Set the parameters that control the scaling of plot elements.
436
470
def set_context(context=None, font_scale=1, rc=None): """ Set the parameters that control the scaling of plot elements. This affects things like the size of the labels, lines, and other elements of the plot, but not the overall style. This is accomplished using the matplotlib rcParams system. 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. See :func:`plotting_context` to get the parameter values. Parameters ---------- context : 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/set_context.rst """ context_object = plotting_context(context, font_scale, rc) mpl.rcParams.update(context_object)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/rcmod.py#L436-L470
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34 ]
100
[]
0
true
100
35
1
100
29
def set_context(context=None, font_scale=1, rc=None): context_object = plotting_context(context, font_scale, rc) mpl.rcParams.update(context_object)
19,018
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/rcmod.py
set_palette
(palette, n_colors=None, desat=None, color_codes=False)
Set the matplotlib color cycle using a seaborn palette. Parameters ---------- palette : seaborn color paltte | 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 the matplotlib color cycle using a seaborn palette.
502
534
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 paltte | 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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/rcmod.py#L502-L534
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ]
100
[]
0
true
100
33
3
100
22
def set_palette(palette, n_colors=None, desat=None, color_codes=False): 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
19,019
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/rcmod.py
_RCAesthetics.__enter__
(self)
474
477
def __enter__(self): rc = mpl.rcParams self._orig = {k: rc[k] for k in self._keys} self._set(self)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/rcmod.py#L474-L477
26
[ 0, 1, 2, 3 ]
100
[]
0
true
100
4
1
100
0
def __enter__(self): rc = mpl.rcParams self._orig = {k: rc[k] for k in self._keys} self._set(self)
19,020
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/rcmod.py
_RCAesthetics.__exit__
(self, exc_type, exc_value, exc_tb)
479
480
def __exit__(self, exc_type, exc_value, exc_tb): self._set(self._orig)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/rcmod.py#L479-L480
26
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def __exit__(self, exc_type, exc_value, exc_tb): self._set(self._orig)
19,021
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/rcmod.py
_RCAesthetics.__call__
(self, func)
return wrapper
482
487
def __call__(self, func): @functools.wraps(func) def wrapper(*args, **kwargs): with self: return func(*args, **kwargs) return wrapper
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/rcmod.py#L482-L487
26
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
100
6
3
100
0
def __call__(self, func): @functools.wraps(func) def wrapper(*args, **kwargs): with self: return func(*args, **kwargs) return wrapper
19,022
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
ci_to_errsize
(cis, heights)
return errsize
Convert intervals to error arguments relative to plot heights. Parameters ---------- cis : 2 x n sequence sequence of confidence interval limits heights : n sequence sequence of plot heights Returns ------- errsize : 2 x n array sequence of error size relative to height values in correct format as argument for plt.bar
Convert intervals to error arguments relative to plot heights.
25
52
def ci_to_errsize(cis, heights): """Convert intervals to error arguments relative to plot heights. Parameters ---------- cis : 2 x n sequence sequence of confidence interval limits heights : n sequence sequence of plot heights Returns ------- errsize : 2 x n array sequence of error size relative to height values in correct format as argument for plt.bar """ cis = np.atleast_2d(cis).reshape(2, -1) heights = np.atleast_1d(heights) errsize = [] for i, (low, high) in enumerate(np.transpose(cis)): h = heights[i] elow = h - low ehigh = high - h errsize.append([elow, ehigh]) errsize = np.asarray(errsize).T return errsize
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L25-L52
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 ]
100
[]
0
true
93.220339
28
2
100
14
def ci_to_errsize(cis, heights): cis = np.atleast_2d(cis).reshape(2, -1) heights = np.atleast_1d(heights) errsize = [] for i, (low, high) in enumerate(np.transpose(cis)): h = heights[i] elow = h - low ehigh = high - h errsize.append([elow, ehigh]) errsize = np.asarray(errsize).T return errsize
19,023
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
_normal_quantile_func
(q)
return qf(q)
Compute the quantile function of the standard normal distribution. This wrapper exists because we are dropping scipy as a mandatory dependency but statistics.NormalDist was added to the standard library in 3.8.
Compute the quantile function of the standard normal distribution.
55
75
def _normal_quantile_func(q): """ Compute the quantile function of the standard normal distribution. This wrapper exists because we are dropping scipy as a mandatory dependency but statistics.NormalDist was added to the standard library in 3.8. """ try: from statistics import NormalDist qf = np.vectorize(NormalDist().inv_cdf) except ImportError: try: from scipy.stats import norm qf = norm.ppf except ImportError: msg = ( "Standard normal quantile functions require either Python>=3.8 or scipy" ) raise RuntimeError(msg) return qf(q)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L55-L75
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20 ]
57.142857
[ 11, 12, 13, 14, 15, 16, 19 ]
33.333333
false
93.220339
21
3
66.666667
4
def _normal_quantile_func(q): try: from statistics import NormalDist qf = np.vectorize(NormalDist().inv_cdf) except ImportError: try: from scipy.stats import norm qf = norm.ppf except ImportError: msg = ( "Standard normal quantile functions require either Python>=3.8 or scipy" ) raise RuntimeError(msg) return qf(q)
19,024
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
_draw_figure
(fig)
Force draw of a matplotlib figure, accounting for back-compat.
Force draw of a matplotlib figure, accounting for back-compat.
78
86
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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L78-L86
26
[ 0, 1, 2, 3, 4 ]
55.555556
[ 5, 6, 7, 8 ]
44.444444
false
93.220339
9
3
55.555556
1
def _draw_figure(fig): # 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
19,025
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
_default_color
(method, hue, color, kws)
return color
If needed, get a default color by using the matplotlib property cycle.
If needed, get a default color by using the matplotlib property cycle.
89
157
def _default_color(method, hue, color, kws): """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: 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() 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() return color
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L89-L157
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68 ]
98.550725
[ 43 ]
1.449275
false
93.220339
69
10
98.550725
1
def _default_color(method, hue, color, kws): 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: 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() 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() return color
19,026
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
desaturate
(color, prop)
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
Decrease the saturation channel of a color by some percent.
160
192
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) # 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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L160-L192
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ]
100
[]
0
true
93.220339
33
2
100
13
def desaturate(color, prop): # Check inputs if not 0 <= prop <= 1: raise ValueError("prop must be between 0 and 1") # Get rgb tuple rep rgb = to_rgb(color) # 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
19,027
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
saturate
(color)
return set_hls_values(color, s=1)
Return a fully saturated color with the same hue. Parameters ---------- color : matplotlib color hex, rgb-tuple, or html color name Returns ------- new_color : rgb tuple saturated color code in RGB tuple representation
Return a fully saturated color with the same hue.
195
209
def saturate(color): """Return a fully saturated color with the same hue. Parameters ---------- color : matplotlib color hex, rgb-tuple, or html color name Returns ------- new_color : rgb tuple saturated color code in RGB tuple representation """ return set_hls_values(color, s=1)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L195-L209
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
93.220339
15
1
100
11
def saturate(color): return set_hls_values(color, s=1)
19,028
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
set_hls_values
(color, h=None, l=None, s=None)
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
Independently manipulate the h, l, or s channels of a color.
212
236
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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L212-L236
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 ]
100
[]
0
true
93.220339
25
3
100
13
def set_hls_values(color, h=None, l=None, s=None): # noqa # 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
19,029
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
axlabel
(xlabel, ylabel, **kwargs)
Grab current axis and label it. DEPRECATED: will be removed in a future version.
Grab current axis and label it.
239
249
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)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L239-L249
26
[ 0, 1, 2, 3, 4, 5 ]
54.545455
[ 6, 7, 8, 9, 10 ]
45.454545
false
93.220339
11
1
54.545455
3
def axlabel(xlabel, ylabel, **kwargs): 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)
19,030
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
remove_na
(vector)
return vector[pd.notnull(vector)]
Helper method for removing null values from data vectors. Parameters ---------- vector : vector object Must implement boolean masking with [] subscript syntax. Returns ------- clean_clean : same type as ``vector`` Vector of data with null values removed. May be a copy or a view.
Helper method for removing null values from data vectors.
252
266
def remove_na(vector): """Helper method for removing null values from data vectors. Parameters ---------- vector : vector object Must implement boolean masking with [] subscript syntax. Returns ------- clean_clean : same type as ``vector`` Vector of data with null values removed. May be a copy or a view. """ return vector[pd.notnull(vector)]
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L252-L266
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
93.220339
15
1
100
11
def remove_na(vector): return vector[pd.notnull(vector)]
19,031
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
get_color_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.
Return the list of colors in the current matplotlib color cycle
269
283
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"]
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L269-L283
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
93.220339
15
1
100
11
def get_color_cycle(): cycler = mpl.rcParams['axes.prop_cycle'] return cycler.by_key()['color'] if 'color' in cycler.keys else [".15"]
19,032
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
despine
(fig=None, ax=None, top=True, right=True, left=False, bottom=False, offset=None, trim=False)
Remove the top and right spines from plot(s). fig : matplotlib figure, optional Figure to despine all axes of, defaults to the current figure. ax : matplotlib axes, optional Specific axes object to despine. Ignored if fig is provided. top, right, left, bottom : boolean, optional If True, remove that spine. offset : int or dict, optional Absolute distance, in points, spines should be moved away from the axes (negative values move spines inward). A single value applies to all spines; a dict can be used to set offset values per side. trim : bool, optional If True, limit spines to the smallest and largest major tick on each non-despined axis. Returns ------- None
Remove the top and right spines from plot(s).
286
385
def despine(fig=None, ax=None, top=True, right=True, left=False, bottom=False, offset=None, trim=False): """Remove the top and right spines from plot(s). fig : matplotlib figure, optional Figure to despine all axes of, defaults to the current figure. ax : matplotlib axes, optional Specific axes object to despine. Ignored if fig is provided. top, right, left, bottom : boolean, optional If True, remove that spine. offset : int or dict, optional Absolute distance, in points, spines should be moved away from the axes (negative values move spines inward). A single value applies to all spines; a dict can be used to set offset values per side. trim : bool, optional If True, limit spines to the smallest and largest major tick on each non-despined axis. Returns ------- None """ # Get references to the axes we want if fig is None and ax is None: axes = plt.gcf().axes elif fig is not None: axes = fig.axes elif ax is not None: axes = [ax] for ax_i in axes: for side in ["top", "right", "left", "bottom"]: # Toggle the spine objects is_visible = not locals()[side] ax_i.spines[side].set_visible(is_visible) if offset is not None and is_visible: try: val = offset.get(side, 0) except AttributeError: val = offset ax_i.spines[side].set_position(('outward', val)) # Potentially move the ticks if left and not right: maj_on = any( t.tick1line.get_visible() for t in ax_i.yaxis.majorTicks ) min_on = any( t.tick1line.get_visible() for t in ax_i.yaxis.minorTicks ) ax_i.yaxis.set_ticks_position("right") for t in ax_i.yaxis.majorTicks: t.tick2line.set_visible(maj_on) for t in ax_i.yaxis.minorTicks: t.tick2line.set_visible(min_on) if bottom and not top: maj_on = any( t.tick1line.get_visible() for t in ax_i.xaxis.majorTicks ) min_on = any( t.tick1line.get_visible() for t in ax_i.xaxis.minorTicks ) ax_i.xaxis.set_ticks_position("top") for t in ax_i.xaxis.majorTicks: t.tick2line.set_visible(maj_on) for t in ax_i.xaxis.minorTicks: t.tick2line.set_visible(min_on) if trim: # clip off the parts of the spines that extend past major ticks xticks = np.asarray(ax_i.get_xticks()) if xticks.size: firsttick = np.compress(xticks >= min(ax_i.get_xlim()), xticks)[0] lasttick = np.compress(xticks <= max(ax_i.get_xlim()), xticks)[-1] ax_i.spines['bottom'].set_bounds(firsttick, lasttick) ax_i.spines['top'].set_bounds(firsttick, lasttick) newticks = xticks.compress(xticks <= lasttick) newticks = newticks.compress(newticks >= firsttick) ax_i.set_xticks(newticks) yticks = np.asarray(ax_i.get_yticks()) if yticks.size: firsttick = np.compress(yticks >= min(ax_i.get_ylim()), yticks)[0] lasttick = np.compress(yticks <= max(ax_i.get_ylim()), yticks)[-1] ax_i.spines['left'].set_bounds(firsttick, lasttick) ax_i.spines['right'].set_bounds(firsttick, lasttick) newticks = yticks.compress(yticks <= lasttick) newticks = newticks.compress(newticks >= firsttick) ax_i.set_yticks(newticks)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L286-L385
26
[ 0, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 50, 54, 55, 56, 57, 58, 59, 60, 61, 65, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 81, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93, 95, 96, 97, 98, 99 ]
61
[]
0
false
93.220339
100
21
100
20
def despine(fig=None, ax=None, top=True, right=True, left=False, bottom=False, offset=None, trim=False): # Get references to the axes we want if fig is None and ax is None: axes = plt.gcf().axes elif fig is not None: axes = fig.axes elif ax is not None: axes = [ax] for ax_i in axes: for side in ["top", "right", "left", "bottom"]: # Toggle the spine objects is_visible = not locals()[side] ax_i.spines[side].set_visible(is_visible) if offset is not None and is_visible: try: val = offset.get(side, 0) except AttributeError: val = offset ax_i.spines[side].set_position(('outward', val)) # Potentially move the ticks if left and not right: maj_on = any( t.tick1line.get_visible() for t in ax_i.yaxis.majorTicks ) min_on = any( t.tick1line.get_visible() for t in ax_i.yaxis.minorTicks ) ax_i.yaxis.set_ticks_position("right") for t in ax_i.yaxis.majorTicks: t.tick2line.set_visible(maj_on) for t in ax_i.yaxis.minorTicks: t.tick2line.set_visible(min_on) if bottom and not top: maj_on = any( t.tick1line.get_visible() for t in ax_i.xaxis.majorTicks ) min_on = any( t.tick1line.get_visible() for t in ax_i.xaxis.minorTicks ) ax_i.xaxis.set_ticks_position("top") for t in ax_i.xaxis.majorTicks: t.tick2line.set_visible(maj_on) for t in ax_i.xaxis.minorTicks: t.tick2line.set_visible(min_on) if trim: # clip off the parts of the spines that extend past major ticks xticks = np.asarray(ax_i.get_xticks()) if xticks.size: firsttick = np.compress(xticks >= min(ax_i.get_xlim()), xticks)[0] lasttick = np.compress(xticks <= max(ax_i.get_xlim()), xticks)[-1] ax_i.spines['bottom'].set_bounds(firsttick, lasttick) ax_i.spines['top'].set_bounds(firsttick, lasttick) newticks = xticks.compress(xticks <= lasttick) newticks = newticks.compress(newticks >= firsttick) ax_i.set_xticks(newticks) yticks = np.asarray(ax_i.get_yticks()) if yticks.size: firsttick = np.compress(yticks >= min(ax_i.get_ylim()), yticks)[0] lasttick = np.compress(yticks <= max(ax_i.get_ylim()), yticks)[-1] ax_i.spines['left'].set_bounds(firsttick, lasttick) ax_i.spines['right'].set_bounds(firsttick, lasttick) newticks = yticks.compress(yticks <= lasttick) newticks = newticks.compress(newticks >= firsttick) ax_i.set_yticks(newticks)
19,033
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
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
Recreate a plot's legend at a new location.
388
475
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 handles = old_legend.legendHandles labels = [t.get_text() for t in old_legend.get_texts()] # 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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L388-L475
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87 ]
100
[]
0
true
93.220339
88
10
100
24
def move_legend(obj, loc, **kwargs): # 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 handles = old_legend.legendHandles labels = [t.get_text() for t in old_legend.get_texts()] # 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
19,034
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
_kde_support
(data, bw, gridsize, cut, clip)
return support
Establish support for a kernel density estimate.
Establish support for a kernel density estimate.
478
484
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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L478-L484
26
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
93.220339
7
1
100
1
def _kde_support(data, bw, gridsize, cut, clip): 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
19,035
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
ci
(a, which=95, axis=None)
return np.nanpercentile(a, p, axis)
Return a percentile range from an array of values.
Return a percentile range from an array of values.
487
490
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)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L487-L490
26
[ 0, 1, 2, 3 ]
100
[]
0
true
93.220339
4
1
100
1
def ci(a, which=95, axis=None): p = 50 - which / 2, 50 + which / 2 return np.nanpercentile(a, p, axis)
19,036
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
get_dataset_names
()
return datasets
Report available example datasets, useful for reporting issues. Requires an internet connection.
Report available example datasets, useful for reporting issues.
493
505
def get_dataset_names(): """Report available example datasets, useful for reporting issues. Requires an internet connection. """ url = "https://github.com/mwaskom/seaborn-data" with urlopen(url) as resp: html = resp.read() pat = r"/mwaskom/seaborn-data/blob/master/(\w*).csv" datasets = re.findall(pat, html.decode()) return datasets
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L493-L505
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
93.220339
13
2
100
3
def get_dataset_names(): url = "https://github.com/mwaskom/seaborn-data" with urlopen(url) as resp: html = resp.read() pat = r"/mwaskom/seaborn-data/blob/master/(\w*).csv" datasets = re.findall(pat, html.decode()) return datasets
19,037
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
get_data_home
(data_home=None)
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.
Return a path to the cache directory for example datasets.
508
523
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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L508-L523
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15 ]
93.75
[ 14 ]
6.25
false
93.220339
16
3
93.75
7
def get_data_home(data_home=None): 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
19,038
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
load_dataset
(name, cache=True, data_home=None, **kws)
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 an example dataset from the online repository (requires internet).
526
631
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"https://raw.githubusercontent.com/mwaskom/seaborn-data/master/{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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L526-L631
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105 ]
97.169811
[ 58 ]
0.943396
false
93.220339
106
15
99.056604
29
def load_dataset(name, cache=True, data_home=None, **kws): # 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"https://raw.githubusercontent.com/mwaskom/seaborn-data/master/{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
19,039
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
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.
Return a boolean for whether the list of ticklabels have overlaps.
634
655
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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L634-L655
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
86.363636
[ 19, 21 ]
9.090909
false
93.220339
22
5
90.909091
10
def axis_ticklabels_overlap(labels): 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
19,040
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
axes_ticklabels_overlap
(ax)
return (axis_ticklabels_overlap(ax.get_xticklabels()), axis_ticklabels_overlap(ax.get_yticklabels()))
Return booleans for whether the x and y ticklabels on an Axes overlap. Parameters ---------- ax : matplotlib Axes Returns ------- x_overlap, y_overlap : booleans True when the labels on that axis overlap.
Return booleans for whether the x and y ticklabels on an Axes overlap.
658
672
def axes_ticklabels_overlap(ax): """Return booleans for whether the x and y ticklabels on an Axes overlap. Parameters ---------- ax : matplotlib Axes Returns ------- x_overlap, y_overlap : booleans True when the labels on that axis overlap. """ return (axis_ticklabels_overlap(ax.get_xticklabels()), axis_ticklabels_overlap(ax.get_yticklabels()))
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L658-L672
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
93.220339
15
1
100
10
def axes_ticklabels_overlap(ax): return (axis_ticklabels_overlap(ax.get_xticklabels()), axis_ticklabels_overlap(ax.get_yticklabels()))
19,041
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
locator_to_legend_entries
(locator, limits, dtype)
return raw_levels, formatted_levels
Return levels and formatted levels for brief numeric legends.
Return levels and formatted levels for brief numeric legends.
675
702
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() # TODO: The following two lines should be replaced # once pinned matplotlib>=3.1.0 with: # formatted_levels = formatter.format_ticks(raw_levels) formatter.set_locs(raw_levels) formatted_levels = [formatter(x) for x in raw_levels] return raw_levels, formatted_levels
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L675-L702
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 ]
100
[]
0
true
93.220339
28
6
100
1
def locator_to_legend_entries(locator, limits, dtype): 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() # TODO: The following two lines should be replaced # once pinned matplotlib>=3.1.0 with: # formatted_levels = formatter.format_ticks(raw_levels) formatter.set_locs(raw_levels) formatted_levels = [formatter(x) for x in raw_levels] return raw_levels, formatted_levels
19,042
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
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
Calculate the relative luminance of a color according to W3C standards
705
724
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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L705-L724
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
100
[]
0
true
93.220339
20
2
100
10
def relative_luminance(color): 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
19,043
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
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``
Return a string representing a Python object.
727
753
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)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L727-L753
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 ]
100
[]
0
true
93.220339
27
3
100
18
def to_utf8(obj): if isinstance(obj, str): return obj try: return obj.decode(encoding="utf-8") except AttributeError: # obj is not bytes-like return str(obj)
19,044
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
_normalize_kwargs
(kws, artist)
return kws
Wrapper for mpl.cbook.normalize_kwargs that supports <= 3.2.1.
Wrapper for mpl.cbook.normalize_kwargs that supports <= 3.2.1.
756
773
def _normalize_kwargs(kws, artist): """Wrapper for mpl.cbook.normalize_kwargs that supports <= 3.2.1.""" _alias_map = { 'color': ['c'], 'linewidth': ['lw'], 'linestyle': ['ls'], 'facecolor': ['fc'], 'edgecolor': ['ec'], 'markerfacecolor': ['mfc'], 'markeredgecolor': ['mec'], 'markeredgewidth': ['mew'], 'markersize': ['ms'] } try: kws = normalize_kwargs(kws, artist) except AttributeError: kws = normalize_kwargs(kws, _alias_map) return kws
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L756-L773
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17 ]
88.888889
[ 15, 16 ]
11.111111
false
93.220339
18
2
88.888889
1
def _normalize_kwargs(kws, artist): _alias_map = { 'color': ['c'], 'linewidth': ['lw'], 'linestyle': ['ls'], 'facecolor': ['fc'], 'edgecolor': ['ec'], 'markerfacecolor': ['mfc'], 'markeredgecolor': ['mec'], 'markeredgewidth': ['mew'], 'markersize': ['ms'] } try: kws = normalize_kwargs(kws, artist) except AttributeError: kws = normalize_kwargs(kws, _alias_map) return kws
19,045
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
_check_argument
(param, options, value)
Raise if value for param is not in options.
Raise if value for param is not in options.
776
781
def _check_argument(param, options, value): """Raise if value for param is not in options.""" if value not in options: raise ValueError( f"`{param}` must be one of {options}, but {repr(value)} was passed." )
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L776-L781
26
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
93.220339
6
2
100
1
def _check_argument(param, options, value): if value not in options: raise ValueError( f"`{param}` must be one of {options}, but {repr(value)} was passed." )
19,046
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
_assign_default_kwargs
(kws, call_func, source_func)
return kws
Assign default kwargs for call_func using values from source_func.
Assign default kwargs for call_func using values from source_func.
784
800
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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L784-L800
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
100
[]
0
true
93.220339
17
4
100
1
def _assign_default_kwargs(kws, call_func, 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
19,047
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
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.
Make invisible-handle "subtitles" entries look more like titles.
803
820
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)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L803-L820
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
94.444444
[ 17 ]
5.555556
false
93.220339
18
5
94.444444
3
def adjust_legend_subtitles(legend): # 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)
19,048
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
_deprecate_ci
(errorbar, ci)
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.
Warn on usage of ci= and convert to appropriate errorbar= arg.
823
845
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 != "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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L823-L845
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
100
[]
0
true
93.220339
23
4
100
5
def _deprecate_ci(errorbar, ci): if 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
19,049
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
_disable_autolayout
()
Context manager for preventing rc-controlled auto-layout behavior.
Context manager for preventing rc-controlled auto-layout behavior.
849
864
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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L849-L864
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
93.220339
16
1
100
1
def _disable_autolayout(): # 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
19,050
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/utils.py
_version_predates
(lib: ModuleType, version: str)
return Version(lib.__version__) < Version(version)
Helper function for checking version compatibility.
Helper function for checking version compatibility.
867
869
def _version_predates(lib: ModuleType, version: str) -> bool: """Helper function for checking version compatibility.""" return Version(lib.__version__) < Version(version)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/utils.py#L867-L869
26
[ 0, 1, 2 ]
100
[]
0
true
93.220339
3
1
100
1
def _version_predates(lib: ModuleType, version: str) -> bool: return Version(lib.__version__) < Version(version)
19,051
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
variable_type
(vector, boolean_type="numeric")
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.
Determine whether a vector contains numeric, categorical, or datetime data.
1,469
1,549
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. """ # If a categorical dtype is set, infer categorical if pd.api.types.is_categorical_dtype(vector): return VariableType("categorical") # Special-case all-na data, which is always "numeric" if pd.isna(vector).all(): return VariableType("numeric") # 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) ) if np.isin(vector, [0, 1, np.nan]).all(): return VariableType(boolean_type) # 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")
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1469-L1549
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80 ]
100
[]
0
true
97.668038
81
15
100
20
def variable_type(vector, boolean_type="numeric"): # If a categorical dtype is set, infer categorical if pd.api.types.is_categorical_dtype(vector): return VariableType("categorical") # Special-case all-na data, which is always "numeric" if pd.isna(vector).all(): return VariableType("numeric") # 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) ) if np.isin(vector, [0, 1, np.nan]).all(): return VariableType(boolean_type) # 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")
19,060
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
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, which must start with "v" or "h" if not None. require_numeric : bool If set, raise when the implied dependent variable is not numeric. Returns ------- orient : "v" or "h" Raises ------ ValueError: When `orient` is not None and does not start with "h" or "v" TypeError: When dependent variable is not numeric, with `require_numeric`
Determine how the plot should be oriented based on the data.
1,552
1,631
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, which must start with "v" or "h" if not None. require_numeric : bool If set, raise when the implied dependent variable is not numeric. Returns ------- orient : "v" or "h" Raises ------ ValueError: When `orient` is not None and does not start with "h" or "v" TypeError: When 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 "v" 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 "h" elif str(orient).startswith("v"): if require_numeric and y_type != "numeric": raise TypeError(nonnumeric_dv_error.format("Vertical", "y")) return "v" elif str(orient).startswith("h"): if require_numeric and x_type != "numeric": raise TypeError(nonnumeric_dv_error.format("Horizontal", "x")) return "h" 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 "h" elif x_type != "numeric" and y_type == "numeric": return "v" elif x_type == "numeric" and y_type != "numeric": return "h" 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 "v"
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1552-L1631
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79 ]
100
[]
0
true
97.668038
80
24
100
24
def infer_orient(x=None, y=None, orient=None, require_numeric=True): 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 "v" 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 "h" elif str(orient).startswith("v"): if require_numeric and y_type != "numeric": raise TypeError(nonnumeric_dv_error.format("Vertical", "y")) return "v" elif str(orient).startswith("h"): if require_numeric and x_type != "numeric": raise TypeError(nonnumeric_dv_error.format("Horizontal", "x")) return "h" 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 "h" elif x_type != "numeric" and y_type == "numeric": return "v" elif x_type == "numeric" and y_type != "numeric": return "h" 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 "v"
19,061
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
unique_dashes
(n)
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.
Build an arbitrarily long list of unique dash styles for lines.
1,634
1,682
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]
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1634-L1682
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48 ]
100
[]
0
true
97.668038
49
3
100
14
def unique_dashes(n): # 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]
19,062
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
unique_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.
Build an arbitrarily long list of unique marker styles for points.
1,685
1,728
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]
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1685-L1728
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43 ]
100
[]
0
true
97.668038
44
2
100
12
def unique_markers(n): # 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]
19,063
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
categorical_order
(vector, order=None)
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.
Return a list of unique data values.
1,731
1,767
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): try: order = vector.unique() except AttributeError: order = pd.unique(vector) if variable_type(vector) == "numeric": order = np.sort(order) order = filter(pd.notnull, order) return list(order)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1731-L1767
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36 ]
100
[]
0
true
97.668038
37
6
100
16
def categorical_order(vector, order=None): if order is None: if hasattr(vector, "categories"): order = vector.categories else: try: order = vector.cat.categories except (TypeError, AttributeError): try: order = vector.unique() except AttributeError: order = pd.unique(vector) if variable_type(vector) == "numeric": order = np.sort(order) order = filter(pd.notnull, order) return list(order)
19,064
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
SemanticMapping.__init__
(self, plotter)
42
49
def __init__(self, plotter): # TODO Putting this here so we can continue to use a lot of the # logic that's built into the library, but the idea of this class # is to move towards semantic mappings that are agnostic about the # kind of plot they're going to be used to draw. # Fully achieving that is going to take some thinking. self.plotter = plotter
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L42-L49
26
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
97.668038
8
1
100
0
def __init__(self, plotter): # TODO Putting this here so we can continue to use a lot of the # logic that's built into the library, but the idea of this class # is to move towards semantic mappings that are agnostic about the # kind of plot they're going to be used to draw. # Fully achieving that is going to take some thinking. self.plotter = plotter
19,065
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
SemanticMapping.map
(cls, plotter, *args, **kwargs)
return plotter
51
55
def map(cls, plotter, *args, **kwargs): # This method is assigned the __init__ docstring method_name = f"_{cls.__name__[:-7].lower()}_map" setattr(plotter, method_name, cls(plotter, *args, **kwargs)) return plotter
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L51-L55
26
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
97.668038
5
1
100
0
def map(cls, plotter, *args, **kwargs): # This method is assigned the __init__ docstring method_name = f"_{cls.__name__[:-7].lower()}_map" setattr(plotter, method_name, cls(plotter, *args, **kwargs)) return plotter
19,066
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
SemanticMapping._check_list_length
(self, levels, values, variable)
return values
Input check when values are provided as a list.
Input check when values are provided as a list.
57
79
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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L57-L79
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
100
[]
0
true
97.668038
23
5
100
1
def _check_list_length(self, levels, values, variable): # 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
19,067
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
SemanticMapping._lookup_single
(self, key)
return self.lookup_table[key]
Apply the mapping to a single data value.
Apply the mapping to a single data value.
81
83
def _lookup_single(self, key): """Apply the mapping to a single data value.""" return self.lookup_table[key]
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L81-L83
26
[ 0, 1, 2 ]
100
[]
0
true
97.668038
3
1
100
1
def _lookup_single(self, key): return self.lookup_table[key]
19,068
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
SemanticMapping.__call__
(self, key, *args, **kwargs)
Get the attribute(s) values for the data key.
Get the attribute(s) values for the data key.
85
90
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)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L85-L90
26
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
97.668038
6
3
100
1
def __call__(self, key, *args, **kwargs): 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)
19,069
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter.__init__
(self, data=None, variables={})
631
648
def __init__(self, data=None, variables={}): self._var_levels = {} # var_ordered is relevant only for categorical axis variables, and may # be better handled by an internal axis information object that tracks # such information and is set up by the scale_* methods. The analogous # information for numeric axes would be information about log scales. self._var_ordered = {"x": False, "y": False} # alt., used DefaultDict self.assign_variables(data, variables) for var, cls in self._semantic_mappings.items(): # Create the mapping function map_func = partial(cls.map, plotter=self) setattr(self, f"map_{var}", map_func) # Call the mapping function to initialize with default values getattr(self, f"map_{var}")()
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L631-L648
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
100
[]
0
true
97.668038
18
2
100
0
def __init__(self, data=None, variables={}): self._var_levels = {} # var_ordered is relevant only for categorical axis variables, and may # be better handled by an internal axis information object that tracks # such information and is set up by the scale_* methods. The analogous # information for numeric axes would be information about log scales. self._var_ordered = {"x": False, "y": False} # alt., used DefaultDict self.assign_variables(data, variables) for var, cls in self._semantic_mappings.items(): # Create the mapping function map_func = partial(cls.map, plotter=self) setattr(self, f"map_{var}", map_func) # Call the mapping function to initialize with default values getattr(self, f"map_{var}")()
19,070
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter.get_semantics
(cls, kwargs, semantics=None)
return variables
Subset a dictionary arguments with known semantic variables.
Subset a dictionary arguments with known semantic variables.
651
660
def get_semantics(cls, kwargs, semantics=None): """Subset a dictionary arguments with known semantic variables.""" # TODO this should be get_variables since we have included x and y if semantics is None: semantics = cls.semantics variables = {} for key, val in kwargs.items(): if key in semantics and val is not None: variables[key] = val return variables
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L651-L660
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
97.668038
10
5
100
1
def get_semantics(cls, kwargs, semantics=None): # TODO this should be get_variables since we have included x and y if semantics is None: semantics = cls.semantics variables = {} for key, val in kwargs.items(): if key in semantics and val is not None: variables[key] = val return variables
19,071
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter.has_xy_data
(self)
return bool({"x", "y"} & set(self.variables))
Return True at least one of x or y is defined.
Return True at least one of x or y is defined.
663
665
def has_xy_data(self): """Return True at least one of x or y is defined.""" return bool({"x", "y"} & set(self.variables))
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L663-L665
26
[ 0, 1, 2 ]
100
[]
0
true
97.668038
3
1
100
1
def has_xy_data(self): return bool({"x", "y"} & set(self.variables))
19,072
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter.var_levels
(self)
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.
Property interface to ordered list of variables levels.
668
686
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: try: map_obj = getattr(self, f"_{var}_map") self._var_levels[var] = map_obj.levels except AttributeError: pass return self._var_levels
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L668-L686
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
100
[]
0
true
97.668038
19
3
100
9
def var_levels(self): for var in self.variables: try: map_obj = getattr(self, f"_{var}_map") self._var_levels[var] = map_obj.levels except AttributeError: pass return self._var_levels
19,073
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter.assign_variables
(self, data=None, variables={})
return self
Define plot variables, optionally using lookup from `data`.
Define plot variables, optionally using lookup from `data`.
688
714
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" plot_data, variables = self._assign_variables_wideform( data, **variables, ) else: self.input_format = "long" plot_data, variables = self._assign_variables_longform( data, **variables, ) self.plot_data = plot_data self.variables = variables self.var_types = { v: variable_type( plot_data[v], boolean_type="numeric" if v in "xy" else "categorical" ) for v in variables } return self
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L688-L714
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 ]
100
[]
0
true
97.668038
27
3
100
1
def assign_variables(self, data=None, variables={}): x = variables.get("x", None) y = variables.get("y", None) if x is None and y is None: self.input_format = "wide" plot_data, variables = self._assign_variables_wideform( data, **variables, ) else: self.input_format = "long" plot_data, variables = self._assign_variables_longform( data, **variables, ) self.plot_data = plot_data self.variables = variables self.var_types = { v: variable_type( plot_data[v], boolean_type="numeric" if v in "xy" else "categorical" ) for v in variables } return self
19,074
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter._assign_variables_wideform
(self, data=None, **kwargs)
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).
Define plot variables given wide-form data.
716
856
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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L716-L856
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140 ]
100
[]
0
true
97.668038
141
20
100
19
def _assign_variables_wideform(self, data=None, **kwargs): # 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
19,075
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter._assign_variables_longform
(self, data=None, **kwargs)
return plot_data, variables
Define plot variables given long-form data and/or vector inputs. Parameters ---------- data : dict-like collection of vectors Input data where variable names map to vector values. kwargs : variable -> data mappings Keys are seaborn variables (x, y, hue, ...) and values are vectors in any format that can construct a :class:`pandas.DataFrame` or names of columns or index levels in ``data``. 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). Raises ------ ValueError When variables are strings that don't appear in ``data``.
Define plot variables given long-form data and/or vector inputs.
858
970
def _assign_variables_longform(self, data=None, **kwargs): """Define plot variables given long-form data and/or vector inputs. Parameters ---------- data : dict-like collection of vectors Input data where variable names map to vector values. kwargs : variable -> data mappings Keys are seaborn variables (x, y, hue, ...) and values are vectors in any format that can construct a :class:`pandas.DataFrame` or names of columns or index levels in ``data``. 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). Raises ------ ValueError When variables are strings that don't appear in ``data``. """ plot_data = {} variables = {} # Data is optional; all variables can be defined as vectors if data is None: data = {} # TODO should we try a data.to_dict() or similar here to more # generally accept objects with that interface? # Note that dict(df) also works for pandas, and gives us what we # want, whereas DataFrame.to_dict() gives a nested dict instead of # a dict of series. # Variables can also be extracted from the index attribute # TODO is this the most general way to enable it? # There is no index.to_dict on multiindex, unfortunately try: index = data.index.to_frame() except AttributeError: index = {} # The caller will determine the order of variables in plot_data for key, val in kwargs.items(): # First try to treat the argument as a key for the data collection. # But be flexible about what can be used as a key. # Usually it will be a string, but allow numbers or tuples too when # taking from the main data object. Only allow strings to reference # fields in the index, because otherwise there is too much ambiguity. try: val_as_data_key = ( val in data or (isinstance(val, (str, bytes)) and val in index) ) except (KeyError, TypeError): val_as_data_key = False if val_as_data_key: # We know that __getitem__ will work if val in data: plot_data[key] = data[val] elif val in index: plot_data[key] = index[val] variables[key] = val elif isinstance(val, (str, bytes)): # This looks like a column name but we don't know what it means! err = f"Could not interpret value `{val}` for parameter `{key}`" raise ValueError(err) else: # Otherwise, assume the value is itself data # Raise when data object is present and a vector can't matched if isinstance(data, pd.DataFrame) and not isinstance(val, pd.Series): if np.ndim(val) and len(data) != len(val): val_cls = val.__class__.__name__ err = ( f"Length of {val_cls} vectors must match length of `data`" f" when both are used, but `data` has length {len(data)}" f" and the vector passed to `{key}` has length {len(val)}." ) raise ValueError(err) plot_data[key] = val # Try to infer the name of the variable variables[key] = getattr(val, "name", None) # Construct a tidy plot DataFrame. This will convert a number of # types automatically, aligning on index in case of pandas objects plot_data = pd.DataFrame(plot_data) # Reduce the variables dictionary to fields with valid data variables = { var: name for var, name in variables.items() if plot_data[var].notnull().any() } return plot_data, variables
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L858-L970
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112 ]
100
[]
0
true
97.668038
113
15
100
24
def _assign_variables_longform(self, data=None, **kwargs): plot_data = {} variables = {} # Data is optional; all variables can be defined as vectors if data is None: data = {} # TODO should we try a data.to_dict() or similar here to more # generally accept objects with that interface? # Note that dict(df) also works for pandas, and gives us what we # want, whereas DataFrame.to_dict() gives a nested dict instead of # a dict of series. # Variables can also be extracted from the index attribute # TODO is this the most general way to enable it? # There is no index.to_dict on multiindex, unfortunately try: index = data.index.to_frame() except AttributeError: index = {} # The caller will determine the order of variables in plot_data for key, val in kwargs.items(): # First try to treat the argument as a key for the data collection. # But be flexible about what can be used as a key. # Usually it will be a string, but allow numbers or tuples too when # taking from the main data object. Only allow strings to reference # fields in the index, because otherwise there is too much ambiguity. try: val_as_data_key = ( val in data or (isinstance(val, (str, bytes)) and val in index) ) except (KeyError, TypeError): val_as_data_key = False if val_as_data_key: # We know that __getitem__ will work if val in data: plot_data[key] = data[val] elif val in index: plot_data[key] = index[val] variables[key] = val elif isinstance(val, (str, bytes)): # This looks like a column name but we don't know what it means! err = f"Could not interpret value `{val}` for parameter `{key}`" raise ValueError(err) else: # Otherwise, assume the value is itself data # Raise when data object is present and a vector can't matched if isinstance(data, pd.DataFrame) and not isinstance(val, pd.Series): if np.ndim(val) and len(data) != len(val): val_cls = val.__class__.__name__ err = ( f"Length of {val_cls} vectors must match length of `data`" f" when both are used, but `data` has length {len(data)}" f" and the vector passed to `{key}` has length {len(val)}." ) raise ValueError(err) plot_data[key] = val # Try to infer the name of the variable variables[key] = getattr(val, "name", None) # Construct a tidy plot DataFrame. This will convert a number of # types automatically, aligning on index in case of pandas objects plot_data = pd.DataFrame(plot_data) # Reduce the variables dictionary to fields with valid data variables = { var: name for var, name in variables.items() if plot_data[var].notnull().any() } return plot_data, variables
19,076
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter.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.
Generator for getting subsets of data defined by semantic variables.
972
1,091
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): 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. converter = self.converters[axis].iloc[0] 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()) elif self.var_types[axis] == "datetime": levels[axis] = mpl.dates.date2num(levels[axis]) elif self.var_types[axis] == "numeric" and self._log_scaled(axis): levels[axis] = np.log10(levels[axis]) if grouping_vars: grouped_data = data.groupby( grouping_vars, sort=False, as_index=False ) grouping_keys = [] for var in grouping_vars: grouping_keys.append(levels.get(var, [])) iter_keys = itertools.product(*grouping_keys) if reverse: iter_keys = reversed(list(iter_keys)) for key in iter_keys: # Pandas fails with singleton tuple inputs pd_key = key[0] if len(key) == 1 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()
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L972-L1091
26
[ 0, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 49, 50, 53, 54, 55, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 118, 119 ]
63.333333
[]
0
false
97.668038
120
22
100
26
def iter_data( self, grouping_vars=None, *, reverse=False, from_comp_data=False, by_facet=True, allow_empty=False, dropna=True, ): # 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): 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. converter = self.converters[axis].iloc[0] 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()) elif self.var_types[axis] == "datetime": levels[axis] = mpl.dates.date2num(levels[axis]) elif self.var_types[axis] == "numeric" and self._log_scaled(axis): levels[axis] = np.log10(levels[axis]) if grouping_vars: grouped_data = data.groupby( grouping_vars, sort=False, as_index=False ) grouping_keys = [] for var in grouping_vars: grouping_keys.append(levels.get(var, [])) iter_keys = itertools.product(*grouping_keys) if reverse: iter_keys = reversed(list(iter_keys)) for key in iter_keys: # Pandas fails with singleton tuple inputs pd_key = key[0] if len(key) == 1 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()
19,077
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter.comp_data
(self)
return self._comp_data
Dataframe with numeric x and y, after unit conversion and log scaling.
Dataframe with numeric x and y, after unit conversion and log scaling.
1,094
1,137
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: with pd.option_context('mode.use_inf_as_na', True): 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)) if converter.get_scale() == "log": comp = np.log10(comp) parts.append(pd.Series(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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1094-L1137
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43 ]
100
[]
0
true
97.668038
44
10
100
1
def comp_data(self): 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: with pd.option_context('mode.use_inf_as_na', True): 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)) if converter.get_scale() == "log": comp = np.log10(comp) parts.append(pd.Series(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
19,078
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter._get_axes
(self, sub_vars)
Return an Axes object based on existence of row/col variables.
Return an Axes object based on existence of row/col variables.
1,139
1,152
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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1139-L1152
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
97.668038
14
6
100
1
def _get_axes(self, sub_vars): 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
19,079
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter._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.
Associate the plotter with an Axes manager and initialize its units.
1,154
1,293
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 "x" in self.variables else False scaley = log_scale if "y" in self.variables 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") else: set_scale("log", base=scale) # 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: try: ax.yaxis.set_inverted(True) except AttributeError: # mpl < 3.1 if not ax.yaxis_inverted(): ax.invert_yaxis()
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1154-L1293
26
[ 0, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136 ]
84.285714
[ 137, 138, 139 ]
2.142857
false
97.668038
140
27
97.857143
13
def _attach( self, obj, allowed_types=None, log_scale=None, ): 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 "x" in self.variables else False scaley = log_scale if "y" in self.variables 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") else: set_scale("log", base=scale) # 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: try: ax.yaxis.set_inverted(True) except AttributeError: # mpl < 3.1 if not ax.yaxis_inverted(): ax.invert_yaxis()
19,080
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter._log_scaled
(self, axis)
return any(log_scaled)
Return True if specified axis is log scaled on all attached axes.
Return True if specified axis is log scaled on all attached axes.
1,297
1,315
def _log_scaled(self, axis): """Return True if specified axis is log scaled on all attached axes.""" if not hasattr(self, "ax"): return False if self.ax is None: axes_list = self.facets.axes.flatten() else: axes_list = [self.ax] log_scaled = [] for ax in axes_list: data_axis = getattr(ax, f"{axis}axis") log_scaled.append(data_axis.get_scale() == "log") if any(log_scaled) and not all(log_scaled): raise RuntimeError("Axis scaling is not consistent") return any(log_scaled)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1297-L1315
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18 ]
94.736842
[ 16 ]
5.263158
false
97.668038
19
6
94.736842
1
def _log_scaled(self, axis): if not hasattr(self, "ax"): return False if self.ax is None: axes_list = self.facets.axes.flatten() else: axes_list = [self.ax] log_scaled = [] for ax in axes_list: data_axis = getattr(ax, f"{axis}axis") log_scaled.append(data_axis.get_scale() == "log") if any(log_scaled) and not all(log_scaled): raise RuntimeError("Axis scaling is not consistent") return any(log_scaled)
19,081
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter._add_axis_labels
(self, ax, default_x="", default_y="")
Add axis labels if not present, set visibility to match ticklabels.
Add axis labels if not present, set visibility to match ticklabels.
1,317
1,328
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)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1317-L1328
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
97.668038
12
3
100
1
def _add_axis_labels(self, ax, default_x="", default_y=""): # 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)
19,082
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter.scale_native
(self, axis, *args, **kwargs)
1,335
1,339
def scale_native(self, axis, *args, **kwargs): # Default, defer to matplotlib raise NotImplementedError
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1335-L1339
26
[ 0, 1, 2, 3 ]
100
[]
0
true
97.668038
5
1
100
0
def scale_native(self, axis, *args, **kwargs): # Default, defer to matplotlib raise NotImplementedError
19,083
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter.scale_numeric
(self, axis, *args, **kwargs)
1,341
1,346
def scale_numeric(self, axis, *args, **kwargs): # Feels needed to completeness, what should it do? # Perhaps handle log scaling? Set the ticker/formatter/limits? raise NotImplementedError
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1341-L1346
26
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
97.668038
6
1
100
0
def scale_numeric(self, axis, *args, **kwargs): # Feels needed to completeness, what should it do? # Perhaps handle log scaling? Set the ticker/formatter/limits? raise NotImplementedError
19,084
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter.scale_datetime
(self, axis, *args, **kwargs)
1,348
1,353
def scale_datetime(self, axis, *args, **kwargs): # Use pd.to_datetime to convert strings or numbers to datetime objects # Note, use day-resolution for numeric->datetime to match matplotlib raise NotImplementedError
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1348-L1353
26
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
97.668038
6
1
100
0
def scale_datetime(self, axis, *args, **kwargs): # Use pd.to_datetime to convert strings or numbers to datetime objects # Note, use day-resolution for numeric->datetime to match matplotlib raise NotImplementedError
19,085
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VectorPlotter.scale_categorical
(self, axis, order=None, formatter=None)
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
Enforce categorical (fixed-scale) rules for the data on given axis.
1,355
1,446
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 cat_data = self.plot_data[axis] # 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)) # 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
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1355-L1446
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91 ]
100
[]
0
true
97.668038
92
5
100
14
def scale_categorical(self, axis, order=None, formatter=None): # 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 cat_data = self.plot_data[axis] # 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)) # 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
19,086
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VariableType.__init__
(self, data)
1,460
1,462
def __init__(self, data): assert data in self.allowed, data super().__init__(data)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1460-L1462
26
[ 0, 1, 2 ]
100
[]
0
true
97.668038
3
2
100
0
def __init__(self, data): assert data in self.allowed, data super().__init__(data)
19,087
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_oldcore.py
VariableType.__eq__
(self, other)
return self.data == other
1,464
1,466
def __eq__(self, other): assert other in self.allowed, other return self.data == other
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_oldcore.py#L1464-L1466
26
[ 0, 1, 2 ]
100
[]
0
true
97.668038
3
2
100
0
def __eq__(self, other): assert other in self.allowed, other return self.data == other
19,088
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_decorators.py
share_init_params_with_map
(cls)
return cls
Make cls.map a classmethod with same signature as cls.__init__.
Make cls.map a classmethod with same signature as cls.__init__.
4
16
def share_init_params_with_map(cls): """Make cls.map a classmethod with same signature as cls.__init__.""" map_sig = signature(cls.map) init_sig = signature(cls.__init__) new = [v for k, v in init_sig.parameters.items() if k != "self"] new.insert(0, map_sig.parameters["cls"]) cls.map.__signature__ = map_sig.replace(parameters=new) cls.map.__doc__ = cls.__init__.__doc__ cls.map = classmethod(cls.map) return cls
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_decorators.py#L4-L16
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
100
13
2
100
1
def share_init_params_with_map(cls): map_sig = signature(cls.map) init_sig = signature(cls.__init__) new = [v for k, v in init_sig.parameters.items() if k != "self"] new.insert(0, map_sig.parameters["cls"]) cls.map.__signature__ = map_sig.replace(parameters=new) cls.map.__doc__ = cls.__init__.__doc__ cls.map = classmethod(cls.map) return cls
19,089
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/palettes.py
_patch_colormap_display
()
Simplify the rich display of matplotlib color maps in a notebook.
Simplify the rich display of matplotlib color maps in a notebook.
94
119
def _patch_colormap_display(): """Simplify the rich display of matplotlib color maps in a notebook.""" def _repr_png_(self): """Generate a PNG representation of the Colormap.""" import io from PIL import Image import numpy as np IMAGE_SIZE = (400, 50) X = np.tile(np.linspace(0, 1, IMAGE_SIZE[0]), (IMAGE_SIZE[1], 1)) pixels = self(X, bytes=True) png_bytes = io.BytesIO() Image.fromarray(pixels).save(png_bytes, format='png') return png_bytes.getvalue() def _repr_html_(self): """Generate an HTML representation of the Colormap.""" import base64 png_bytes = self._repr_png_() png_base64 = base64.b64encode(png_bytes).decode('ascii') return ('<img ' + 'alt="' + self.name + ' color map" ' + 'title="' + self.name + '"' + 'src="data:image/png;base64,' + png_base64 + '">') mpl.colors.Colormap._repr_png_ = _repr_png_ mpl.colors.Colormap._repr_html_ = _repr_html_
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/palettes.py#L94-L119
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 ]
100
[]
0
true
99.6
26
3
100
1
def _patch_colormap_display(): def _repr_png_(self): import io from PIL import Image import numpy as np IMAGE_SIZE = (400, 50) X = np.tile(np.linspace(0, 1, IMAGE_SIZE[0]), (IMAGE_SIZE[1], 1)) pixels = self(X, bytes=True) png_bytes = io.BytesIO() Image.fromarray(pixels).save(png_bytes, format='png') return png_bytes.getvalue() def _repr_html_(self): import base64 png_bytes = self._repr_png_() png_base64 = base64.b64encode(png_bytes).decode('ascii') return ('<img ' + 'alt="' + self.name + ' color map" ' + 'title="' + self.name + '"' + 'src="data:image/png;base64,' + png_base64 + '">') mpl.colors.Colormap._repr_png_ = _repr_png_ mpl.colors.Colormap._repr_html_ = _repr_html_
19,090
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/palettes.py
color_palette
(palette=None, n_colors=None, desat=None, as_cmap=False)
return palette
Return a list of colors or continuous colormap defining a palette. Possible ``palette`` values include: - Name of a seaborn palette (deep, muted, bright, pastel, dark, colorblind) - Name of matplotlib colormap - 'husl' or 'hls' - 'ch:<cubehelix arguments>' - 'light:<color>', 'dark:<color>', 'blend:<color>,<color>', - A sequence of colors in any format matplotlib accepts Calling this function with ``palette=None`` will return the current matplotlib color cycle. This function can also be used in a ``with`` statement to temporarily set the color cycle for a plot or set of plots. See the :ref:`tutorial <palette_tutorial>` for more information. Parameters ---------- palette : None, string, or sequence, optional Name of palette or None to return current palette. If a sequence, input colors are used but possibly cycled and desaturated. n_colors : int, optional Number of colors in the palette. If ``None``, the default will depend on how ``palette`` is specified. Named palettes default to 6 colors, but grabbing the current palette or passing in a list of colors will not change the number of colors unless this is specified. Asking for more colors than exist in the palette will cause it to cycle. Ignored when ``as_cmap`` is True. desat : float, optional Proportion to desaturate each color by. as_cmap : bool If True, return a :class:`matplotlib.colors.ListedColormap`. Returns ------- list of RGB tuples or :class:`matplotlib.colors.ListedColormap` See Also -------- set_palette : Set the default color cycle for all plots. set_color_codes : Reassign color codes like ``"b"``, ``"g"``, etc. to colors from one of the seaborn palettes. Examples -------- .. include:: ../docstrings/color_palette.rst
Return a list of colors or continuous colormap defining a palette.
122
255
def color_palette(palette=None, n_colors=None, desat=None, as_cmap=False): """Return a list of colors or continuous colormap defining a palette. Possible ``palette`` values include: - Name of a seaborn palette (deep, muted, bright, pastel, dark, colorblind) - Name of matplotlib colormap - 'husl' or 'hls' - 'ch:<cubehelix arguments>' - 'light:<color>', 'dark:<color>', 'blend:<color>,<color>', - A sequence of colors in any format matplotlib accepts Calling this function with ``palette=None`` will return the current matplotlib color cycle. This function can also be used in a ``with`` statement to temporarily set the color cycle for a plot or set of plots. See the :ref:`tutorial <palette_tutorial>` for more information. Parameters ---------- palette : None, string, or sequence, optional Name of palette or None to return current palette. If a sequence, input colors are used but possibly cycled and desaturated. n_colors : int, optional Number of colors in the palette. If ``None``, the default will depend on how ``palette`` is specified. Named palettes default to 6 colors, but grabbing the current palette or passing in a list of colors will not change the number of colors unless this is specified. Asking for more colors than exist in the palette will cause it to cycle. Ignored when ``as_cmap`` is True. desat : float, optional Proportion to desaturate each color by. as_cmap : bool If True, return a :class:`matplotlib.colors.ListedColormap`. Returns ------- list of RGB tuples or :class:`matplotlib.colors.ListedColormap` See Also -------- set_palette : Set the default color cycle for all plots. set_color_codes : Reassign color codes like ``"b"``, ``"g"``, etc. to colors from one of the seaborn palettes. Examples -------- .. include:: ../docstrings/color_palette.rst """ if palette is None: palette = get_color_cycle() if n_colors is None: n_colors = len(palette) elif not isinstance(palette, str): palette = palette if n_colors is None: n_colors = len(palette) else: if n_colors is None: # Use all colors in a qualitative palette or 6 of another kind n_colors = QUAL_PALETTE_SIZES.get(palette, 6) if palette in SEABORN_PALETTES: # Named "seaborn variant" of matplotlib default color cycle palette = SEABORN_PALETTES[palette] elif palette == "hls": # Evenly spaced colors in cylindrical RGB space palette = hls_palette(n_colors, as_cmap=as_cmap) elif palette == "husl": # Evenly spaced colors in cylindrical Lab space palette = husl_palette(n_colors, as_cmap=as_cmap) elif palette.lower() == "jet": # Paternalism raise ValueError("No.") elif palette.startswith("ch:"): # Cubehelix palette with params specified in string args, kwargs = _parse_cubehelix_args(palette) palette = cubehelix_palette(n_colors, *args, **kwargs, as_cmap=as_cmap) elif palette.startswith("light:"): # light palette to color specified in string _, color = palette.split(":") reverse = color.endswith("_r") if reverse: color = color[:-2] palette = light_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap) elif palette.startswith("dark:"): # light palette to color specified in string _, color = palette.split(":") reverse = color.endswith("_r") if reverse: color = color[:-2] palette = dark_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap) elif palette.startswith("blend:"): # blend palette between colors specified in string _, colors = palette.split(":") colors = colors.split(",") palette = blend_palette(colors, n_colors, as_cmap=as_cmap) else: try: # Perhaps a named matplotlib colormap? palette = mpl_palette(palette, n_colors, as_cmap=as_cmap) except (ValueError, KeyError): # Error class changed in mpl36 raise ValueError(f"{palette!r} is not a valid palette name") if desat is not None: palette = [desaturate(c, desat) for c in palette] if not as_cmap: # Always return as many colors as we asked for pal_cycle = cycle(palette) palette = [next(pal_cycle) for _ in range(n_colors)] # Always return in r, g, b tuple format try: palette = map(mpl.colors.colorConverter.to_rgb, palette) palette = _ColorPalette(palette) except ValueError: raise ValueError(f"Could not generate a palette for {palette}") return palette
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/palettes.py#L122-L255
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133 ]
100
[]
0
true
99.6
134
22
100
49
def color_palette(palette=None, n_colors=None, desat=None, as_cmap=False): if palette is None: palette = get_color_cycle() if n_colors is None: n_colors = len(palette) elif not isinstance(palette, str): palette = palette if n_colors is None: n_colors = len(palette) else: if n_colors is None: # Use all colors in a qualitative palette or 6 of another kind n_colors = QUAL_PALETTE_SIZES.get(palette, 6) if palette in SEABORN_PALETTES: # Named "seaborn variant" of matplotlib default color cycle palette = SEABORN_PALETTES[palette] elif palette == "hls": # Evenly spaced colors in cylindrical RGB space palette = hls_palette(n_colors, as_cmap=as_cmap) elif palette == "husl": # Evenly spaced colors in cylindrical Lab space palette = husl_palette(n_colors, as_cmap=as_cmap) elif palette.lower() == "jet": # Paternalism raise ValueError("No.") elif palette.startswith("ch:"): # Cubehelix palette with params specified in string args, kwargs = _parse_cubehelix_args(palette) palette = cubehelix_palette(n_colors, *args, **kwargs, as_cmap=as_cmap) elif palette.startswith("light:"): # light palette to color specified in string _, color = palette.split(":") reverse = color.endswith("_r") if reverse: color = color[:-2] palette = light_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap) elif palette.startswith("dark:"): # light palette to color specified in string _, color = palette.split(":") reverse = color.endswith("_r") if reverse: color = color[:-2] palette = dark_palette(color, n_colors, reverse=reverse, as_cmap=as_cmap) elif palette.startswith("blend:"): # blend palette between colors specified in string _, colors = palette.split(":") colors = colors.split(",") palette = blend_palette(colors, n_colors, as_cmap=as_cmap) else: try: # Perhaps a named matplotlib colormap? palette = mpl_palette(palette, n_colors, as_cmap=as_cmap) except (ValueError, KeyError): # Error class changed in mpl36 raise ValueError(f"{palette!r} is not a valid palette name") if desat is not None: palette = [desaturate(c, desat) for c in palette] if not as_cmap: # Always return as many colors as we asked for pal_cycle = cycle(palette) palette = [next(pal_cycle) for _ in range(n_colors)] # Always return in r, g, b tuple format try: palette = map(mpl.colors.colorConverter.to_rgb, palette) palette = _ColorPalette(palette) except ValueError: raise ValueError(f"Could not generate a palette for {palette}") return palette
19,091
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/palettes.py
hls_palette
(n_colors=6, h=.01, l=.6, s=.65, as_cmap=False)
Return hues with constant lightness and saturation in the HLS system. The hues are evenly sampled along a circular path. The resulting palette will be appropriate for categorical or cyclical data. The `h`, `l`, and `s` values should be between 0 and 1. .. note:: While the separation of the resulting colors will be mathematically constant, the HLS system does not construct a perceptually-uniform space, so their apparent intensity will vary. Parameters ---------- n_colors : int Number of colors in the palette. h : float The value of the first hue. l : float The lightness value. s : float The saturation intensity. as_cmap : bool If True, return a matplotlib colormap object. Returns ------- palette list of RGB tuples or :class:`matplotlib.colors.ListedColormap` See Also -------- husl_palette : Make a palette using evenly spaced hues in the HUSL system. Examples -------- .. include:: ../docstrings/hls_palette.rst
Return hues with constant lightness and saturation in the HLS system.
258
309
def hls_palette(n_colors=6, h=.01, l=.6, s=.65, as_cmap=False): # noqa """ Return hues with constant lightness and saturation in the HLS system. The hues are evenly sampled along a circular path. The resulting palette will be appropriate for categorical or cyclical data. The `h`, `l`, and `s` values should be between 0 and 1. .. note:: While the separation of the resulting colors will be mathematically constant, the HLS system does not construct a perceptually-uniform space, so their apparent intensity will vary. Parameters ---------- n_colors : int Number of colors in the palette. h : float The value of the first hue. l : float The lightness value. s : float The saturation intensity. as_cmap : bool If True, return a matplotlib colormap object. Returns ------- palette list of RGB tuples or :class:`matplotlib.colors.ListedColormap` See Also -------- husl_palette : Make a palette using evenly spaced hues in the HUSL system. Examples -------- .. include:: ../docstrings/hls_palette.rst """ if as_cmap: n_colors = 256 hues = np.linspace(0, 1, int(n_colors) + 1)[:-1] hues += h hues %= 1 hues -= hues.astype(int) palette = [colorsys.hls_to_rgb(h_i, l, s) for h_i in hues] if as_cmap: return mpl.colors.ListedColormap(palette, "hls") else: return _ColorPalette(palette)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/palettes.py#L258-L309
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 ]
100
[]
0
true
99.6
52
4
100
37
def hls_palette(n_colors=6, h=.01, l=.6, s=.65, as_cmap=False): # noqa if as_cmap: n_colors = 256 hues = np.linspace(0, 1, int(n_colors) + 1)[:-1] hues += h hues %= 1 hues -= hues.astype(int) palette = [colorsys.hls_to_rgb(h_i, l, s) for h_i in hues] if as_cmap: return mpl.colors.ListedColormap(palette, "hls") else: return _ColorPalette(palette)
19,092
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/palettes.py
husl_palette
(n_colors=6, h=.01, s=.9, l=.65, as_cmap=False)
Return hues with constant lightness and saturation in the HUSL system. The hues are evenly sampled along a circular path. The resulting palette will be appropriate for categorical or cyclical data. The `h`, `l`, and `s` values should be between 0 and 1. This function is similar to :func:`hls_palette`, but it uses a nonlinear color space that is more perceptually uniform. Parameters ---------- n_colors : int Number of colors in the palette. h : float The value of the first hue. l : float The lightness value. s : float The saturation intensity. as_cmap : bool If True, return a matplotlib colormap object. Returns ------- palette list of RGB tuples or :class:`matplotlib.colors.ListedColormap` See Also -------- hls_palette : Make a palette using evenly spaced hues in the HSL system. Examples -------- .. include:: ../docstrings/husl_palette.rst
Return hues with constant lightness and saturation in the HUSL system.
312
363
def husl_palette(n_colors=6, h=.01, s=.9, l=.65, as_cmap=False): # noqa """ Return hues with constant lightness and saturation in the HUSL system. The hues are evenly sampled along a circular path. The resulting palette will be appropriate for categorical or cyclical data. The `h`, `l`, and `s` values should be between 0 and 1. This function is similar to :func:`hls_palette`, but it uses a nonlinear color space that is more perceptually uniform. Parameters ---------- n_colors : int Number of colors in the palette. h : float The value of the first hue. l : float The lightness value. s : float The saturation intensity. as_cmap : bool If True, return a matplotlib colormap object. Returns ------- palette list of RGB tuples or :class:`matplotlib.colors.ListedColormap` See Also -------- hls_palette : Make a palette using evenly spaced hues in the HSL system. Examples -------- .. include:: ../docstrings/husl_palette.rst """ if as_cmap: n_colors = 256 hues = np.linspace(0, 1, int(n_colors) + 1)[:-1] hues += h hues %= 1 hues *= 359 s *= 99 l *= 99 # noqa palette = [_color_to_rgb((h_i, s, l), input="husl") for h_i in hues] if as_cmap: return mpl.colors.ListedColormap(palette, "hsl") else: return _ColorPalette(palette)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/palettes.py#L312-L363
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 ]
100
[]
0
true
99.6
52
4
100
35
def husl_palette(n_colors=6, h=.01, s=.9, l=.65, as_cmap=False): # noqa if as_cmap: n_colors = 256 hues = np.linspace(0, 1, int(n_colors) + 1)[:-1] hues += h hues %= 1 hues *= 359 s *= 99 l *= 99 # noqa palette = [_color_to_rgb((h_i, s, l), input="husl") for h_i in hues] if as_cmap: return mpl.colors.ListedColormap(palette, "hsl") else: return _ColorPalette(palette)
19,093
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/palettes.py
mpl_palette
(name, n_colors=6, as_cmap=False)
Return a palette or colormap from the matplotlib registry. For continuous palettes, evenly-spaced discrete samples are chosen while excluding the minimum and maximum value in the colormap to provide better contrast at the extremes. For qualitative palettes (e.g. those from colorbrewer), exact values are indexed (rather than interpolated), but fewer than `n_colors` can be returned if the palette does not define that many. Parameters ---------- name : string Name of the palette. This should be a named matplotlib colormap. n_colors : int Number of discrete colors in the palette. Returns ------- list of RGB tuples or :class:`matplotlib.colors.ListedColormap` Examples -------- .. include: ../docstrings/mpl_palette.rst
Return a palette or colormap from the matplotlib registry.
366
417
def mpl_palette(name, n_colors=6, as_cmap=False): """ Return a palette or colormap from the matplotlib registry. For continuous palettes, evenly-spaced discrete samples are chosen while excluding the minimum and maximum value in the colormap to provide better contrast at the extremes. For qualitative palettes (e.g. those from colorbrewer), exact values are indexed (rather than interpolated), but fewer than `n_colors` can be returned if the palette does not define that many. Parameters ---------- name : string Name of the palette. This should be a named matplotlib colormap. n_colors : int Number of discrete colors in the palette. Returns ------- list of RGB tuples or :class:`matplotlib.colors.ListedColormap` Examples -------- .. include: ../docstrings/mpl_palette.rst """ if name.endswith("_d"): sub_name = name[:-2] if sub_name.endswith("_r"): reverse = True sub_name = sub_name[:-2] else: reverse = False pal = color_palette(sub_name, 2) + ["#333333"] if reverse: pal = pal[::-1] cmap = blend_palette(pal, n_colors, as_cmap=True) else: cmap = get_colormap(name) if name in MPL_QUAL_PALS: bins = np.linspace(0, 1, MPL_QUAL_PALS[name])[:n_colors] else: bins = np.linspace(0, 1, int(n_colors) + 2)[1:-1] palette = list(map(tuple, cmap(bins)[:, :3])) if as_cmap: return cmap else: return _ColorPalette(palette)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/palettes.py#L366-L417
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 ]
100
[]
0
true
99.6
52
6
100
24
def mpl_palette(name, n_colors=6, as_cmap=False): if name.endswith("_d"): sub_name = name[:-2] if sub_name.endswith("_r"): reverse = True sub_name = sub_name[:-2] else: reverse = False pal = color_palette(sub_name, 2) + ["#333333"] if reverse: pal = pal[::-1] cmap = blend_palette(pal, n_colors, as_cmap=True) else: cmap = get_colormap(name) if name in MPL_QUAL_PALS: bins = np.linspace(0, 1, MPL_QUAL_PALS[name])[:n_colors] else: bins = np.linspace(0, 1, int(n_colors) + 2)[1:-1] palette = list(map(tuple, cmap(bins)[:, :3])) if as_cmap: return cmap else: return _ColorPalette(palette)
19,094