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/matrix.py
_DendrogramPlotter.calculated_linkage
(self)
return self._calculate_linkage_scipy()
552
562
def calculated_linkage(self): try: return self._calculate_linkage_fastcluster() except ImportError: if np.product(self.shape) >= 10000: msg = ("Clustering large matrix with scipy. Installing " "`fastcluster` may give better performance.") warnings.warn(msg) return self._calculate_linkage_scipy()
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L552-L562
26
[ 0, 1 ]
18.181818
[ 2, 3, 4, 5, 6, 8, 10 ]
63.636364
false
42.46824
11
3
36.363636
0
def calculated_linkage(self): try: return self._calculate_linkage_fastcluster() except ImportError: if np.product(self.shape) >= 10000: msg = ("Clustering large matrix with scipy. Installing " "`fastcluster` may give better performance.") warnings.warn(msg) return self._calculate_linkage_scipy()
19,195
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/matrix.py
_DendrogramPlotter.calculate_dendrogram
(self)
return hierarchy.dendrogram(self.linkage, no_plot=True, color_threshold=-np.inf)
Calculates a dendrogram based on the linkage matrix Made a separate function, not a property because don't want to recalculate the dendrogram every time it is accessed. Returns ------- dendrogram : dict Dendrogram dictionary as returned by scipy.cluster.hierarchy .dendrogram. The important key-value pairing is "reordered_ind" which indicates the re-ordering of the matrix
Calculates a dendrogram based on the linkage matrix
564
578
def calculate_dendrogram(self): """Calculates a dendrogram based on the linkage matrix Made a separate function, not a property because don't want to recalculate the dendrogram every time it is accessed. Returns ------- dendrogram : dict Dendrogram dictionary as returned by scipy.cluster.hierarchy .dendrogram. The important key-value pairing is "reordered_ind" which indicates the re-ordering of the matrix """ return hierarchy.dendrogram(self.linkage, no_plot=True, color_threshold=-np.inf)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L564-L578
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
86.666667
[ 13 ]
6.666667
false
42.46824
15
1
93.333333
11
def calculate_dendrogram(self): return hierarchy.dendrogram(self.linkage, no_plot=True, color_threshold=-np.inf)
19,196
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/matrix.py
_DendrogramPlotter.reordered_ind
(self)
return self.dendrogram['leaves']
Indices of the matrix, reordered by the dendrogram
Indices of the matrix, reordered by the dendrogram
581
583
def reordered_ind(self): """Indices of the matrix, reordered by the dendrogram""" return self.dendrogram['leaves']
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L581-L583
26
[ 0, 1 ]
66.666667
[ 2 ]
33.333333
false
42.46824
3
1
66.666667
1
def reordered_ind(self): return self.dendrogram['leaves']
19,197
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/matrix.py
_DendrogramPlotter.plot
(self, ax, tree_kws)
return self
Plots a dendrogram of the similarities between data on the axes Parameters ---------- ax : matplotlib.axes.Axes Axes object upon which the dendrogram is plotted
Plots a dendrogram of the similarities between data on the axes
585
639
def plot(self, ax, tree_kws): """Plots a dendrogram of the similarities between data on the axes Parameters ---------- ax : matplotlib.axes.Axes Axes object upon which the dendrogram is plotted """ tree_kws = {} if tree_kws is None else tree_kws.copy() tree_kws.setdefault("linewidths", .5) tree_kws.setdefault("colors", tree_kws.pop("color", (.2, .2, .2))) if self.rotate and self.axis == 0: coords = zip(self.dependent_coord, self.independent_coord) else: coords = zip(self.independent_coord, self.dependent_coord) lines = LineCollection([list(zip(x, y)) for x, y in coords], **tree_kws) ax.add_collection(lines) number_of_leaves = len(self.reordered_ind) max_dependent_coord = max(map(max, self.dependent_coord)) if self.rotate: ax.yaxis.set_ticks_position('right') # Constants 10 and 1.05 come from # `scipy.cluster.hierarchy._plot_dendrogram` ax.set_ylim(0, number_of_leaves * 10) ax.set_xlim(0, max_dependent_coord * 1.05) ax.invert_xaxis() ax.invert_yaxis() else: # Constants 10 and 1.05 come from # `scipy.cluster.hierarchy._plot_dendrogram` ax.set_xlim(0, number_of_leaves * 10) ax.set_ylim(0, max_dependent_coord * 1.05) despine(ax=ax, bottom=True, left=True) ax.set(xticks=self.xticks, yticks=self.yticks, xlabel=self.xlabel, ylabel=self.ylabel) xtl = ax.set_xticklabels(self.xticklabels) ytl = ax.set_yticklabels(self.yticklabels, rotation='vertical') # Force a draw of the plot to avoid matplotlib window error _draw_figure(ax.figure) if len(ytl) > 0 and axis_ticklabels_overlap(ytl): plt.setp(ytl, rotation="horizontal") if len(xtl) > 0 and axis_ticklabels_overlap(xtl): plt.setp(xtl, rotation="vertical") return self
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L585-L639
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
16.363636
[ 9, 10, 11, 13, 14, 16, 17, 20, 21, 22, 24, 25, 29, 30, 32, 33, 37, 38, 40, 42, 44, 45, 48, 50, 51, 52, 53, 54 ]
50.909091
false
42.46824
55
9
49.090909
6
def plot(self, ax, tree_kws): tree_kws = {} if tree_kws is None else tree_kws.copy() tree_kws.setdefault("linewidths", .5) tree_kws.setdefault("colors", tree_kws.pop("color", (.2, .2, .2))) if self.rotate and self.axis == 0: coords = zip(self.dependent_coord, self.independent_coord) else: coords = zip(self.independent_coord, self.dependent_coord) lines = LineCollection([list(zip(x, y)) for x, y in coords], **tree_kws) ax.add_collection(lines) number_of_leaves = len(self.reordered_ind) max_dependent_coord = max(map(max, self.dependent_coord)) if self.rotate: ax.yaxis.set_ticks_position('right') # Constants 10 and 1.05 come from # `scipy.cluster.hierarchy._plot_dendrogram` ax.set_ylim(0, number_of_leaves * 10) ax.set_xlim(0, max_dependent_coord * 1.05) ax.invert_xaxis() ax.invert_yaxis() else: # Constants 10 and 1.05 come from # `scipy.cluster.hierarchy._plot_dendrogram` ax.set_xlim(0, number_of_leaves * 10) ax.set_ylim(0, max_dependent_coord * 1.05) despine(ax=ax, bottom=True, left=True) ax.set(xticks=self.xticks, yticks=self.yticks, xlabel=self.xlabel, ylabel=self.ylabel) xtl = ax.set_xticklabels(self.xticklabels) ytl = ax.set_yticklabels(self.yticklabels, rotation='vertical') # Force a draw of the plot to avoid matplotlib window error _draw_figure(ax.figure) if len(ytl) > 0 and axis_ticklabels_overlap(ytl): plt.setp(ytl, rotation="horizontal") if len(xtl) > 0 and axis_ticklabels_overlap(xtl): plt.setp(xtl, rotation="vertical") return self
19,198
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/matrix.py
ClusterGrid.__init__
(self, data, pivot_kws=None, z_score=None, standard_scale=None, figsize=None, row_colors=None, col_colors=None, mask=None, dendrogram_ratio=None, colors_ratio=None, cbar_pos=None)
Grid object for organizing clustered heatmap input on to axes
Grid object for organizing clustered heatmap input on to axes
698
772
def __init__(self, data, pivot_kws=None, z_score=None, standard_scale=None, figsize=None, row_colors=None, col_colors=None, mask=None, dendrogram_ratio=None, colors_ratio=None, cbar_pos=None): """Grid object for organizing clustered heatmap input on to axes""" if _no_scipy: raise RuntimeError("ClusterGrid requires scipy to be available") if isinstance(data, pd.DataFrame): self.data = data else: self.data = pd.DataFrame(data) self.data2d = self.format_data(self.data, pivot_kws, z_score, standard_scale) self.mask = _matrix_mask(self.data2d, mask) self._figure = plt.figure(figsize=figsize) self.row_colors, self.row_color_labels = \ self._preprocess_colors(data, row_colors, axis=0) self.col_colors, self.col_color_labels = \ self._preprocess_colors(data, col_colors, axis=1) try: row_dendrogram_ratio, col_dendrogram_ratio = dendrogram_ratio except TypeError: row_dendrogram_ratio = col_dendrogram_ratio = dendrogram_ratio try: row_colors_ratio, col_colors_ratio = colors_ratio except TypeError: row_colors_ratio = col_colors_ratio = colors_ratio width_ratios = self.dim_ratios(self.row_colors, row_dendrogram_ratio, row_colors_ratio) height_ratios = self.dim_ratios(self.col_colors, col_dendrogram_ratio, col_colors_ratio) nrows = 2 if self.col_colors is None else 3 ncols = 2 if self.row_colors is None else 3 self.gs = gridspec.GridSpec(nrows, ncols, width_ratios=width_ratios, height_ratios=height_ratios) self.ax_row_dendrogram = self._figure.add_subplot(self.gs[-1, 0]) self.ax_col_dendrogram = self._figure.add_subplot(self.gs[0, -1]) self.ax_row_dendrogram.set_axis_off() self.ax_col_dendrogram.set_axis_off() self.ax_row_colors = None self.ax_col_colors = None if self.row_colors is not None: self.ax_row_colors = self._figure.add_subplot( self.gs[-1, 1]) if self.col_colors is not None: self.ax_col_colors = self._figure.add_subplot( self.gs[1, -1]) self.ax_heatmap = self._figure.add_subplot(self.gs[-1, -1]) if cbar_pos is None: self.ax_cbar = self.cax = None else: # Initialize the colorbar axes in the gridspec so that tight_layout # works. We will move it where it belongs later. This is a hack. self.ax_cbar = self._figure.add_subplot(self.gs[0, 0]) self.cax = self.ax_cbar # Backwards compatibility self.cbar_pos = cbar_pos self.dendrogram_row = None self.dendrogram_col = None
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L698-L772
26
[ 0, 3, 4, 5, 6 ]
6.666667
[ 7, 8, 10, 12, 15, 17, 19, 21, 24, 25, 26, 27, 29, 30, 31, 32, 34, 37, 41, 42, 44, 48, 49, 50, 51, 53, 54, 56, 57, 59, 60, 63, 64, 65, 69, 70, 71, 73, 74 ]
52
false
42.46824
75
8
48
1
def __init__(self, data, pivot_kws=None, z_score=None, standard_scale=None, figsize=None, row_colors=None, col_colors=None, mask=None, dendrogram_ratio=None, colors_ratio=None, cbar_pos=None): if _no_scipy: raise RuntimeError("ClusterGrid requires scipy to be available") if isinstance(data, pd.DataFrame): self.data = data else: self.data = pd.DataFrame(data) self.data2d = self.format_data(self.data, pivot_kws, z_score, standard_scale) self.mask = _matrix_mask(self.data2d, mask) self._figure = plt.figure(figsize=figsize) self.row_colors, self.row_color_labels = \ self._preprocess_colors(data, row_colors, axis=0) self.col_colors, self.col_color_labels = \ self._preprocess_colors(data, col_colors, axis=1) try: row_dendrogram_ratio, col_dendrogram_ratio = dendrogram_ratio except TypeError: row_dendrogram_ratio = col_dendrogram_ratio = dendrogram_ratio try: row_colors_ratio, col_colors_ratio = colors_ratio except TypeError: row_colors_ratio = col_colors_ratio = colors_ratio width_ratios = self.dim_ratios(self.row_colors, row_dendrogram_ratio, row_colors_ratio) height_ratios = self.dim_ratios(self.col_colors, col_dendrogram_ratio, col_colors_ratio) nrows = 2 if self.col_colors is None else 3 ncols = 2 if self.row_colors is None else 3 self.gs = gridspec.GridSpec(nrows, ncols, width_ratios=width_ratios, height_ratios=height_ratios) self.ax_row_dendrogram = self._figure.add_subplot(self.gs[-1, 0]) self.ax_col_dendrogram = self._figure.add_subplot(self.gs[0, -1]) self.ax_row_dendrogram.set_axis_off() self.ax_col_dendrogram.set_axis_off() self.ax_row_colors = None self.ax_col_colors = None if self.row_colors is not None: self.ax_row_colors = self._figure.add_subplot( self.gs[-1, 1]) if self.col_colors is not None: self.ax_col_colors = self._figure.add_subplot( self.gs[1, -1]) self.ax_heatmap = self._figure.add_subplot(self.gs[-1, -1]) if cbar_pos is None: self.ax_cbar = self.cax = None else: # Initialize the colorbar axes in the gridspec so that tight_layout # works. We will move it where it belongs later. This is a hack. self.ax_cbar = self._figure.add_subplot(self.gs[0, 0]) self.cax = self.ax_cbar # Backwards compatibility self.cbar_pos = cbar_pos self.dendrogram_row = None self.dendrogram_col = None
19,199
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/matrix.py
ClusterGrid._preprocess_colors
(self, data, colors, axis)
return colors, labels
Preprocess {row/col}_colors to extract labels and convert colors.
Preprocess {row/col}_colors to extract labels and convert colors.
774
814
def _preprocess_colors(self, data, colors, axis): """Preprocess {row/col}_colors to extract labels and convert colors.""" labels = None if colors is not None: if isinstance(colors, (pd.DataFrame, pd.Series)): # If data is unindexed, raise if (not hasattr(data, "index") and axis == 0) or ( not hasattr(data, "columns") and axis == 1 ): axis_name = "col" if axis else "row" msg = (f"{axis_name}_colors indices can't be matched with data " f"indices. Provide {axis_name}_colors as a non-indexed " "datatype, e.g. by using `.to_numpy()``") raise TypeError(msg) # Ensure colors match data indices if axis == 0: colors = colors.reindex(data.index) else: colors = colors.reindex(data.columns) # Replace na's with white color # TODO We should set these to transparent instead colors = colors.astype(object).fillna('white') # Extract color values and labels from frame/series if isinstance(colors, pd.DataFrame): labels = list(colors.columns) colors = colors.T.values else: if colors.name is None: labels = [""] else: labels = [colors.name] colors = colors.values colors = _convert_colors(colors) return colors, labels
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L774-L814
26
[ 0, 1 ]
4.878049
[ 2, 4, 5, 8, 11, 12, 15, 18, 19, 21, 25, 28, 29, 30, 32, 33, 35, 36, 38, 40 ]
48.780488
false
42.46824
41
10
51.219512
1
def _preprocess_colors(self, data, colors, axis): labels = None if colors is not None: if isinstance(colors, (pd.DataFrame, pd.Series)): # If data is unindexed, raise if (not hasattr(data, "index") and axis == 0) or ( not hasattr(data, "columns") and axis == 1 ): axis_name = "col" if axis else "row" msg = (f"{axis_name}_colors indices can't be matched with data " f"indices. Provide {axis_name}_colors as a non-indexed " "datatype, e.g. by using `.to_numpy()``") raise TypeError(msg) # Ensure colors match data indices if axis == 0: colors = colors.reindex(data.index) else: colors = colors.reindex(data.columns) # Replace na's with white color # TODO We should set these to transparent instead colors = colors.astype(object).fillna('white') # Extract color values and labels from frame/series if isinstance(colors, pd.DataFrame): labels = list(colors.columns) colors = colors.T.values else: if colors.name is None: labels = [""] else: labels = [colors.name] colors = colors.values colors = _convert_colors(colors) return colors, labels
19,200
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/matrix.py
ClusterGrid.format_data
(self, data, pivot_kws, z_score=None, standard_scale=None)
return data2d
Extract variables from data or use directly.
Extract variables from data or use directly.
816
834
def format_data(self, data, pivot_kws, z_score=None, standard_scale=None): """Extract variables from data or use directly.""" # Either the data is already in 2d matrix format, or need to do a pivot if pivot_kws is not None: data2d = data.pivot(**pivot_kws) else: data2d = data if z_score is not None and standard_scale is not None: raise ValueError( 'Cannot perform both z-scoring and standard-scaling on data') if z_score is not None: data2d = self.z_score(data2d, z_score) if standard_scale is not None: data2d = self.standard_scale(data2d, standard_scale) return data2d
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L816-L834
26
[ 0 ]
5.263158
[ 5, 6, 8, 10, 11, 14, 15, 16, 17, 18 ]
52.631579
false
42.46824
19
6
47.368421
1
def format_data(self, data, pivot_kws, z_score=None, standard_scale=None): # Either the data is already in 2d matrix format, or need to do a pivot if pivot_kws is not None: data2d = data.pivot(**pivot_kws) else: data2d = data if z_score is not None and standard_scale is not None: raise ValueError( 'Cannot perform both z-scoring and standard-scaling on data') if z_score is not None: data2d = self.z_score(data2d, z_score) if standard_scale is not None: data2d = self.standard_scale(data2d, standard_scale) return data2d
19,201
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/matrix.py
ClusterGrid.z_score
(data2d, axis=1)
Standarize the mean and variance of the data axis Parameters ---------- data2d : pandas.DataFrame Data to normalize axis : int Which axis to normalize across. If 0, normalize across rows, if 1, normalize across columns. Returns ------- normalized : pandas.DataFrame Noramlized data with a mean of 0 and variance of 1 across the specified axis.
Standarize the mean and variance of the data axis
837
864
def z_score(data2d, axis=1): """Standarize the mean and variance of the data axis Parameters ---------- data2d : pandas.DataFrame Data to normalize axis : int Which axis to normalize across. If 0, normalize across rows, if 1, normalize across columns. Returns ------- normalized : pandas.DataFrame Noramlized data with a mean of 0 and variance of 1 across the specified axis. """ if axis == 1: z_scored = data2d else: z_scored = data2d.T z_scored = (z_scored - z_scored.mean()) / z_scored.std() if axis == 1: return z_scored else: return z_scored.T
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L837-L864
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
60.714286
[ 17, 18, 20, 22, 24, 25, 27 ]
25
false
42.46824
28
3
75
15
def z_score(data2d, axis=1): if axis == 1: z_scored = data2d else: z_scored = data2d.T z_scored = (z_scored - z_scored.mean()) / z_scored.std() if axis == 1: return z_scored else: return z_scored.T
19,202
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/matrix.py
ClusterGrid.standard_scale
(data2d, axis=1)
Divide the data by the difference between the max and min Parameters ---------- data2d : pandas.DataFrame Data to normalize axis : int Which axis to normalize across. If 0, normalize across rows, if 1, normalize across columns. Returns ------- standardized : pandas.DataFrame Noramlized data with a mean of 0 and variance of 1 across the specified axis.
Divide the data by the difference between the max and min
867
898
def standard_scale(data2d, axis=1): """Divide the data by the difference between the max and min Parameters ---------- data2d : pandas.DataFrame Data to normalize axis : int Which axis to normalize across. If 0, normalize across rows, if 1, normalize across columns. Returns ------- standardized : pandas.DataFrame Noramlized data with a mean of 0 and variance of 1 across the specified axis. """ # Normalize these values to range from 0 to 1 if axis == 1: standardized = data2d else: standardized = data2d.T subtract = standardized.min() standardized = (standardized - subtract) / ( standardized.max() - standardized.min()) if axis == 1: return standardized else: return standardized.T
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L867-L898
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
59.375
[ 19, 20, 22, 24, 25, 28, 29, 31 ]
25
false
42.46824
32
3
75
15
def standard_scale(data2d, axis=1): # Normalize these values to range from 0 to 1 if axis == 1: standardized = data2d else: standardized = data2d.T subtract = standardized.min() standardized = (standardized - subtract) / ( standardized.max() - standardized.min()) if axis == 1: return standardized else: return standardized.T
19,203
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/matrix.py
ClusterGrid.dim_ratios
(self, colors, dendrogram_ratio, colors_ratio)
return ratios
Get the proportions of the figure taken up by each axes.
Get the proportions of the figure taken up by each axes.
900
916
def dim_ratios(self, colors, dendrogram_ratio, colors_ratio): """Get the proportions of the figure taken up by each axes.""" ratios = [dendrogram_ratio] if colors is not None: # Colors are encoded as rgb, so there is an extra dimension if np.ndim(colors) > 2: n_colors = len(colors) else: n_colors = 1 ratios += [n_colors * colors_ratio] # Add the ratio for the heatmap itself ratios.append(1 - sum(ratios)) return ratios
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L900-L916
26
[ 0, 1 ]
11.764706
[ 2, 4, 6, 7, 9, 11, 14, 16 ]
47.058824
false
42.46824
17
3
52.941176
1
def dim_ratios(self, colors, dendrogram_ratio, colors_ratio): ratios = [dendrogram_ratio] if colors is not None: # Colors are encoded as rgb, so there is an extra dimension if np.ndim(colors) > 2: n_colors = len(colors) else: n_colors = 1 ratios += [n_colors * colors_ratio] # Add the ratio for the heatmap itself ratios.append(1 - sum(ratios)) return ratios
19,204
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/matrix.py
ClusterGrid.color_list_to_matrix_and_cmap
(colors, ind, axis=0)
return matrix, cmap
Turns a list of colors into a numpy matrix and matplotlib colormap These arguments can now be plotted using heatmap(matrix, cmap) and the provided colors will be plotted. Parameters ---------- colors : list of matplotlib colors Colors to label the rows or columns of a dataframe. ind : list of ints Ordering of the rows or columns, to reorder the original colors by the clustered dendrogram order axis : int Which axis this is labeling Returns ------- matrix : numpy.array A numpy array of integer values, where each indexes into the cmap cmap : matplotlib.colors.ListedColormap
Turns a list of colors into a numpy matrix and matplotlib colormap
919
968
def color_list_to_matrix_and_cmap(colors, ind, axis=0): """Turns a list of colors into a numpy matrix and matplotlib colormap These arguments can now be plotted using heatmap(matrix, cmap) and the provided colors will be plotted. Parameters ---------- colors : list of matplotlib colors Colors to label the rows or columns of a dataframe. ind : list of ints Ordering of the rows or columns, to reorder the original colors by the clustered dendrogram order axis : int Which axis this is labeling Returns ------- matrix : numpy.array A numpy array of integer values, where each indexes into the cmap cmap : matplotlib.colors.ListedColormap """ try: mpl.colors.to_rgb(colors[0]) except ValueError: # We have a 2D color structure m, n = len(colors), len(colors[0]) if not all(len(c) == n for c in colors[1:]): raise ValueError("Multiple side color vectors must have same size") else: # We have one vector of colors m, n = 1, len(colors) colors = [colors] # Map from unique colors to colormap index value unique_colors = {} matrix = np.zeros((m, n), int) for i, inner in enumerate(colors): for j, color in enumerate(inner): idx = unique_colors.setdefault(color, len(unique_colors)) matrix[i, j] = idx # Reorder for clustering and transpose for axis matrix = matrix[:, ind] if axis == 0: matrix = matrix.T cmap = mpl.colors.ListedColormap(list(unique_colors)) return matrix, cmap
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L919-L968
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
46
[ 23, 24, 25, 27, 28, 29, 32, 33, 36, 37, 38, 39, 40, 41, 44, 45, 46, 48, 49 ]
38
false
42.46824
50
6
62
20
def color_list_to_matrix_and_cmap(colors, ind, axis=0): try: mpl.colors.to_rgb(colors[0]) except ValueError: # We have a 2D color structure m, n = len(colors), len(colors[0]) if not all(len(c) == n for c in colors[1:]): raise ValueError("Multiple side color vectors must have same size") else: # We have one vector of colors m, n = 1, len(colors) colors = [colors] # Map from unique colors to colormap index value unique_colors = {} matrix = np.zeros((m, n), int) for i, inner in enumerate(colors): for j, color in enumerate(inner): idx = unique_colors.setdefault(color, len(unique_colors)) matrix[i, j] = idx # Reorder for clustering and transpose for axis matrix = matrix[:, ind] if axis == 0: matrix = matrix.T cmap = mpl.colors.ListedColormap(list(unique_colors)) return matrix, cmap
19,205
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/matrix.py
ClusterGrid.plot_dendrograms
(self, row_cluster, col_cluster, metric, method, row_linkage, col_linkage, tree_kws)
970
993
def plot_dendrograms(self, row_cluster, col_cluster, metric, method, row_linkage, col_linkage, tree_kws): # Plot the row dendrogram if row_cluster: self.dendrogram_row = dendrogram( self.data2d, metric=metric, method=method, label=False, axis=0, ax=self.ax_row_dendrogram, rotate=True, linkage=row_linkage, tree_kws=tree_kws ) else: self.ax_row_dendrogram.set_xticks([]) self.ax_row_dendrogram.set_yticks([]) # PLot the column dendrogram if col_cluster: self.dendrogram_col = dendrogram( self.data2d, metric=metric, method=method, label=False, axis=1, ax=self.ax_col_dendrogram, linkage=col_linkage, tree_kws=tree_kws ) else: self.ax_col_dendrogram.set_xticks([]) self.ax_col_dendrogram.set_yticks([]) despine(ax=self.ax_row_dendrogram, bottom=True, left=True) despine(ax=self.ax_col_dendrogram, bottom=True, left=True)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L970-L993
26
[ 0 ]
4.166667
[ 3, 4, 10, 11, 13, 14, 20, 21, 22, 23 ]
41.666667
false
42.46824
24
3
58.333333
0
def plot_dendrograms(self, row_cluster, col_cluster, metric, method, row_linkage, col_linkage, tree_kws): # Plot the row dendrogram if row_cluster: self.dendrogram_row = dendrogram( self.data2d, metric=metric, method=method, label=False, axis=0, ax=self.ax_row_dendrogram, rotate=True, linkage=row_linkage, tree_kws=tree_kws ) else: self.ax_row_dendrogram.set_xticks([]) self.ax_row_dendrogram.set_yticks([]) # PLot the column dendrogram if col_cluster: self.dendrogram_col = dendrogram( self.data2d, metric=metric, method=method, label=False, axis=1, ax=self.ax_col_dendrogram, linkage=col_linkage, tree_kws=tree_kws ) else: self.ax_col_dendrogram.set_xticks([]) self.ax_col_dendrogram.set_yticks([]) despine(ax=self.ax_row_dendrogram, bottom=True, left=True) despine(ax=self.ax_col_dendrogram, bottom=True, left=True)
19,206
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/matrix.py
ClusterGrid.plot_colors
(self, xind, yind, **kws)
Plots color labels between the dendrogram and the heatmap Parameters ---------- heatmap_kws : dict Keyword arguments heatmap
Plots color labels between the dendrogram and the heatmap
995
1,058
def plot_colors(self, xind, yind, **kws): """Plots color labels between the dendrogram and the heatmap Parameters ---------- heatmap_kws : dict Keyword arguments heatmap """ # Remove any custom colormap and centering # TODO this code has consistently caused problems when we # have missed kwargs that need to be excluded that it might # be better to rewrite *in*clusively. kws = kws.copy() kws.pop('cmap', None) kws.pop('norm', None) kws.pop('center', None) kws.pop('annot', None) kws.pop('vmin', None) kws.pop('vmax', None) kws.pop('robust', None) kws.pop('xticklabels', None) kws.pop('yticklabels', None) # Plot the row colors if self.row_colors is not None: matrix, cmap = self.color_list_to_matrix_and_cmap( self.row_colors, yind, axis=0) # Get row_color labels if self.row_color_labels is not None: row_color_labels = self.row_color_labels else: row_color_labels = False heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_row_colors, xticklabels=row_color_labels, yticklabels=False, **kws) # Adjust rotation of labels if row_color_labels is not False: plt.setp(self.ax_row_colors.get_xticklabels(), rotation=90) else: despine(self.ax_row_colors, left=True, bottom=True) # Plot the column colors if self.col_colors is not None: matrix, cmap = self.color_list_to_matrix_and_cmap( self.col_colors, xind, axis=1) # Get col_color labels if self.col_color_labels is not None: col_color_labels = self.col_color_labels else: col_color_labels = False heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_col_colors, xticklabels=False, yticklabels=col_color_labels, **kws) # Adjust rotation of labels, place on right side if col_color_labels is not False: self.ax_col_colors.yaxis.tick_right() plt.setp(self.ax_col_colors.get_yticklabels(), rotation=0) else: despine(self.ax_col_colors, left=True, bottom=True)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L995-L1058
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
20.3125
[ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 25, 26, 30, 31, 33, 35, 39, 40, 42, 45, 46, 50, 51, 53, 55, 59, 60, 61, 63 ]
45.3125
false
42.46824
64
7
54.6875
6
def plot_colors(self, xind, yind, **kws): # Remove any custom colormap and centering # TODO this code has consistently caused problems when we # have missed kwargs that need to be excluded that it might # be better to rewrite *in*clusively. kws = kws.copy() kws.pop('cmap', None) kws.pop('norm', None) kws.pop('center', None) kws.pop('annot', None) kws.pop('vmin', None) kws.pop('vmax', None) kws.pop('robust', None) kws.pop('xticklabels', None) kws.pop('yticklabels', None) # Plot the row colors if self.row_colors is not None: matrix, cmap = self.color_list_to_matrix_and_cmap( self.row_colors, yind, axis=0) # Get row_color labels if self.row_color_labels is not None: row_color_labels = self.row_color_labels else: row_color_labels = False heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_row_colors, xticklabels=row_color_labels, yticklabels=False, **kws) # Adjust rotation of labels if row_color_labels is not False: plt.setp(self.ax_row_colors.get_xticklabels(), rotation=90) else: despine(self.ax_row_colors, left=True, bottom=True) # Plot the column colors if self.col_colors is not None: matrix, cmap = self.color_list_to_matrix_and_cmap( self.col_colors, xind, axis=1) # Get col_color labels if self.col_color_labels is not None: col_color_labels = self.col_color_labels else: col_color_labels = False heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_col_colors, xticklabels=False, yticklabels=col_color_labels, **kws) # Adjust rotation of labels, place on right side if col_color_labels is not False: self.ax_col_colors.yaxis.tick_right() plt.setp(self.ax_col_colors.get_yticklabels(), rotation=0) else: despine(self.ax_col_colors, left=True, bottom=True)
19,207
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/matrix.py
ClusterGrid.plot_matrix
(self, colorbar_kws, xind, yind, **kws)
1,060
1,115
def plot_matrix(self, colorbar_kws, xind, yind, **kws): self.data2d = self.data2d.iloc[yind, xind] self.mask = self.mask.iloc[yind, xind] # Try to reorganize specified tick labels, if provided xtl = kws.pop("xticklabels", "auto") try: xtl = np.asarray(xtl)[xind] except (TypeError, IndexError): pass ytl = kws.pop("yticklabels", "auto") try: ytl = np.asarray(ytl)[yind] except (TypeError, IndexError): pass # Reorganize the annotations to match the heatmap annot = kws.pop("annot", None) if annot is None or annot is False: pass else: if isinstance(annot, bool): annot_data = self.data2d else: annot_data = np.asarray(annot) if annot_data.shape != self.data2d.shape: err = "`data` and `annot` must have same shape." raise ValueError(err) annot_data = annot_data[yind][:, xind] annot = annot_data # Setting ax_cbar=None in clustermap call implies no colorbar kws.setdefault("cbar", self.ax_cbar is not None) heatmap(self.data2d, ax=self.ax_heatmap, cbar_ax=self.ax_cbar, cbar_kws=colorbar_kws, mask=self.mask, xticklabels=xtl, yticklabels=ytl, annot=annot, **kws) ytl = self.ax_heatmap.get_yticklabels() ytl_rot = None if not ytl else ytl[0].get_rotation() self.ax_heatmap.yaxis.set_ticks_position('right') self.ax_heatmap.yaxis.set_label_position('right') if ytl_rot is not None: ytl = self.ax_heatmap.get_yticklabels() plt.setp(ytl, rotation=ytl_rot) tight_params = dict(h_pad=.02, w_pad=.02) if self.ax_cbar is None: self._figure.tight_layout(**tight_params) else: # Turn the colorbar axes off for tight layout so that its # ticks don't interfere with the rest of the plot layout. # Then move it. self.ax_cbar.set_axis_off() self._figure.tight_layout(**tight_params) self.ax_cbar.set_axis_on() self.ax_cbar.set_position(self.cbar_pos)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L1060-L1115
26
[ 0 ]
1.785714
[ 1, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17, 18, 19, 21, 22, 24, 25, 26, 27, 28, 29, 32, 33, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 52, 53, 54, 55 ]
69.642857
false
42.46824
56
9
30.357143
0
def plot_matrix(self, colorbar_kws, xind, yind, **kws): self.data2d = self.data2d.iloc[yind, xind] self.mask = self.mask.iloc[yind, xind] # Try to reorganize specified tick labels, if provided xtl = kws.pop("xticklabels", "auto") try: xtl = np.asarray(xtl)[xind] except (TypeError, IndexError): pass ytl = kws.pop("yticklabels", "auto") try: ytl = np.asarray(ytl)[yind] except (TypeError, IndexError): pass # Reorganize the annotations to match the heatmap annot = kws.pop("annot", None) if annot is None or annot is False: pass else: if isinstance(annot, bool): annot_data = self.data2d else: annot_data = np.asarray(annot) if annot_data.shape != self.data2d.shape: err = "`data` and `annot` must have same shape." raise ValueError(err) annot_data = annot_data[yind][:, xind] annot = annot_data # Setting ax_cbar=None in clustermap call implies no colorbar kws.setdefault("cbar", self.ax_cbar is not None) heatmap(self.data2d, ax=self.ax_heatmap, cbar_ax=self.ax_cbar, cbar_kws=colorbar_kws, mask=self.mask, xticklabels=xtl, yticklabels=ytl, annot=annot, **kws) ytl = self.ax_heatmap.get_yticklabels() ytl_rot = None if not ytl else ytl[0].get_rotation() self.ax_heatmap.yaxis.set_ticks_position('right') self.ax_heatmap.yaxis.set_label_position('right') if ytl_rot is not None: ytl = self.ax_heatmap.get_yticklabels() plt.setp(ytl, rotation=ytl_rot) tight_params = dict(h_pad=.02, w_pad=.02) if self.ax_cbar is None: self._figure.tight_layout(**tight_params) else: # Turn the colorbar axes off for tight layout so that its # ticks don't interfere with the rest of the plot layout. # Then move it. self.ax_cbar.set_axis_off() self._figure.tight_layout(**tight_params) self.ax_cbar.set_axis_on() self.ax_cbar.set_position(self.cbar_pos)
19,208
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/matrix.py
ClusterGrid.plot
(self, metric, method, colorbar_kws, row_cluster, col_cluster, row_linkage, col_linkage, tree_kws, **kws)
return self
1,117
1,143
def plot(self, metric, method, colorbar_kws, row_cluster, col_cluster, row_linkage, col_linkage, tree_kws, **kws): # heatmap square=True sets the aspect ratio on the axes, but that is # not compatible with the multi-axes layout of clustergrid if kws.get("square", False): msg = "``square=True`` ignored in clustermap" warnings.warn(msg) kws.pop("square") colorbar_kws = {} if colorbar_kws is None else colorbar_kws self.plot_dendrograms(row_cluster, col_cluster, metric, method, row_linkage=row_linkage, col_linkage=col_linkage, tree_kws=tree_kws) try: xind = self.dendrogram_col.reordered_ind except AttributeError: xind = np.arange(self.data2d.shape[1]) try: yind = self.dendrogram_row.reordered_ind except AttributeError: yind = np.arange(self.data2d.shape[0]) self.plot_colors(xind, yind, **kws) self.plot_matrix(colorbar_kws, xind, yind, **kws) return self
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/matrix.py#L1117-L1143
26
[ 0 ]
3.703704
[ 5, 6, 7, 8, 10, 12, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26 ]
62.962963
false
42.46824
27
4
37.037037
0
def plot(self, metric, method, colorbar_kws, row_cluster, col_cluster, row_linkage, col_linkage, tree_kws, **kws): # heatmap square=True sets the aspect ratio on the axes, but that is # not compatible with the multi-axes layout of clustergrid if kws.get("square", False): msg = "``square=True`` ignored in clustermap" warnings.warn(msg) kws.pop("square") colorbar_kws = {} if colorbar_kws is None else colorbar_kws self.plot_dendrograms(row_cluster, col_cluster, metric, method, row_linkage=row_linkage, col_linkage=col_linkage, tree_kws=tree_kws) try: xind = self.dendrogram_col.reordered_ind except AttributeError: xind = np.arange(self.data2d.shape[1]) try: yind = self.dendrogram_row.reordered_ind except AttributeError: yind = np.arange(self.data2d.shape[0]) self.plot_colors(xind, yind, **kws) self.plot_matrix(colorbar_kws, xind, yind, **kws) return self
19,209
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/algorithms.py
bootstrap
(*args, **kwargs)
return np.array(boot_dist)
Resample one or more arrays with replacement and store aggregate values. Positional arguments are a sequence of arrays to bootstrap along the first axis and pass to a summary function. Keyword arguments: n_boot : int, default=10000 Number of iterations axis : int, default=None Will pass axis to ``func`` as a keyword argument. units : array, default=None Array of sampling unit IDs. When used the bootstrap resamples units and then observations within units instead of individual datapoints. func : string or callable, default="mean" Function to call on the args that are passed in. If string, uses as name of function in the numpy namespace. If nans are present in the data, will try to use nan-aware version of named function. seed : Generator | SeedSequence | RandomState | int | None Seed for the random number generator; useful if you want reproducible resamples. Returns ------- boot_dist: array array of bootstrapped statistic values
Resample one or more arrays with replacement and store aggregate values.
6
101
def bootstrap(*args, **kwargs): """Resample one or more arrays with replacement and store aggregate values. Positional arguments are a sequence of arrays to bootstrap along the first axis and pass to a summary function. Keyword arguments: n_boot : int, default=10000 Number of iterations axis : int, default=None Will pass axis to ``func`` as a keyword argument. units : array, default=None Array of sampling unit IDs. When used the bootstrap resamples units and then observations within units instead of individual datapoints. func : string or callable, default="mean" Function to call on the args that are passed in. If string, uses as name of function in the numpy namespace. If nans are present in the data, will try to use nan-aware version of named function. seed : Generator | SeedSequence | RandomState | int | None Seed for the random number generator; useful if you want reproducible resamples. Returns ------- boot_dist: array array of bootstrapped statistic values """ # Ensure list of arrays are same length if len(np.unique(list(map(len, args)))) > 1: raise ValueError("All input arrays must have the same length") n = len(args[0]) # Default keyword arguments n_boot = kwargs.get("n_boot", 10000) func = kwargs.get("func", "mean") axis = kwargs.get("axis", None) units = kwargs.get("units", None) random_seed = kwargs.get("random_seed", None) if random_seed is not None: msg = "`random_seed` has been renamed to `seed` and will be removed" warnings.warn(msg) seed = kwargs.get("seed", random_seed) if axis is None: func_kwargs = dict() else: func_kwargs = dict(axis=axis) # Initialize the resampler if isinstance(seed, np.random.RandomState): rng = seed else: rng = np.random.default_rng(seed) # Coerce to arrays args = list(map(np.asarray, args)) if units is not None: units = np.asarray(units) if isinstance(func, str): # Allow named numpy functions f = getattr(np, func) # Try to use nan-aware version of function if necessary missing_data = np.isnan(np.sum(np.column_stack(args))) if missing_data and not func.startswith("nan"): nanf = getattr(np, f"nan{func}", None) if nanf is None: msg = f"Data contain nans but no nan-aware version of `{func}` found" warnings.warn(msg, UserWarning) else: f = nanf else: f = func # Handle numpy changes try: integers = rng.integers except AttributeError: integers = rng.randint # Do the bootstrap if units is not None: return _structured_bootstrap(args, n_boot, units, f, func_kwargs, integers) boot_dist = [] for i in range(int(n_boot)): resampler = integers(0, n, n, dtype=np.intp) # intp is indexing dtype sample = [a.take(resampler, axis=0) for a in args] boot_dist.append(f(*sample, **func_kwargs)) return np.array(boot_dist)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/algorithms.py#L6-L101
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 ]
100
[]
0
true
100
96
14
100
26
def bootstrap(*args, **kwargs): # Ensure list of arrays are same length if len(np.unique(list(map(len, args)))) > 1: raise ValueError("All input arrays must have the same length") n = len(args[0]) # Default keyword arguments n_boot = kwargs.get("n_boot", 10000) func = kwargs.get("func", "mean") axis = kwargs.get("axis", None) units = kwargs.get("units", None) random_seed = kwargs.get("random_seed", None) if random_seed is not None: msg = "`random_seed` has been renamed to `seed` and will be removed" warnings.warn(msg) seed = kwargs.get("seed", random_seed) if axis is None: func_kwargs = dict() else: func_kwargs = dict(axis=axis) # Initialize the resampler if isinstance(seed, np.random.RandomState): rng = seed else: rng = np.random.default_rng(seed) # Coerce to arrays args = list(map(np.asarray, args)) if units is not None: units = np.asarray(units) if isinstance(func, str): # Allow named numpy functions f = getattr(np, func) # Try to use nan-aware version of function if necessary missing_data = np.isnan(np.sum(np.column_stack(args))) if missing_data and not func.startswith("nan"): nanf = getattr(np, f"nan{func}", None) if nanf is None: msg = f"Data contain nans but no nan-aware version of `{func}` found" warnings.warn(msg, UserWarning) else: f = nanf else: f = func # Handle numpy changes try: integers = rng.integers except AttributeError: integers = rng.randint # Do the bootstrap if units is not None: return _structured_bootstrap(args, n_boot, units, f, func_kwargs, integers) boot_dist = [] for i in range(int(n_boot)): resampler = integers(0, n, n, dtype=np.intp) # intp is indexing dtype sample = [a.take(resampler, axis=0) for a in args] boot_dist.append(f(*sample, **func_kwargs)) return np.array(boot_dist)
19,210
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/algorithms.py
_structured_bootstrap
(args, n_boot, units, func, func_kwargs, integers)
return np.array(boot_dist)
Resample units instead of datapoints.
Resample units instead of datapoints.
104
120
def _structured_bootstrap(args, n_boot, units, func, func_kwargs, integers): """Resample units instead of datapoints.""" unique_units = np.unique(units) n_units = len(unique_units) args = [[a[units == unit] for unit in unique_units] for a in args] boot_dist = [] for i in range(int(n_boot)): resampler = integers(0, n_units, n_units, dtype=np.intp) sample = [[a[i] for i in resampler] for a in args] lengths = map(len, sample[0]) resampler = [integers(0, n, n, dtype=np.intp) for n in lengths] sample = [[c.take(r, axis=0) for c, r in zip(a, resampler)] for a in sample] sample = list(map(np.concatenate, sample)) boot_dist.append(func(*sample, **func_kwargs)) return np.array(boot_dist)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/algorithms.py#L104-L120
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
100
[]
0
true
100
17
9
100
1
def _structured_bootstrap(args, n_boot, units, func, func_kwargs, integers): unique_units = np.unique(units) n_units = len(unique_units) args = [[a[units == unit] for unit in unique_units] for a in args] boot_dist = [] for i in range(int(n_boot)): resampler = integers(0, n_units, n_units, dtype=np.intp) sample = [[a[i] for i in resampler] for a in args] lengths = map(len, sample[0]) resampler = [integers(0, n, n, dtype=np.intp) for n in lengths] sample = [[c.take(r, axis=0) for c, r in zip(a, resampler)] for a in sample] sample = list(map(np.concatenate, sample)) boot_dist.append(func(*sample, **func_kwargs)) return np.array(boot_dist)
19,211
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
histplot
( data=None, *, # Vector variables x=None, y=None, hue=None, weights=None, # Histogram computation parameters stat="count", bins="auto", binwidth=None, binrange=None, discrete=None, cumulative=False, common_bins=True, common_norm=True, # Histogram appearance parameters multiple="layer", element="bars", fill=True, shrink=1, # Histogram smoothing with a kernel density estimate kde=False, kde_kws=None, line_kws=None, # Bivariate histogram parameters thresh=0, pthresh=None, pmax=None, cbar=False, cbar_ax=None, cbar_kws=None, # Hue mapping parameters palette=None, hue_order=None, hue_norm=None, color=None, # Axes information log_scale=None, legend=True, ax=None, # Other appearance keywords **kwargs, )
return ax
1,374
1,465
def histplot( data=None, *, # Vector variables x=None, y=None, hue=None, weights=None, # Histogram computation parameters stat="count", bins="auto", binwidth=None, binrange=None, discrete=None, cumulative=False, common_bins=True, common_norm=True, # Histogram appearance parameters multiple="layer", element="bars", fill=True, shrink=1, # Histogram smoothing with a kernel density estimate kde=False, kde_kws=None, line_kws=None, # Bivariate histogram parameters thresh=0, pthresh=None, pmax=None, cbar=False, cbar_ax=None, cbar_kws=None, # Hue mapping parameters palette=None, hue_order=None, hue_norm=None, color=None, # Axes information log_scale=None, legend=True, ax=None, # Other appearance keywords **kwargs, ): p = _DistributionPlotter( data=data, variables=_DistributionPlotter.get_semantics(locals()) ) p.map_hue(palette=palette, order=hue_order, norm=hue_norm) if ax is None: ax = plt.gca() p._attach(ax, log_scale=log_scale) if p.univariate: # Note, bivariate plots won't cycle if fill: method = ax.bar if element == "bars" else ax.fill_between else: method = ax.plot color = _default_color(method, hue, color, kwargs) if not p.has_xy_data: return ax # Default to discrete bins for categorical variables if discrete is None: discrete = p._default_discrete() estimate_kws = dict( stat=stat, bins=bins, binwidth=binwidth, binrange=binrange, discrete=discrete, cumulative=cumulative, ) if p.univariate: p.plot_univariate_histogram( multiple=multiple, element=element, fill=fill, shrink=shrink, common_norm=common_norm, common_bins=common_bins, kde=kde, kde_kws=kde_kws, color=color, legend=legend, estimate_kws=estimate_kws, line_kws=line_kws, **kwargs, ) else: p.plot_bivariate_histogram( common_bins=common_bins, common_norm=common_norm, thresh=thresh, pthresh=pthresh, pmax=pmax, color=color, legend=legend, cbar=cbar, cbar_ax=cbar_ax, cbar_kws=cbar_kws, estimate_kws=estimate_kws, **kwargs, ) return ax
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L1374-L1465
26
[ 0, 20, 21, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 55, 56, 57, 58, 75, 76, 90, 91 ]
35.869565
[]
0
false
96.354167
92
7
100
0
def histplot( data=None, *, # Vector variables x=None, y=None, hue=None, weights=None, # Histogram computation parameters stat="count", bins="auto", binwidth=None, binrange=None, discrete=None, cumulative=False, common_bins=True, common_norm=True, # Histogram appearance parameters multiple="layer", element="bars", fill=True, shrink=1, # Histogram smoothing with a kernel density estimate kde=False, kde_kws=None, line_kws=None, # Bivariate histogram parameters thresh=0, pthresh=None, pmax=None, cbar=False, cbar_ax=None, cbar_kws=None, # Hue mapping parameters palette=None, hue_order=None, hue_norm=None, color=None, # Axes information log_scale=None, legend=True, ax=None, # Other appearance keywords **kwargs, ): p = _DistributionPlotter( data=data, variables=_DistributionPlotter.get_semantics(locals()) ) p.map_hue(palette=palette, order=hue_order, norm=hue_norm) if ax is None: ax = plt.gca() p._attach(ax, log_scale=log_scale) if p.univariate: # Note, bivariate plots won't cycle if fill: method = ax.bar if element == "bars" else ax.fill_between else: method = ax.plot color = _default_color(method, hue, color, kwargs) if not p.has_xy_data: return ax # Default to discrete bins for categorical variables if discrete is None: discrete = p._default_discrete() estimate_kws = dict( stat=stat, bins=bins, binwidth=binwidth, binrange=binrange, discrete=discrete, cumulative=cumulative, ) if p.univariate: p.plot_univariate_histogram( multiple=multiple, element=element, fill=fill, shrink=shrink, common_norm=common_norm, common_bins=common_bins, kde=kde, kde_kws=kde_kws, color=color, legend=legend, estimate_kws=estimate_kws, line_kws=line_kws, **kwargs, ) else: p.plot_bivariate_histogram( common_bins=common_bins, common_norm=common_norm, thresh=thresh, pthresh=pthresh, pmax=pmax, color=color, legend=legend, cbar=cbar, cbar_ax=cbar_ax, cbar_kws=cbar_kws, estimate_kws=estimate_kws, **kwargs, ) return ax
19,212
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
kdeplot
( data=None, *, x=None, y=None, hue=None, weights=None, palette=None, hue_order=None, hue_norm=None, color=None, fill=None, multiple="layer", common_norm=True, common_grid=False, cumulative=False, bw_method="scott", bw_adjust=1, warn_singular=True, log_scale=None, levels=10, thresh=.05, gridsize=200, cut=3, clip=None, legend=True, cbar=False, cbar_ax=None, cbar_kws=None, ax=None, **kwargs, )
return ax
1,597
1,746
def kdeplot( data=None, *, x=None, y=None, hue=None, weights=None, palette=None, hue_order=None, hue_norm=None, color=None, fill=None, multiple="layer", common_norm=True, common_grid=False, cumulative=False, bw_method="scott", bw_adjust=1, warn_singular=True, log_scale=None, levels=10, thresh=.05, gridsize=200, cut=3, clip=None, legend=True, cbar=False, cbar_ax=None, cbar_kws=None, ax=None, **kwargs, ): # --- Start with backwards compatability for versions < 0.11.0 ---------------- # Handle (past) deprecation of `data2` if "data2" in kwargs: msg = "`data2` has been removed (replaced by `y`); please update your code." TypeError(msg) # Handle deprecation of `vertical` vertical = kwargs.pop("vertical", None) if vertical is not None: if vertical: action_taken = "assigning data to `y`." if x is None: data, y = y, data else: x, y = y, x else: action_taken = "assigning data to `x`." msg = textwrap.dedent(f"""\n The `vertical` parameter is deprecated; {action_taken} This will become an error in seaborn v0.13.0; please update your code. """) warnings.warn(msg, UserWarning, stacklevel=2) # Handle deprecation of `bw` bw = kwargs.pop("bw", None) if bw is not None: msg = textwrap.dedent(f"""\n The `bw` parameter is deprecated in favor of `bw_method` and `bw_adjust`. Setting `bw_method={bw}`, but please see the docs for the new parameters and update your code. This will become an error in seaborn v0.13.0. """) warnings.warn(msg, UserWarning, stacklevel=2) bw_method = bw # Handle deprecation of `kernel` if kwargs.pop("kernel", None) is not None: msg = textwrap.dedent("""\n Support for alternate kernels has been removed; using Gaussian kernel. This will become an error in seaborn v0.13.0; please update your code. """) warnings.warn(msg, UserWarning, stacklevel=2) # Handle deprecation of shade_lowest shade_lowest = kwargs.pop("shade_lowest", None) if shade_lowest is not None: if shade_lowest: thresh = 0 msg = textwrap.dedent(f"""\n `shade_lowest` has been replaced by `thresh`; setting `thresh={thresh}. This will become an error in seaborn v0.13.0; please update your code. """) warnings.warn(msg, UserWarning, stacklevel=2) # Handle "soft" deprecation of shade `shade` is not really the right # terminology here, but unlike some of the other deprecated parameters it # is probably very commonly used and much hard to remove. This is therefore # going to be a longer process where, first, `fill` will be introduced and # be used throughout the documentation. In 0.12, when kwarg-only # enforcement hits, we can remove the shade/shade_lowest out of the # function signature all together and pull them out of the kwargs. Then we # can actually fire a FutureWarning, and eventually remove. shade = kwargs.pop("shade", None) if shade is not None: fill = shade msg = textwrap.dedent(f"""\n `shade` is now deprecated in favor of `fill`; setting `fill={shade}`. This will become an error in seaborn v0.14.0; please update your code. """) warnings.warn(msg, FutureWarning, stacklevel=2) # Handle `n_levels` # This was never in the formal API but it was processed, and appeared in an # example. We can treat as an alias for `levels` now and deprecate later. levels = kwargs.pop("n_levels", levels) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # p = _DistributionPlotter( data=data, variables=_DistributionPlotter.get_semantics(locals()), ) p.map_hue(palette=palette, order=hue_order, norm=hue_norm) if ax is None: ax = plt.gca() p._attach(ax, allowed_types=["numeric", "datetime"], log_scale=log_scale) method = ax.fill_between if fill else ax.plot color = _default_color(method, hue, color, kwargs) if not p.has_xy_data: return ax # Pack the kwargs for statistics.KDE estimate_kws = dict( bw_method=bw_method, bw_adjust=bw_adjust, gridsize=gridsize, cut=cut, clip=clip, cumulative=cumulative, ) if p.univariate: plot_kws = kwargs.copy() p.plot_univariate_density( multiple=multiple, common_norm=common_norm, common_grid=common_grid, fill=fill, color=color, legend=legend, warn_singular=warn_singular, estimate_kws=estimate_kws, **plot_kws, ) else: p.plot_bivariate_density( common_norm=common_norm, fill=fill, levels=levels, thresh=thresh, legend=legend, color=color, warn_singular=warn_singular, cbar=cbar, cbar_ax=cbar_ax, cbar_kws=cbar_kws, estimate_kws=estimate_kws, **kwargs, ) return ax
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L1597-L1746
26
[ 0, 12, 13, 17, 18, 19, 20, 21, 22, 25, 28, 31, 32, 33, 34, 35, 36, 37, 41, 42, 43, 44, 45, 46, 47, 50, 51, 52, 53, 54, 55, 71, 72, 73, 74, 75, 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 ]
72
[ 14, 15, 23, 27, 56, 57, 58, 62 ]
5.333333
false
96.354167
150
13
94.666667
0
def kdeplot( data=None, *, x=None, y=None, hue=None, weights=None, palette=None, hue_order=None, hue_norm=None, color=None, fill=None, multiple="layer", common_norm=True, common_grid=False, cumulative=False, bw_method="scott", bw_adjust=1, warn_singular=True, log_scale=None, levels=10, thresh=.05, gridsize=200, cut=3, clip=None, legend=True, cbar=False, cbar_ax=None, cbar_kws=None, ax=None, **kwargs, ): # --- Start with backwards compatability for versions < 0.11.0 ---------------- # Handle (past) deprecation of `data2` if "data2" in kwargs: msg = "`data2` has been removed (replaced by `y`); please update your code." TypeError(msg) # Handle deprecation of `vertical` vertical = kwargs.pop("vertical", None) if vertical is not None: if vertical: action_taken = "assigning data to `y`." if x is None: data, y = y, data else: x, y = y, x else: action_taken = "assigning data to `x`." msg = textwrap.dedent(f"""\n The `vertical` parameter is deprecated; {action_taken} This will become an error in seaborn v0.13.0; please update your code.\n The `bw` parameter is deprecated in favor of `bw_method` and `bw_adjust`. Setting `bw_method={bw}`, but please see the docs for the new parameters and update your code. This will become an error in seaborn v0.13.0.\n Support for alternate kernels has been removed; using Gaussian kernel. This will become an error in seaborn v0.13.0; please update your code.\n `shade_lowest` has been replaced by `thresh`; setting `thresh={thresh}. This will become an error in seaborn v0.13.0; please update your code.\n `shade` is now deprecated in favor of `fill`; setting `fill={shade}`. This will become an error in seaborn v0.14.0; please update your code. """) warnings.warn(msg, FutureWarning, stacklevel=2) # Handle `n_levels` # This was never in the formal API but it was processed, and appeared in an # example. We can treat as an alias for `levels` now and deprecate later. levels = kwargs.pop("n_levels", levels) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # p = _DistributionPlotter( data=data, variables=_DistributionPlotter.get_semantics(locals()), ) p.map_hue(palette=palette, order=hue_order, norm=hue_norm) if ax is None: ax = plt.gca() p._attach(ax, allowed_types=["numeric", "datetime"], log_scale=log_scale) method = ax.fill_between if fill else ax.plot color = _default_color(method, hue, color, kwargs) if not p.has_xy_data: return ax # Pack the kwargs for statistics.KDE estimate_kws = dict( bw_method=bw_method, bw_adjust=bw_adjust, gridsize=gridsize, cut=cut, clip=clip, cumulative=cumulative, ) if p.univariate: plot_kws = kwargs.copy() p.plot_univariate_density( multiple=multiple, common_norm=common_norm, common_grid=common_grid, fill=fill, color=color, legend=legend, warn_singular=warn_singular, estimate_kws=estimate_kws, **plot_kws, ) else: p.plot_bivariate_density( common_norm=common_norm, fill=fill, levels=levels, thresh=thresh, legend=legend, color=color, warn_singular=warn_singular, cbar=cbar, cbar_ax=cbar_ax, cbar_kws=cbar_kws, estimate_kws=estimate_kws, **kwargs, ) return ax
19,213
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
ecdfplot
( data=None, *, # Vector variables x=None, y=None, hue=None, weights=None, # Computation parameters stat="proportion", complementary=False, # Hue mapping parameters palette=None, hue_order=None, hue_norm=None, # Axes information log_scale=None, legend=True, ax=None, # Other appearance keywords **kwargs, )
return ax
1,877
1,930
def ecdfplot( data=None, *, # Vector variables x=None, y=None, hue=None, weights=None, # Computation parameters stat="proportion", complementary=False, # Hue mapping parameters palette=None, hue_order=None, hue_norm=None, # Axes information log_scale=None, legend=True, ax=None, # Other appearance keywords **kwargs, ): p = _DistributionPlotter( data=data, variables=_DistributionPlotter.get_semantics(locals()) ) p.map_hue(palette=palette, order=hue_order, norm=hue_norm) # We could support other semantics (size, style) here fairly easily # But it would make distplot a bit more complicated. # It's always possible to add features like that later, so I am going to defer. # It will be even easier to wait until after there is a more general/abstract # way to go from semantic specs to artist attributes. if ax is None: ax = plt.gca() p._attach(ax, log_scale=log_scale) color = kwargs.pop("color", kwargs.pop("c", None)) kwargs["color"] = _default_color(ax.plot, hue, color, kwargs) if not p.has_xy_data: return ax # We could add this one day, but it's of dubious value if not p.univariate: raise NotImplementedError("Bivariate ECDF plots are not implemented") estimate_kws = dict( stat=stat, complementary=complementary, ) p.plot_univariate_ecdf( estimate_kws=estimate_kws, legend=legend, **kwargs, ) return ax
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L1877-L1930
26
[ 0, 13, 14, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 38, 39, 41, 42, 46, 47, 52, 53 ]
54.716981
[ 36 ]
1.886792
false
96.354167
54
4
98.113208
0
def ecdfplot( data=None, *, # Vector variables x=None, y=None, hue=None, weights=None, # Computation parameters stat="proportion", complementary=False, # Hue mapping parameters palette=None, hue_order=None, hue_norm=None, # Axes information log_scale=None, legend=True, ax=None, # Other appearance keywords **kwargs, ): p = _DistributionPlotter( data=data, variables=_DistributionPlotter.get_semantics(locals()) ) p.map_hue(palette=palette, order=hue_order, norm=hue_norm) # We could support other semantics (size, style) here fairly easily # But it would make distplot a bit more complicated. # It's always possible to add features like that later, so I am going to defer. # It will be even easier to wait until after there is a more general/abstract # way to go from semantic specs to artist attributes. if ax is None: ax = plt.gca() p._attach(ax, log_scale=log_scale) color = kwargs.pop("color", kwargs.pop("c", None)) kwargs["color"] = _default_color(ax.plot, hue, color, kwargs) if not p.has_xy_data: return ax # We could add this one day, but it's of dubious value if not p.univariate: raise NotImplementedError("Bivariate ECDF plots are not implemented") estimate_kws = dict( stat=stat, complementary=complementary, ) p.plot_univariate_ecdf( estimate_kws=estimate_kws, legend=legend, **kwargs, ) return ax
19,214
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
rugplot
( data=None, *, x=None, y=None, hue=None, height=.025, expand_margins=True, palette=None, hue_order=None, hue_norm=None, legend=True, ax=None, **kwargs )
return ax
1,989
2,066
def rugplot( data=None, *, x=None, y=None, hue=None, height=.025, expand_margins=True, palette=None, hue_order=None, hue_norm=None, legend=True, ax=None, **kwargs ): # A note: I think it would make sense to add multiple= to rugplot and allow # rugs for different hue variables to be shifted orthogonal to the data axis # But is this stacking, or dodging? # A note: if we want to add a style semantic to rugplot, # we could make an option that draws the rug using scatterplot # A note, it would also be nice to offer some kind of histogram/density # rugplot, since alpha blending doesn't work great in the large n regime # --- Start with backwards compatability for versions < 0.11.0 ---------------- a = kwargs.pop("a", None) axis = kwargs.pop("axis", None) if a is not None: data = a msg = textwrap.dedent("""\n The `a` parameter has been replaced; use `x`, `y`, and/or `data` instead. Please update your code; This will become an error in seaborn v0.13.0. """) warnings.warn(msg, UserWarning, stacklevel=2) if axis is not None: if axis == "x": x = data elif axis == "y": y = data msg = textwrap.dedent(f"""\n The `axis` parameter has been deprecated; use the `{axis}` parameter instead. Please update your code; this will become an error in seaborn v0.13.0. """) warnings.warn(msg, UserWarning, stacklevel=2) vertical = kwargs.pop("vertical", None) if vertical is not None: if vertical: action_taken = "assigning data to `y`." if x is None: data, y = y, data else: x, y = y, x else: action_taken = "assigning data to `x`." msg = textwrap.dedent(f"""\n The `vertical` parameter is deprecated; {action_taken} This will become an error in seaborn v0.13.0; please update your code. """) warnings.warn(msg, UserWarning, stacklevel=2) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # weights = None p = _DistributionPlotter( data=data, variables=_DistributionPlotter.get_semantics(locals()), ) p.map_hue(palette=palette, order=hue_order, norm=hue_norm) if ax is None: ax = plt.gca() p._attach(ax) color = kwargs.pop("color", kwargs.pop("c", None)) kwargs["color"] = _default_color(ax.plot, hue, color, kwargs) if not p.has_xy_data: return ax p.plot_rug(height, expand_margins, legend, **kwargs) return ax
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L1989-L2066
26
[ 0, 16, 17, 18, 19, 20, 21, 22, 25, 26, 27, 28, 29, 30, 31, 32, 33, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 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 ]
71.794872
[ 46, 48 ]
2.564103
false
96.354167
78
10
97.435897
0
def rugplot( data=None, *, x=None, y=None, hue=None, height=.025, expand_margins=True, palette=None, hue_order=None, hue_norm=None, legend=True, ax=None, **kwargs ): # A note: I think it would make sense to add multiple= to rugplot and allow # rugs for different hue variables to be shifted orthogonal to the data axis # But is this stacking, or dodging? # A note: if we want to add a style semantic to rugplot, # we could make an option that draws the rug using scatterplot # A note, it would also be nice to offer some kind of histogram/density # rugplot, since alpha blending doesn't work great in the large n regime # --- Start with backwards compatability for versions < 0.11.0 ---------------- a = kwargs.pop("a", None) axis = kwargs.pop("axis", None) if a is not None: data = a msg = textwrap.dedent("""\n The `a` parameter has been replaced; use `x`, `y`, and/or `data` instead. Please update your code; This will become an error in seaborn v0.13.0.\n The `axis` parameter has been deprecated; use the `{axis}` parameter instead. Please update your code; this will become an error in seaborn v0.13.0.\n The `vertical` parameter is deprecated; {action_taken} This will become an error in seaborn v0.13.0; please update your code. """) warnings.warn(msg, UserWarning, stacklevel=2) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # weights = None p = _DistributionPlotter( data=data, variables=_DistributionPlotter.get_semantics(locals()), ) p.map_hue(palette=palette, order=hue_order, norm=hue_norm) if ax is None: ax = plt.gca() p._attach(ax) color = kwargs.pop("color", kwargs.pop("c", None)) kwargs["color"] = _default_color(ax.plot, hue, color, kwargs) if not p.has_xy_data: return ax p.plot_rug(height, expand_margins, legend, **kwargs) return ax
19,215
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
displot
( data=None, *, # Vector variables x=None, y=None, hue=None, row=None, col=None, weights=None, # Other plot parameters kind="hist", rug=False, rug_kws=None, log_scale=None, legend=True, # Hue-mapping parameters palette=None, hue_order=None, hue_norm=None, color=None, # Faceting parameters col_wrap=None, row_order=None, col_order=None, height=5, aspect=1, facet_kws=None, **kwargs, )
return g
2,111
2,300
def displot( data=None, *, # Vector variables x=None, y=None, hue=None, row=None, col=None, weights=None, # Other plot parameters kind="hist", rug=False, rug_kws=None, log_scale=None, legend=True, # Hue-mapping parameters palette=None, hue_order=None, hue_norm=None, color=None, # Faceting parameters col_wrap=None, row_order=None, col_order=None, height=5, aspect=1, facet_kws=None, **kwargs, ): p = _DistributionFacetPlotter( data=data, variables=_DistributionFacetPlotter.get_semantics(locals()) ) p.map_hue(palette=palette, order=hue_order, norm=hue_norm) _check_argument("kind", ["hist", "kde", "ecdf"], kind) # --- Initialize the FacetGrid object # Check for attempt to plot onto specific axes and warn if "ax" in kwargs: msg = ( "`displot` is a figure-level function and does not accept " "the ax= parameter. You may wish to try {}plot.".format(kind) ) warnings.warn(msg, UserWarning) kwargs.pop("ax") for var in ["row", "col"]: # Handle faceting variables that lack name information if var in p.variables and p.variables[var] is None: p.variables[var] = f"_{var}_" # Adapt the plot_data dataframe for use with FacetGrid grid_data = p.plot_data.rename(columns=p.variables) grid_data = grid_data.loc[:, ~grid_data.columns.duplicated()] col_name = p.variables.get("col") row_name = p.variables.get("row") if facet_kws is None: facet_kws = {} g = FacetGrid( data=grid_data, row=row_name, col=col_name, col_wrap=col_wrap, row_order=row_order, col_order=col_order, height=height, aspect=aspect, **facet_kws, ) # Now attach the axes object to the plotter object if kind == "kde": allowed_types = ["numeric", "datetime"] else: allowed_types = None p._attach(g, allowed_types=allowed_types, log_scale=log_scale) # Check for a specification that lacks x/y data and return early if not p.has_xy_data: return g if color is None and hue is None: color = "C0" # XXX else warn if hue is not None? kwargs["legend"] = legend # --- Draw the plots if kind == "hist": hist_kws = kwargs.copy() # Extract the parameters that will go directly to Histogram estimate_defaults = {} _assign_default_kwargs(estimate_defaults, Histogram.__init__, histplot) estimate_kws = {} for key, default_val in estimate_defaults.items(): estimate_kws[key] = hist_kws.pop(key, default_val) # Handle derivative defaults if estimate_kws["discrete"] is None: estimate_kws["discrete"] = p._default_discrete() hist_kws["estimate_kws"] = estimate_kws hist_kws.setdefault("color", color) if p.univariate: _assign_default_kwargs(hist_kws, p.plot_univariate_histogram, histplot) p.plot_univariate_histogram(**hist_kws) else: _assign_default_kwargs(hist_kws, p.plot_bivariate_histogram, histplot) p.plot_bivariate_histogram(**hist_kws) elif kind == "kde": kde_kws = kwargs.copy() # Extract the parameters that will go directly to KDE estimate_defaults = {} _assign_default_kwargs(estimate_defaults, KDE.__init__, kdeplot) estimate_kws = {} for key, default_val in estimate_defaults.items(): estimate_kws[key] = kde_kws.pop(key, default_val) kde_kws["estimate_kws"] = estimate_kws kde_kws["color"] = color if p.univariate: _assign_default_kwargs(kde_kws, p.plot_univariate_density, kdeplot) p.plot_univariate_density(**kde_kws) else: _assign_default_kwargs(kde_kws, p.plot_bivariate_density, kdeplot) p.plot_bivariate_density(**kde_kws) elif kind == "ecdf": ecdf_kws = kwargs.copy() # Extract the parameters that will go directly to the estimator estimate_kws = {} estimate_defaults = {} _assign_default_kwargs(estimate_defaults, ECDF.__init__, ecdfplot) for key, default_val in estimate_defaults.items(): estimate_kws[key] = ecdf_kws.pop(key, default_val) ecdf_kws["estimate_kws"] = estimate_kws ecdf_kws["color"] = color if p.univariate: _assign_default_kwargs(ecdf_kws, p.plot_univariate_ecdf, ecdfplot) p.plot_univariate_ecdf(**ecdf_kws) else: raise NotImplementedError("Bivariate ECDF plots are not implemented") # All plot kinds can include a rug if rug: # TODO with expand_margins=True, each facet expands margins... annoying! if rug_kws is None: rug_kws = {} _assign_default_kwargs(rug_kws, p.plot_rug, rugplot) rug_kws["legend"] = False if color is not None: rug_kws["color"] = color p.plot_rug(**rug_kws) # Call FacetGrid annotation methods # Note that the legend is currently set inside the plotting method g.set_axis_labels( x_var=p.variables.get("x", g.axes.flat[0].get_xlabel()), y_var=p.variables.get("y", g.axes.flat[0].get_ylabel()), ) g.set_titles() g.tight_layout() if data is not None and (x is not None or y is not None): if not isinstance(data, pd.DataFrame): data = pd.DataFrame(data) g.data = pd.merge( data, g.data[g.data.columns.difference(data.columns)], left_index=True, right_index=True, ) else: wide_cols = { k: f"_{k}_" if v is None else v for k, v in p.variables.items() } g.data = p.plot_data.rename(columns=wide_cols) return g
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L2111-L2300
26
[ 0, 13, 14, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 57, 58, 59, 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, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 171, 172, 173, 174, 175, 176, 177, 184, 187, 188, 189 ]
77.777778
[]
0
false
96.354167
190
27
100
0
def displot( data=None, *, # Vector variables x=None, y=None, hue=None, row=None, col=None, weights=None, # Other plot parameters kind="hist", rug=False, rug_kws=None, log_scale=None, legend=True, # Hue-mapping parameters palette=None, hue_order=None, hue_norm=None, color=None, # Faceting parameters col_wrap=None, row_order=None, col_order=None, height=5, aspect=1, facet_kws=None, **kwargs, ): p = _DistributionFacetPlotter( data=data, variables=_DistributionFacetPlotter.get_semantics(locals()) ) p.map_hue(palette=palette, order=hue_order, norm=hue_norm) _check_argument("kind", ["hist", "kde", "ecdf"], kind) # --- Initialize the FacetGrid object # Check for attempt to plot onto specific axes and warn if "ax" in kwargs: msg = ( "`displot` is a figure-level function and does not accept " "the ax= parameter. You may wish to try {}plot.".format(kind) ) warnings.warn(msg, UserWarning) kwargs.pop("ax") for var in ["row", "col"]: # Handle faceting variables that lack name information if var in p.variables and p.variables[var] is None: p.variables[var] = f"_{var}_" # Adapt the plot_data dataframe for use with FacetGrid grid_data = p.plot_data.rename(columns=p.variables) grid_data = grid_data.loc[:, ~grid_data.columns.duplicated()] col_name = p.variables.get("col") row_name = p.variables.get("row") if facet_kws is None: facet_kws = {} g = FacetGrid( data=grid_data, row=row_name, col=col_name, col_wrap=col_wrap, row_order=row_order, col_order=col_order, height=height, aspect=aspect, **facet_kws, ) # Now attach the axes object to the plotter object if kind == "kde": allowed_types = ["numeric", "datetime"] else: allowed_types = None p._attach(g, allowed_types=allowed_types, log_scale=log_scale) # Check for a specification that lacks x/y data and return early if not p.has_xy_data: return g if color is None and hue is None: color = "C0" # XXX else warn if hue is not None? kwargs["legend"] = legend # --- Draw the plots if kind == "hist": hist_kws = kwargs.copy() # Extract the parameters that will go directly to Histogram estimate_defaults = {} _assign_default_kwargs(estimate_defaults, Histogram.__init__, histplot) estimate_kws = {} for key, default_val in estimate_defaults.items(): estimate_kws[key] = hist_kws.pop(key, default_val) # Handle derivative defaults if estimate_kws["discrete"] is None: estimate_kws["discrete"] = p._default_discrete() hist_kws["estimate_kws"] = estimate_kws hist_kws.setdefault("color", color) if p.univariate: _assign_default_kwargs(hist_kws, p.plot_univariate_histogram, histplot) p.plot_univariate_histogram(**hist_kws) else: _assign_default_kwargs(hist_kws, p.plot_bivariate_histogram, histplot) p.plot_bivariate_histogram(**hist_kws) elif kind == "kde": kde_kws = kwargs.copy() # Extract the parameters that will go directly to KDE estimate_defaults = {} _assign_default_kwargs(estimate_defaults, KDE.__init__, kdeplot) estimate_kws = {} for key, default_val in estimate_defaults.items(): estimate_kws[key] = kde_kws.pop(key, default_val) kde_kws["estimate_kws"] = estimate_kws kde_kws["color"] = color if p.univariate: _assign_default_kwargs(kde_kws, p.plot_univariate_density, kdeplot) p.plot_univariate_density(**kde_kws) else: _assign_default_kwargs(kde_kws, p.plot_bivariate_density, kdeplot) p.plot_bivariate_density(**kde_kws) elif kind == "ecdf": ecdf_kws = kwargs.copy() # Extract the parameters that will go directly to the estimator estimate_kws = {} estimate_defaults = {} _assign_default_kwargs(estimate_defaults, ECDF.__init__, ecdfplot) for key, default_val in estimate_defaults.items(): estimate_kws[key] = ecdf_kws.pop(key, default_val) ecdf_kws["estimate_kws"] = estimate_kws ecdf_kws["color"] = color if p.univariate: _assign_default_kwargs(ecdf_kws, p.plot_univariate_ecdf, ecdfplot) p.plot_univariate_ecdf(**ecdf_kws) else: raise NotImplementedError("Bivariate ECDF plots are not implemented") # All plot kinds can include a rug if rug: # TODO with expand_margins=True, each facet expands margins... annoying! if rug_kws is None: rug_kws = {} _assign_default_kwargs(rug_kws, p.plot_rug, rugplot) rug_kws["legend"] = False if color is not None: rug_kws["color"] = color p.plot_rug(**rug_kws) # Call FacetGrid annotation methods # Note that the legend is currently set inside the plotting method g.set_axis_labels( x_var=p.variables.get("x", g.axes.flat[0].get_xlabel()), y_var=p.variables.get("y", g.axes.flat[0].get_ylabel()), ) g.set_titles() g.tight_layout() if data is not None and (x is not None or y is not None): if not isinstance(data, pd.DataFrame): data = pd.DataFrame(data) g.data = pd.merge( data, g.data[g.data.columns.difference(data.columns)], left_index=True, right_index=True, ) else: wide_cols = { k: f"_{k}_" if v is None else v for k, v in p.variables.items() } g.data = p.plot_data.rename(columns=wide_cols) return g
19,216
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_freedman_diaconis_bins
(a)
Calculate number of hist bins using Freedman-Diaconis rule.
Calculate number of hist bins using Freedman-Diaconis rule.
2,390
2,402
def _freedman_diaconis_bins(a): """Calculate number of hist bins using Freedman-Diaconis rule.""" # From https://stats.stackexchange.com/questions/798/ a = np.asarray(a) if len(a) < 2: return 1 iqr = np.subtract.reduce(np.nanpercentile(a, [75, 25])) h = 2 * iqr / (len(a) ** (1 / 3)) # fall back to sqrt(a) bins if iqr is 0 if h == 0: return int(np.sqrt(a.size)) else: return int(np.ceil((a.max() - a.min()) / h))
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L2390-L2402
26
[ 0, 1, 2, 3, 4, 6, 7, 8, 9, 11, 12 ]
84.615385
[ 5, 10 ]
15.384615
false
96.354167
13
3
84.615385
1
def _freedman_diaconis_bins(a): # From https://stats.stackexchange.com/questions/798/ a = np.asarray(a) if len(a) < 2: return 1 iqr = np.subtract.reduce(np.nanpercentile(a, [75, 25])) h = 2 * iqr / (len(a) ** (1 / 3)) # fall back to sqrt(a) bins if iqr is 0 if h == 0: return int(np.sqrt(a.size)) else: return int(np.ceil((a.max() - a.min()) / h))
19,217
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
distplot
(a=None, bins=None, hist=True, kde=True, rug=False, fit=None, hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None, color=None, vertical=False, norm_hist=False, axlabel=None, label=None, ax=None, x=None)
return ax
DEPRECATED This function has been deprecated and will be removed in seaborn v0.14.0. It has been replaced by :func:`histplot` and :func:`displot`, two functions with a modern API and many more capabilities. For a guide to updating, please see this notebook: https://gist.github.com/mwaskom/de44147ed2974457ad6372750bbe5751
DEPRECATED
2,405
2,546
def distplot(a=None, bins=None, hist=True, kde=True, rug=False, fit=None, hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None, color=None, vertical=False, norm_hist=False, axlabel=None, label=None, ax=None, x=None): """ DEPRECATED This function has been deprecated and will be removed in seaborn v0.14.0. It has been replaced by :func:`histplot` and :func:`displot`, two functions with a modern API and many more capabilities. For a guide to updating, please see this notebook: https://gist.github.com/mwaskom/de44147ed2974457ad6372750bbe5751 """ if kde and not hist: axes_level_suggestion = ( "`kdeplot` (an axes-level function for kernel density plots)" ) else: axes_level_suggestion = ( "`histplot` (an axes-level function for histograms)" ) msg = textwrap.dedent(f""" `distplot` is a deprecated function and will be removed in seaborn v0.14.0. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or {axes_level_suggestion}. For a guide to updating your code to use the new functions, please see https://gist.github.com/mwaskom/de44147ed2974457ad6372750bbe5751 """) warnings.warn(msg, UserWarning, stacklevel=2) if ax is None: ax = plt.gca() # Intelligently label the support axis label_ax = bool(axlabel) if axlabel is None and hasattr(a, "name"): axlabel = a.name if axlabel is not None: label_ax = True # Support new-style API if x is not None: a = x # Make a a 1-d float array a = np.asarray(a, float) if a.ndim > 1: a = a.squeeze() # Drop null values from array a = remove_na(a) # Decide if the hist is normed norm_hist = norm_hist or kde or (fit is not None) # Handle dictionary defaults hist_kws = {} if hist_kws is None else hist_kws.copy() kde_kws = {} if kde_kws is None else kde_kws.copy() rug_kws = {} if rug_kws is None else rug_kws.copy() fit_kws = {} if fit_kws is None else fit_kws.copy() # Get the color from the current color cycle if color is None: if vertical: line, = ax.plot(0, a.mean()) else: line, = ax.plot(a.mean(), 0) color = line.get_color() line.remove() # Plug the label into the right kwarg dictionary if label is not None: if hist: hist_kws["label"] = label elif kde: kde_kws["label"] = label elif rug: rug_kws["label"] = label elif fit: fit_kws["label"] = label if hist: if bins is None: bins = min(_freedman_diaconis_bins(a), 50) hist_kws.setdefault("alpha", 0.4) hist_kws.setdefault("density", norm_hist) orientation = "horizontal" if vertical else "vertical" hist_color = hist_kws.pop("color", color) ax.hist(a, bins, orientation=orientation, color=hist_color, **hist_kws) if hist_color != color: hist_kws["color"] = hist_color axis = "y" if vertical else "x" if kde: kde_color = kde_kws.pop("color", color) kdeplot(**{axis: a}, ax=ax, color=kde_color, **kde_kws) if kde_color != color: kde_kws["color"] = kde_color if rug: rug_color = rug_kws.pop("color", color) rugplot(**{axis: a}, ax=ax, color=rug_color, **rug_kws) if rug_color != color: rug_kws["color"] = rug_color if fit is not None: def pdf(x): return fit.pdf(x, *params) fit_color = fit_kws.pop("color", "#282828") gridsize = fit_kws.pop("gridsize", 200) cut = fit_kws.pop("cut", 3) clip = fit_kws.pop("clip", (-np.inf, np.inf)) bw = gaussian_kde(a).scotts_factor() * a.std(ddof=1) x = _kde_support(a, bw, gridsize, cut, clip) params = fit.fit(a) y = pdf(x) if vertical: x, y = y, x ax.plot(x, y, color=fit_color, **fit_kws) if fit_color != "#282828": fit_kws["color"] = fit_color if label_ax: if vertical: ax.set_ylabel(axlabel) else: ax.set_xlabel(axlabel) return ax
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L2405-L2546
26
[ 0, 16, 17, 18, 22, 25, 26, 27, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 52, 53, 54, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 101, 102, 103, 104, 105, 106, 107, 109, 110, 111, 112, 113, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 131, 132, 134, 135, 136, 137, 138, 139, 140, 141 ]
69.014085
[ 50, 55, 80, 81, 82, 83, 84, 85, 86, 87, 100, 108, 114, 130, 133 ]
10.56338
false
96.354167
142
31
89.43662
9
def distplot(a=None, bins=None, hist=True, kde=True, rug=False, fit=None, hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None, color=None, vertical=False, norm_hist=False, axlabel=None, label=None, ax=None, x=None): if kde and not hist: axes_level_suggestion = ( "`kdeplot` (an axes-level function for kernel density plots)" ) else: axes_level_suggestion = ( "`histplot` (an axes-level function for histograms)" ) msg = textwrap.dedent(f""" `distplot` is a deprecated function and will be removed in seaborn v0.14.0. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or {axes_level_suggestion}. For a guide to updating your code to use the new functions, please see https://gist.github.com/mwaskom/de44147ed2974457ad6372750bbe5751 """) warnings.warn(msg, UserWarning, stacklevel=2) if ax is None: ax = plt.gca() # Intelligently label the support axis label_ax = bool(axlabel) if axlabel is None and hasattr(a, "name"): axlabel = a.name if axlabel is not None: label_ax = True # Support new-style API if x is not None: a = x # Make a a 1-d float array a = np.asarray(a, float) if a.ndim > 1: a = a.squeeze() # Drop null values from array a = remove_na(a) # Decide if the hist is normed norm_hist = norm_hist or kde or (fit is not None) # Handle dictionary defaults hist_kws = {} if hist_kws is None else hist_kws.copy() kde_kws = {} if kde_kws is None else kde_kws.copy() rug_kws = {} if rug_kws is None else rug_kws.copy() fit_kws = {} if fit_kws is None else fit_kws.copy() # Get the color from the current color cycle if color is None: if vertical: line, = ax.plot(0, a.mean()) else: line, = ax.plot(a.mean(), 0) color = line.get_color() line.remove() # Plug the label into the right kwarg dictionary if label is not None: if hist: hist_kws["label"] = label elif kde: kde_kws["label"] = label elif rug: rug_kws["label"] = label elif fit: fit_kws["label"] = label if hist: if bins is None: bins = min(_freedman_diaconis_bins(a), 50) hist_kws.setdefault("alpha", 0.4) hist_kws.setdefault("density", norm_hist) orientation = "horizontal" if vertical else "vertical" hist_color = hist_kws.pop("color", color) ax.hist(a, bins, orientation=orientation, color=hist_color, **hist_kws) if hist_color != color: hist_kws["color"] = hist_color axis = "y" if vertical else "x" if kde: kde_color = kde_kws.pop("color", color) kdeplot(**{axis: a}, ax=ax, color=kde_color, **kde_kws) if kde_color != color: kde_kws["color"] = kde_color if rug: rug_color = rug_kws.pop("color", color) rugplot(**{axis: a}, ax=ax, color=rug_color, **rug_kws) if rug_color != color: rug_kws["color"] = rug_color if fit is not None: def pdf(x): return fit.pdf(x, *params) fit_color = fit_kws.pop("color", "#282828") gridsize = fit_kws.pop("gridsize", 200) cut = fit_kws.pop("cut", 3) clip = fit_kws.pop("clip", (-np.inf, np.inf)) bw = gaussian_kde(a).scotts_factor() * a.std(ddof=1) x = _kde_support(a, bw, gridsize, cut, clip) params = fit.fit(a) y = pdf(x) if vertical: x, y = y, x ax.plot(x, y, color=fit_color, **fit_kws) if fit_color != "#282828": fit_kws["color"] = fit_color if label_ax: if vertical: ax.set_ylabel(axlabel) else: ax.set_xlabel(axlabel) return ax
19,218
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter.__init__
( self, data=None, variables={}, )
107
113
def __init__( self, data=None, variables={}, ): super().__init__(data=data, variables=variables)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L107-L113
26
[ 0, 5, 6 ]
42.857143
[]
0
false
96.354167
7
1
100
0
def __init__( self, data=None, variables={}, ): super().__init__(data=data, variables=variables)
19,219
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter.univariate
(self)
return bool({"x", "y"} - set(self.variables))
Return True if only x or y are used.
Return True if only x or y are used.
116
122
def univariate(self): """Return True if only x or y are used.""" # TODO this could go down to core, but putting it here now. # We'd want to be conceptually clear that univariate only applies # to x/y and not to other semantics, which can exist. # We haven't settled on a good conceptual name for x/y. return bool({"x", "y"} - set(self.variables))
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L116-L122
26
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
96.354167
7
1
100
1
def univariate(self): # TODO this could go down to core, but putting it here now. # We'd want to be conceptually clear that univariate only applies # to x/y and not to other semantics, which can exist. # We haven't settled on a good conceptual name for x/y. return bool({"x", "y"} - set(self.variables))
19,220
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter.data_variable
(self)
return {"x", "y"}.intersection(self.variables).pop()
Return the variable with data for univariate plots.
Return the variable with data for univariate plots.
125
130
def data_variable(self): """Return the variable with data for univariate plots.""" # TODO This could also be in core, but it should have a better name. if not self.univariate: raise AttributeError("This is not a univariate plot") return {"x", "y"}.intersection(self.variables).pop()
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L125-L130
26
[ 0, 1, 2, 3, 5 ]
83.333333
[ 4 ]
16.666667
false
96.354167
6
2
83.333333
1
def data_variable(self): # TODO This could also be in core, but it should have a better name. if not self.univariate: raise AttributeError("This is not a univariate plot") return {"x", "y"}.intersection(self.variables).pop()
19,221
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter.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.
133
136
def has_xy_data(self): """Return True at least one of x or y is defined.""" # TODO see above points about where this should go return bool({"x", "y"} & set(self.variables))
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L133-L136
26
[ 0, 1, 2, 3 ]
100
[]
0
true
96.354167
4
1
100
1
def has_xy_data(self): # TODO see above points about where this should go return bool({"x", "y"} & set(self.variables))
19,222
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter._add_legend
( self, ax_obj, artist, fill, element, multiple, alpha, artist_kws, legend_kws, )
Add artists that reflect semantic mappings and put then in a legend.
Add artists that reflect semantic mappings and put then in a legend.
138
171
def _add_legend( self, ax_obj, artist, fill, element, multiple, alpha, artist_kws, legend_kws, ): """Add artists that reflect semantic mappings and put then in a legend.""" # TODO note that this doesn't handle numeric mappings like the relational plots handles = [] labels = [] for level in self._hue_map.levels: color = self._hue_map(level) kws = self._artist_kws( artist_kws, fill, element, multiple, color, alpha ) # color gets added to the kws to workaround an issue with barplot's color # cycle integration but it causes problems in this context where we are # setting artist properties directly, so pop it off here if "facecolor" in kws: kws.pop("color", None) handles.append(artist(**kws)) labels.append(level) if isinstance(ax_obj, mpl.axes.Axes): ax_obj.legend(handles, labels, title=self.variables["hue"], **legend_kws) else: # i.e. a FacetGrid. TODO make this better legend_data = dict(zip(labels, handles)) ax_obj.add_legend( legend_data, title=self.variables["hue"], label_order=self.var_levels["hue"], **legend_kws )
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L138-L171
26
[ 0, 5, 6, 7, 8, 9, 10, 11, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28 ]
55.882353
[]
0
false
96.354167
34
4
100
1
def _add_legend( self, ax_obj, artist, fill, element, multiple, alpha, artist_kws, legend_kws, ): # TODO note that this doesn't handle numeric mappings like the relational plots handles = [] labels = [] for level in self._hue_map.levels: color = self._hue_map(level) kws = self._artist_kws( artist_kws, fill, element, multiple, color, alpha ) # color gets added to the kws to workaround an issue with barplot's color # cycle integration but it causes problems in this context where we are # setting artist properties directly, so pop it off here if "facecolor" in kws: kws.pop("color", None) handles.append(artist(**kws)) labels.append(level) if isinstance(ax_obj, mpl.axes.Axes): ax_obj.legend(handles, labels, title=self.variables["hue"], **legend_kws) else: # i.e. a FacetGrid. TODO make this better legend_data = dict(zip(labels, handles)) ax_obj.add_legend( legend_data, title=self.variables["hue"], label_order=self.var_levels["hue"], **legend_kws )
19,223
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter._artist_kws
(self, kws, fill, element, multiple, color, alpha)
return kws
Handle differences between artists in filled/unfilled plots.
Handle differences between artists in filled/unfilled plots.
173
194
def _artist_kws(self, kws, fill, element, multiple, color, alpha): """Handle differences between artists in filled/unfilled plots.""" kws = kws.copy() if fill: kws = _normalize_kwargs(kws, mpl.collections.PolyCollection) kws.setdefault("facecolor", to_rgba(color, alpha)) if element == "bars": # Make bar() interface with property cycle correctly # https://github.com/matplotlib/matplotlib/issues/19385 kws["color"] = "none" if multiple in ["stack", "fill"] or element == "bars": kws.setdefault("edgecolor", mpl.rcParams["patch.edgecolor"]) else: kws.setdefault("edgecolor", to_rgba(color, 1)) elif element == "bars": kws["facecolor"] = "none" kws["edgecolor"] = to_rgba(color, alpha) else: kws["color"] = to_rgba(color, alpha) return kws
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L173-L194
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.354167
22
6
100
1
def _artist_kws(self, kws, fill, element, multiple, color, alpha): kws = kws.copy() if fill: kws = _normalize_kwargs(kws, mpl.collections.PolyCollection) kws.setdefault("facecolor", to_rgba(color, alpha)) if element == "bars": # Make bar() interface with property cycle correctly # https://github.com/matplotlib/matplotlib/issues/19385 kws["color"] = "none" if multiple in ["stack", "fill"] or element == "bars": kws.setdefault("edgecolor", mpl.rcParams["patch.edgecolor"]) else: kws.setdefault("edgecolor", to_rgba(color, 1)) elif element == "bars": kws["facecolor"] = "none" kws["edgecolor"] = to_rgba(color, alpha) else: kws["color"] = to_rgba(color, alpha) return kws
19,224
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter._quantile_to_level
(self, data, quantile)
return levels
Return data levels corresponding to quantile cuts of mass.
Return data levels corresponding to quantile cuts of mass.
196
204
def _quantile_to_level(self, data, quantile): """Return data levels corresponding to quantile cuts of mass.""" isoprop = np.asarray(quantile) values = np.ravel(data) sorted_values = np.sort(values)[::-1] normalized_values = np.cumsum(sorted_values) / values.sum() idx = np.searchsorted(normalized_values, 1 - isoprop) levels = np.take(sorted_values, idx, mode="clip") return levels
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L196-L204
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
96.354167
9
1
100
1
def _quantile_to_level(self, data, quantile): isoprop = np.asarray(quantile) values = np.ravel(data) sorted_values = np.sort(values)[::-1] normalized_values = np.cumsum(sorted_values) / values.sum() idx = np.searchsorted(normalized_values, 1 - isoprop) levels = np.take(sorted_values, idx, mode="clip") return levels
19,225
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter._cmap_from_color
(self, color)
return mpl.colors.ListedColormap(colors[::-1])
Return a sequential colormap given a color seed.
Return a sequential colormap given a color seed.
206
218
def _cmap_from_color(self, color): """Return a sequential colormap given a color seed.""" # Like so much else here, this is broadly useful, but keeping it # in this class to signify that I haven't thought overly hard about it... r, g, b, _ = to_rgba(color) h, s, _ = husl.rgb_to_husl(r, g, b) xx = np.linspace(-1, 1, int(1.15 * 256))[:256] ramp = np.zeros((256, 3)) ramp[:, 0] = h ramp[:, 1] = s * np.cos(xx) ramp[:, 2] = np.linspace(35, 80, 256) colors = np.clip([husl.husl_to_rgb(*hsl) for hsl in ramp], 0, 1) return mpl.colors.ListedColormap(colors[::-1])
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L206-L218
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
96.354167
13
2
100
1
def _cmap_from_color(self, color): # Like so much else here, this is broadly useful, but keeping it # in this class to signify that I haven't thought overly hard about it... r, g, b, _ = to_rgba(color) h, s, _ = husl.rgb_to_husl(r, g, b) xx = np.linspace(-1, 1, int(1.15 * 256))[:256] ramp = np.zeros((256, 3)) ramp[:, 0] = h ramp[:, 1] = s * np.cos(xx) ramp[:, 2] = np.linspace(35, 80, 256) colors = np.clip([husl.husl_to_rgb(*hsl) for hsl in ramp], 0, 1) return mpl.colors.ListedColormap(colors[::-1])
19,226
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter._default_discrete
(self)
return discrete
Find default values for discrete hist estimation based on variable type.
Find default values for discrete hist estimation based on variable type.
220
228
def _default_discrete(self): """Find default values for discrete hist estimation based on variable type.""" if self.univariate: discrete = self.var_types[self.data_variable] == "categorical" else: discrete_x = self.var_types["x"] == "categorical" discrete_y = self.var_types["y"] == "categorical" discrete = discrete_x, discrete_y return discrete
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L220-L228
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
96.354167
9
2
100
1
def _default_discrete(self): if self.univariate: discrete = self.var_types[self.data_variable] == "categorical" else: discrete_x = self.var_types["x"] == "categorical" discrete_y = self.var_types["y"] == "categorical" discrete = discrete_x, discrete_y return discrete
19,227
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter._resolve_multiple
(self, curves, multiple)
return curves, baselines
Modify the density data structure to handle multiple densities.
Modify the density data structure to handle multiple densities.
230
295
def _resolve_multiple(self, curves, multiple): """Modify the density data structure to handle multiple densities.""" # Default baselines have all densities starting at 0 baselines = {k: np.zeros_like(v) for k, v in curves.items()} # TODO we should have some central clearinghouse for checking if any # "grouping" (terminnology?) semantics have been assigned if "hue" not in self.variables: return curves, baselines if multiple in ("stack", "fill"): # Setting stack or fill means that the curves share a # support grid / set of bin edges, so we can make a dataframe # Reverse the column order to plot from top to bottom curves = pd.DataFrame(curves).iloc[:, ::-1] # Find column groups that are nested within col/row variables column_groups = {} for i, keyd in enumerate(map(dict, curves.columns)): facet_key = keyd.get("col", None), keyd.get("row", None) column_groups.setdefault(facet_key, []) column_groups[facet_key].append(i) baselines = curves.copy() for col_idxs in column_groups.values(): cols = curves.columns[col_idxs] norm_constant = curves[cols].sum(axis="columns") # Take the cumulative sum to stack curves[cols] = curves[cols].cumsum(axis="columns") # Normalize by row sum to fill if multiple == "fill": curves[cols] = curves[cols].div(norm_constant, axis="index") # Define where each segment starts baselines[cols] = curves[cols].shift(1, axis=1).fillna(0) if multiple == "dodge": # Account for the unique semantic (non-faceting) levels # This will require rethiniking if we add other semantics! hue_levels = self.var_levels["hue"] n = len(hue_levels) for key in curves: level = dict(key)["hue"] hist = curves[key].reset_index(name="heights") level_idx = hue_levels.index(level) if self._log_scaled(self.data_variable): log_min = np.log10(hist["edges"]) log_max = np.log10(hist["edges"] + hist["widths"]) log_width = (log_max - log_min) / n new_min = np.power(10, log_min + level_idx * log_width) new_max = np.power(10, log_min + (level_idx + 1) * log_width) hist["widths"] = new_max - new_min hist["edges"] = new_min else: hist["widths"] /= n hist["edges"] += level_idx * hist["widths"] curves[key] = hist.set_index(["edges", "widths"])["heights"] return curves, baselines
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L230-L295
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 ]
100
[]
0
true
96.354167
66
9
100
1
def _resolve_multiple(self, curves, multiple): # Default baselines have all densities starting at 0 baselines = {k: np.zeros_like(v) for k, v in curves.items()} # TODO we should have some central clearinghouse for checking if any # "grouping" (terminnology?) semantics have been assigned if "hue" not in self.variables: return curves, baselines if multiple in ("stack", "fill"): # Setting stack or fill means that the curves share a # support grid / set of bin edges, so we can make a dataframe # Reverse the column order to plot from top to bottom curves = pd.DataFrame(curves).iloc[:, ::-1] # Find column groups that are nested within col/row variables column_groups = {} for i, keyd in enumerate(map(dict, curves.columns)): facet_key = keyd.get("col", None), keyd.get("row", None) column_groups.setdefault(facet_key, []) column_groups[facet_key].append(i) baselines = curves.copy() for col_idxs in column_groups.values(): cols = curves.columns[col_idxs] norm_constant = curves[cols].sum(axis="columns") # Take the cumulative sum to stack curves[cols] = curves[cols].cumsum(axis="columns") # Normalize by row sum to fill if multiple == "fill": curves[cols] = curves[cols].div(norm_constant, axis="index") # Define where each segment starts baselines[cols] = curves[cols].shift(1, axis=1).fillna(0) if multiple == "dodge": # Account for the unique semantic (non-faceting) levels # This will require rethiniking if we add other semantics! hue_levels = self.var_levels["hue"] n = len(hue_levels) for key in curves: level = dict(key)["hue"] hist = curves[key].reset_index(name="heights") level_idx = hue_levels.index(level) if self._log_scaled(self.data_variable): log_min = np.log10(hist["edges"]) log_max = np.log10(hist["edges"] + hist["widths"]) log_width = (log_max - log_min) / n new_min = np.power(10, log_min + level_idx * log_width) new_max = np.power(10, log_min + (level_idx + 1) * log_width) hist["widths"] = new_max - new_min hist["edges"] = new_min else: hist["widths"] /= n hist["edges"] += level_idx * hist["widths"] curves[key] = hist.set_index(["edges", "widths"])["heights"] return curves, baselines
19,228
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter._compute_univariate_density
( self, data_variable, common_norm, common_grid, estimate_kws, log_scale, warn_singular=True, )
return densities
301
373
def _compute_univariate_density( self, data_variable, common_norm, common_grid, estimate_kws, log_scale, warn_singular=True, ): # Initialize the estimator object estimator = KDE(**estimate_kws) if set(self.variables) - {"x", "y"}: if common_grid: all_observations = self.comp_data.dropna() estimator.define_support(all_observations[data_variable]) else: common_norm = False all_data = self.plot_data.dropna() if common_norm and "weights" in all_data: whole_weight = all_data["weights"].sum() else: whole_weight = len(all_data) densities = {} for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True): # Extract the data points from this sub set and remove nulls observations = sub_data[data_variable] # Extract the weights for this subset of observations if "weights" in self.variables: weights = sub_data["weights"] part_weight = weights.sum() else: weights = None part_weight = len(sub_data) # Estimate the density of observations at this level variance = np.nan_to_num(observations.var()) singular = len(observations) < 2 or math.isclose(variance, 0) try: if not singular: # Convoluted approach needed because numerical failures # can manifest in a few different ways. density, support = estimator(observations, weights=weights) except np.linalg.LinAlgError: singular = True if singular: msg = ( "Dataset has 0 variance; skipping density estimate. " "Pass `warn_singular=False` to disable this warning." ) if warn_singular: warnings.warn(msg, UserWarning, stacklevel=4) continue if log_scale: support = np.power(10, support) # Apply a scaling factor so that the integral over all subsets is 1 if common_norm: density *= part_weight / whole_weight # Store the density for this level key = tuple(sub_vars.items()) densities[key] = pd.Series(density, index=support) return densities
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L301-L373
26
[ 0, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72 ]
79.452055
[]
0
false
96.354167
73
14
100
0
def _compute_univariate_density( self, data_variable, common_norm, common_grid, estimate_kws, log_scale, warn_singular=True, ): # Initialize the estimator object estimator = KDE(**estimate_kws) if set(self.variables) - {"x", "y"}: if common_grid: all_observations = self.comp_data.dropna() estimator.define_support(all_observations[data_variable]) else: common_norm = False all_data = self.plot_data.dropna() if common_norm and "weights" in all_data: whole_weight = all_data["weights"].sum() else: whole_weight = len(all_data) densities = {} for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True): # Extract the data points from this sub set and remove nulls observations = sub_data[data_variable] # Extract the weights for this subset of observations if "weights" in self.variables: weights = sub_data["weights"] part_weight = weights.sum() else: weights = None part_weight = len(sub_data) # Estimate the density of observations at this level variance = np.nan_to_num(observations.var()) singular = len(observations) < 2 or math.isclose(variance, 0) try: if not singular: # Convoluted approach needed because numerical failures # can manifest in a few different ways. density, support = estimator(observations, weights=weights) except np.linalg.LinAlgError: singular = True if singular: msg = ( "Dataset has 0 variance; skipping density estimate. " "Pass `warn_singular=False` to disable this warning." ) if warn_singular: warnings.warn(msg, UserWarning, stacklevel=4) continue if log_scale: support = np.power(10, support) # Apply a scaling factor so that the integral over all subsets is 1 if common_norm: density *= part_weight / whole_weight # Store the density for this level key = tuple(sub_vars.items()) densities[key] = pd.Series(density, index=support) return densities
19,229
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter.plot_univariate_histogram
( self, multiple, element, fill, common_norm, common_bins, shrink, kde, kde_kws, color, legend, line_kws, estimate_kws, **plot_kws, )
379
742
def plot_univariate_histogram( self, multiple, element, fill, common_norm, common_bins, shrink, kde, kde_kws, color, legend, line_kws, estimate_kws, **plot_kws, ): # -- Default keyword dicts kde_kws = {} if kde_kws is None else kde_kws.copy() line_kws = {} if line_kws is None else line_kws.copy() estimate_kws = {} if estimate_kws is None else estimate_kws.copy() # -- Input checking _check_argument("multiple", ["layer", "stack", "fill", "dodge"], multiple) _check_argument("element", ["bars", "step", "poly"], element) auto_bins_with_weights = ( "weights" in self.variables and estimate_kws["bins"] == "auto" and estimate_kws["binwidth"] is None and not estimate_kws["discrete"] ) if auto_bins_with_weights: msg = ( "`bins` cannot be 'auto' when using weights. " "Setting `bins=10`, but you will likely want to adjust." ) warnings.warn(msg, UserWarning) estimate_kws["bins"] = 10 # Simplify downstream code if we are not normalizing if estimate_kws["stat"] == "count": common_norm = False orient = self.data_variable # Now initialize the Histogram estimator estimator = Hist(**estimate_kws) histograms = {} # Do pre-compute housekeeping related to multiple groups all_data = self.comp_data.dropna() all_weights = all_data.get("weights", None) multiple_histograms = set(self.variables) - {"x", "y"} if multiple_histograms: if common_bins: bin_kws = estimator._define_bin_params(all_data, orient, None) else: common_norm = False if common_norm and all_weights is not None: whole_weight = all_weights.sum() else: whole_weight = len(all_data) # Estimate the smoothed kernel densities, for use later if kde: # TODO alternatively, clip at min/max bins? kde_kws.setdefault("cut", 0) kde_kws["cumulative"] = estimate_kws["cumulative"] log_scale = self._log_scaled(self.data_variable) densities = self._compute_univariate_density( self.data_variable, common_norm, common_bins, kde_kws, log_scale, warn_singular=False, ) # First pass through the data to compute the histograms for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True): # Prepare the relevant data key = tuple(sub_vars.items()) orient = self.data_variable if "weights" in self.variables: sub_data["weight"] = sub_data.pop("weights") part_weight = sub_data["weight"].sum() else: part_weight = len(sub_data) # Do the histogram computation if not (multiple_histograms and common_bins): bin_kws = estimator._define_bin_params(sub_data, orient, None) res = estimator._normalize(estimator._eval(sub_data, orient, bin_kws)) heights = res[estimator.stat].to_numpy() widths = res["space"].to_numpy() edges = res[orient].to_numpy() - widths / 2 # Rescale the smoothed curve to match the histogram if kde and key in densities: density = densities[key] if estimator.cumulative: hist_norm = heights.max() else: hist_norm = (heights * widths).sum() densities[key] *= hist_norm # Convert edges back to original units for plotting if self._log_scaled(self.data_variable): widths = np.power(10, edges + widths) - np.power(10, edges) edges = np.power(10, edges) # Pack the histogram data and metadata together edges = edges + (1 - shrink) / 2 * widths widths *= shrink index = pd.MultiIndex.from_arrays([ pd.Index(edges, name="edges"), pd.Index(widths, name="widths"), ]) hist = pd.Series(heights, index=index, name="heights") # Apply scaling to normalize across groups if common_norm: hist *= part_weight / whole_weight # Store the finalized histogram data for future plotting histograms[key] = hist # Modify the histogram and density data to resolve multiple groups histograms, baselines = self._resolve_multiple(histograms, multiple) if kde: densities, _ = self._resolve_multiple( densities, None if multiple == "dodge" else multiple ) # Set autoscaling-related meta sticky_stat = (0, 1) if multiple == "fill" else (0, np.inf) if multiple == "fill": # Filled plots should not have any margins bin_vals = histograms.index.to_frame() edges = bin_vals["edges"] widths = bin_vals["widths"] sticky_data = ( edges.min(), edges.max() + widths.loc[edges.idxmax()] ) else: sticky_data = [] # --- Handle default visual attributes # Note: default linewidth is determined after plotting # Default alpha should depend on other parameters if fill: # Note: will need to account for other grouping semantics if added if "hue" in self.variables and multiple == "layer": default_alpha = .5 if element == "bars" else .25 elif kde: default_alpha = .5 else: default_alpha = .75 else: default_alpha = 1 alpha = plot_kws.pop("alpha", default_alpha) # TODO make parameter? hist_artists = [] # Go back through the dataset and draw the plots for sub_vars, _ in self.iter_data("hue", reverse=True): key = tuple(sub_vars.items()) hist = histograms[key].rename("heights").reset_index() bottom = np.asarray(baselines[key]) ax = self._get_axes(sub_vars) # Define the matplotlib attributes that depend on semantic mapping if "hue" in self.variables: sub_color = self._hue_map(sub_vars["hue"]) else: sub_color = color artist_kws = self._artist_kws( plot_kws, fill, element, multiple, sub_color, alpha ) if element == "bars": # Use matplotlib bar plotting plot_func = ax.bar if self.data_variable == "x" else ax.barh artists = plot_func( hist["edges"], hist["heights"] - bottom, hist["widths"], bottom, align="edge", **artist_kws, ) for bar in artists: if self.data_variable == "x": bar.sticky_edges.x[:] = sticky_data bar.sticky_edges.y[:] = sticky_stat else: bar.sticky_edges.x[:] = sticky_stat bar.sticky_edges.y[:] = sticky_data hist_artists.extend(artists) else: # Use either fill_between or plot to draw hull of histogram if element == "step": final = hist.iloc[-1] x = np.append(hist["edges"], final["edges"] + final["widths"]) y = np.append(hist["heights"], final["heights"]) b = np.append(bottom, bottom[-1]) if self.data_variable == "x": step = "post" drawstyle = "steps-post" else: step = "post" # fillbetweenx handles mapping internally drawstyle = "steps-pre" elif element == "poly": x = hist["edges"] + hist["widths"] / 2 y = hist["heights"] b = bottom step = None drawstyle = None if self.data_variable == "x": if fill: artist = ax.fill_between(x, b, y, step=step, **artist_kws) else: artist, = ax.plot(x, y, drawstyle=drawstyle, **artist_kws) artist.sticky_edges.x[:] = sticky_data artist.sticky_edges.y[:] = sticky_stat else: if fill: artist = ax.fill_betweenx(x, b, y, step=step, **artist_kws) else: artist, = ax.plot(y, x, drawstyle=drawstyle, **artist_kws) artist.sticky_edges.x[:] = sticky_stat artist.sticky_edges.y[:] = sticky_data hist_artists.append(artist) if kde: # Add in the density curves try: density = densities[key] except KeyError: continue support = density.index if "x" in self.variables: line_args = support, density sticky_x, sticky_y = None, (0, np.inf) else: line_args = density, support sticky_x, sticky_y = (0, np.inf), None line_kws["color"] = to_rgba(sub_color, 1) line, = ax.plot( *line_args, **line_kws, ) if sticky_x is not None: line.sticky_edges.x[:] = sticky_x if sticky_y is not None: line.sticky_edges.y[:] = sticky_y if element == "bars" and "linewidth" not in plot_kws: # Now we handle linewidth, which depends on the scaling of the plot # We will base everything on the minimum bin width hist_metadata = pd.concat([ # Use .items for generality over dict or df h.index.to_frame() for _, h in histograms.items() ]).reset_index(drop=True) thin_bar_idx = hist_metadata["widths"].idxmin() binwidth = hist_metadata.loc[thin_bar_idx, "widths"] left_edge = hist_metadata.loc[thin_bar_idx, "edges"] # Set initial value default_linewidth = math.inf # Loop through subsets based only on facet variables for sub_vars, _ in self.iter_data(): ax = self._get_axes(sub_vars) # Needed in some cases to get valid transforms. # Innocuous in other cases? ax.autoscale_view() # Convert binwidth from data coordinates to pixels pts_x, pts_y = 72 / ax.figure.dpi * abs( ax.transData.transform([left_edge + binwidth] * 2) - ax.transData.transform([left_edge] * 2) ) if self.data_variable == "x": binwidth_points = pts_x else: binwidth_points = pts_y # The relative size of the lines depends on the appearance # This is a provisional value and may need more tweaking default_linewidth = min(.1 * binwidth_points, default_linewidth) # Set the attributes for bar in hist_artists: # Don't let the lines get too thick max_linewidth = bar.get_linewidth() if not fill: max_linewidth *= 1.5 linewidth = min(default_linewidth, max_linewidth) # If not filling, don't let lines disappear if not fill: min_linewidth = .5 linewidth = max(linewidth, min_linewidth) bar.set_linewidth(linewidth) # --- Finalize the plot ---- # Axis labels ax = self.ax if self.ax is not None else self.facets.axes.flat[0] default_x = default_y = "" if self.data_variable == "x": default_y = estimator.stat.capitalize() if self.data_variable == "y": default_x = estimator.stat.capitalize() self._add_axis_labels(ax, default_x, default_y) # Legend for semantic variables if "hue" in self.variables and legend: if fill or element == "bars": artist = partial(mpl.patches.Patch) else: artist = partial(mpl.lines.Line2D, [], []) ax_obj = self.ax if self.ax is not None else self.facets self._add_legend( ax_obj, artist, fill, element, multiple, alpha, plot_kws, {}, )
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L379-L742
26
[ 0, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 32, 33, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 59, 60, 61, 62, 64, 65, 66, 67, 68, 69, 70, 71, 72, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 139, 140, 141, 142, 143, 144, 145, 146, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 165, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 185, 186, 187, 190, 191, 192, 193, 194, 195, 196, 204, 205, 206, 207, 208, 210, 211, 212, 213, 214, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 245, 246, 247, 249, 250, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 272, 273, 274, 275, 276, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 315, 316, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 359, 360, 361 ]
78.296703
[ 106, 358 ]
0.549451
false
96.354167
364
56
99.450549
0
def plot_univariate_histogram( self, multiple, element, fill, common_norm, common_bins, shrink, kde, kde_kws, color, legend, line_kws, estimate_kws, **plot_kws, ): # -- Default keyword dicts kde_kws = {} if kde_kws is None else kde_kws.copy() line_kws = {} if line_kws is None else line_kws.copy() estimate_kws = {} if estimate_kws is None else estimate_kws.copy() # -- Input checking _check_argument("multiple", ["layer", "stack", "fill", "dodge"], multiple) _check_argument("element", ["bars", "step", "poly"], element) auto_bins_with_weights = ( "weights" in self.variables and estimate_kws["bins"] == "auto" and estimate_kws["binwidth"] is None and not estimate_kws["discrete"] ) if auto_bins_with_weights: msg = ( "`bins` cannot be 'auto' when using weights. " "Setting `bins=10`, but you will likely want to adjust." ) warnings.warn(msg, UserWarning) estimate_kws["bins"] = 10 # Simplify downstream code if we are not normalizing if estimate_kws["stat"] == "count": common_norm = False orient = self.data_variable # Now initialize the Histogram estimator estimator = Hist(**estimate_kws) histograms = {} # Do pre-compute housekeeping related to multiple groups all_data = self.comp_data.dropna() all_weights = all_data.get("weights", None) multiple_histograms = set(self.variables) - {"x", "y"} if multiple_histograms: if common_bins: bin_kws = estimator._define_bin_params(all_data, orient, None) else: common_norm = False if common_norm and all_weights is not None: whole_weight = all_weights.sum() else: whole_weight = len(all_data) # Estimate the smoothed kernel densities, for use later if kde: # TODO alternatively, clip at min/max bins? kde_kws.setdefault("cut", 0) kde_kws["cumulative"] = estimate_kws["cumulative"] log_scale = self._log_scaled(self.data_variable) densities = self._compute_univariate_density( self.data_variable, common_norm, common_bins, kde_kws, log_scale, warn_singular=False, ) # First pass through the data to compute the histograms for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True): # Prepare the relevant data key = tuple(sub_vars.items()) orient = self.data_variable if "weights" in self.variables: sub_data["weight"] = sub_data.pop("weights") part_weight = sub_data["weight"].sum() else: part_weight = len(sub_data) # Do the histogram computation if not (multiple_histograms and common_bins): bin_kws = estimator._define_bin_params(sub_data, orient, None) res = estimator._normalize(estimator._eval(sub_data, orient, bin_kws)) heights = res[estimator.stat].to_numpy() widths = res["space"].to_numpy() edges = res[orient].to_numpy() - widths / 2 # Rescale the smoothed curve to match the histogram if kde and key in densities: density = densities[key] if estimator.cumulative: hist_norm = heights.max() else: hist_norm = (heights * widths).sum() densities[key] *= hist_norm # Convert edges back to original units for plotting if self._log_scaled(self.data_variable): widths = np.power(10, edges + widths) - np.power(10, edges) edges = np.power(10, edges) # Pack the histogram data and metadata together edges = edges + (1 - shrink) / 2 * widths widths *= shrink index = pd.MultiIndex.from_arrays([ pd.Index(edges, name="edges"), pd.Index(widths, name="widths"), ]) hist = pd.Series(heights, index=index, name="heights") # Apply scaling to normalize across groups if common_norm: hist *= part_weight / whole_weight # Store the finalized histogram data for future plotting histograms[key] = hist # Modify the histogram and density data to resolve multiple groups histograms, baselines = self._resolve_multiple(histograms, multiple) if kde: densities, _ = self._resolve_multiple( densities, None if multiple == "dodge" else multiple ) # Set autoscaling-related meta sticky_stat = (0, 1) if multiple == "fill" else (0, np.inf) if multiple == "fill": # Filled plots should not have any margins bin_vals = histograms.index.to_frame() edges = bin_vals["edges"] widths = bin_vals["widths"] sticky_data = ( edges.min(), edges.max() + widths.loc[edges.idxmax()] ) else: sticky_data = [] # --- Handle default visual attributes # Note: default linewidth is determined after plotting # Default alpha should depend on other parameters if fill: # Note: will need to account for other grouping semantics if added if "hue" in self.variables and multiple == "layer": default_alpha = .5 if element == "bars" else .25 elif kde: default_alpha = .5 else: default_alpha = .75 else: default_alpha = 1 alpha = plot_kws.pop("alpha", default_alpha) # TODO make parameter? hist_artists = [] # Go back through the dataset and draw the plots for sub_vars, _ in self.iter_data("hue", reverse=True): key = tuple(sub_vars.items()) hist = histograms[key].rename("heights").reset_index() bottom = np.asarray(baselines[key]) ax = self._get_axes(sub_vars) # Define the matplotlib attributes that depend on semantic mapping if "hue" in self.variables: sub_color = self._hue_map(sub_vars["hue"]) else: sub_color = color artist_kws = self._artist_kws( plot_kws, fill, element, multiple, sub_color, alpha ) if element == "bars": # Use matplotlib bar plotting plot_func = ax.bar if self.data_variable == "x" else ax.barh artists = plot_func( hist["edges"], hist["heights"] - bottom, hist["widths"], bottom, align="edge", **artist_kws, ) for bar in artists: if self.data_variable == "x": bar.sticky_edges.x[:] = sticky_data bar.sticky_edges.y[:] = sticky_stat else: bar.sticky_edges.x[:] = sticky_stat bar.sticky_edges.y[:] = sticky_data hist_artists.extend(artists) else: # Use either fill_between or plot to draw hull of histogram if element == "step": final = hist.iloc[-1] x = np.append(hist["edges"], final["edges"] + final["widths"]) y = np.append(hist["heights"], final["heights"]) b = np.append(bottom, bottom[-1]) if self.data_variable == "x": step = "post" drawstyle = "steps-post" else: step = "post" # fillbetweenx handles mapping internally drawstyle = "steps-pre" elif element == "poly": x = hist["edges"] + hist["widths"] / 2 y = hist["heights"] b = bottom step = None drawstyle = None if self.data_variable == "x": if fill: artist = ax.fill_between(x, b, y, step=step, **artist_kws) else: artist, = ax.plot(x, y, drawstyle=drawstyle, **artist_kws) artist.sticky_edges.x[:] = sticky_data artist.sticky_edges.y[:] = sticky_stat else: if fill: artist = ax.fill_betweenx(x, b, y, step=step, **artist_kws) else: artist, = ax.plot(y, x, drawstyle=drawstyle, **artist_kws) artist.sticky_edges.x[:] = sticky_stat artist.sticky_edges.y[:] = sticky_data hist_artists.append(artist) if kde: # Add in the density curves try: density = densities[key] except KeyError: continue support = density.index if "x" in self.variables: line_args = support, density sticky_x, sticky_y = None, (0, np.inf) else: line_args = density, support sticky_x, sticky_y = (0, np.inf), None line_kws["color"] = to_rgba(sub_color, 1) line, = ax.plot( *line_args, **line_kws, ) if sticky_x is not None: line.sticky_edges.x[:] = sticky_x if sticky_y is not None: line.sticky_edges.y[:] = sticky_y if element == "bars" and "linewidth" not in plot_kws: # Now we handle linewidth, which depends on the scaling of the plot # We will base everything on the minimum bin width hist_metadata = pd.concat([ # Use .items for generality over dict or df h.index.to_frame() for _, h in histograms.items() ]).reset_index(drop=True) thin_bar_idx = hist_metadata["widths"].idxmin() binwidth = hist_metadata.loc[thin_bar_idx, "widths"] left_edge = hist_metadata.loc[thin_bar_idx, "edges"] # Set initial value default_linewidth = math.inf # Loop through subsets based only on facet variables for sub_vars, _ in self.iter_data(): ax = self._get_axes(sub_vars) # Needed in some cases to get valid transforms. # Innocuous in other cases? ax.autoscale_view() # Convert binwidth from data coordinates to pixels pts_x, pts_y = 72 / ax.figure.dpi * abs( ax.transData.transform([left_edge + binwidth] * 2) - ax.transData.transform([left_edge] * 2) ) if self.data_variable == "x": binwidth_points = pts_x else: binwidth_points = pts_y # The relative size of the lines depends on the appearance # This is a provisional value and may need more tweaking default_linewidth = min(.1 * binwidth_points, default_linewidth) # Set the attributes for bar in hist_artists: # Don't let the lines get too thick max_linewidth = bar.get_linewidth() if not fill: max_linewidth *= 1.5 linewidth = min(default_linewidth, max_linewidth) # If not filling, don't let lines disappear if not fill: min_linewidth = .5 linewidth = max(linewidth, min_linewidth) bar.set_linewidth(linewidth) # --- Finalize the plot ---- # Axis labels ax = self.ax if self.ax is not None else self.facets.axes.flat[0] default_x = default_y = "" if self.data_variable == "x": default_y = estimator.stat.capitalize() if self.data_variable == "y": default_x = estimator.stat.capitalize() self._add_axis_labels(ax, default_x, default_y) # Legend for semantic variables if "hue" in self.variables and legend: if fill or element == "bars": artist = partial(mpl.patches.Patch) else: artist = partial(mpl.lines.Line2D, [], []) ax_obj = self.ax if self.ax is not None else self.facets self._add_legend( ax_obj, artist, fill, element, multiple, alpha, plot_kws, {}, )
19,230
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter.plot_bivariate_histogram
( self, common_bins, common_norm, thresh, pthresh, pmax, color, legend, cbar, cbar_ax, cbar_kws, estimate_kws, **plot_kws, )
744
899
def plot_bivariate_histogram( self, common_bins, common_norm, thresh, pthresh, pmax, color, legend, cbar, cbar_ax, cbar_kws, estimate_kws, **plot_kws, ): # Default keyword dicts cbar_kws = {} if cbar_kws is None else cbar_kws.copy() # Now initialize the Histogram estimator estimator = Histogram(**estimate_kws) # Do pre-compute housekeeping related to multiple groups if set(self.variables) - {"x", "y"}: all_data = self.comp_data.dropna() if common_bins: estimator.define_bin_params( all_data["x"], all_data["y"], all_data.get("weights", None), ) else: common_norm = False # -- Determine colormap threshold and norm based on the full data full_heights = [] for _, sub_data in self.iter_data(from_comp_data=True): sub_heights, _ = estimator( sub_data["x"], sub_data["y"], sub_data.get("weights", None) ) full_heights.append(sub_heights) common_color_norm = not set(self.variables) - {"x", "y"} or common_norm if pthresh is not None and common_color_norm: thresh = self._quantile_to_level(full_heights, pthresh) plot_kws.setdefault("vmin", 0) if common_color_norm: if pmax is not None: vmax = self._quantile_to_level(full_heights, pmax) else: vmax = plot_kws.pop("vmax", max(map(np.max, full_heights))) else: vmax = None # Get a default color # (We won't follow the color cycle here, as multiple plots are unlikely) if color is None: color = "C0" # --- Loop over data (subsets) and draw the histograms for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True): if sub_data.empty: continue # Do the histogram computation heights, (x_edges, y_edges) = estimator( sub_data["x"], sub_data["y"], weights=sub_data.get("weights", None), ) # Check for log scaling on the data axis if self._log_scaled("x"): x_edges = np.power(10, x_edges) if self._log_scaled("y"): y_edges = np.power(10, y_edges) # Apply scaling to normalize across groups if estimator.stat != "count" and common_norm: heights *= len(sub_data) / len(all_data) # Define the specific kwargs for this artist artist_kws = plot_kws.copy() if "hue" in self.variables: color = self._hue_map(sub_vars["hue"]) cmap = self._cmap_from_color(color) artist_kws["cmap"] = cmap else: cmap = artist_kws.pop("cmap", None) if isinstance(cmap, str): cmap = color_palette(cmap, as_cmap=True) elif cmap is None: cmap = self._cmap_from_color(color) artist_kws["cmap"] = cmap # Set the upper norm on the colormap if not common_color_norm and pmax is not None: vmax = self._quantile_to_level(heights, pmax) if vmax is not None: artist_kws["vmax"] = vmax # Make cells at or below the threshold transparent if not common_color_norm and pthresh: thresh = self._quantile_to_level(heights, pthresh) if thresh is not None: heights = np.ma.masked_less_equal(heights, thresh) # Get the axes for this plot ax = self._get_axes(sub_vars) # pcolormesh is going to turn the grid off, but we want to keep it # I'm not sure if there's a better way to get the grid state x_grid = any([l.get_visible() for l in ax.xaxis.get_gridlines()]) y_grid = any([l.get_visible() for l in ax.yaxis.get_gridlines()]) mesh = ax.pcolormesh( x_edges, y_edges, heights.T, **artist_kws, ) # pcolormesh sets sticky edges, but we only want them if not thresholding if thresh is not None: mesh.sticky_edges.x[:] = [] mesh.sticky_edges.y[:] = [] # Add an optional colorbar # Note, we want to improve this. When hue is used, it will stack # multiple colorbars with redundant ticks in an ugly way. # But it's going to take some work to have multiple colorbars that # share ticks nicely. if cbar: ax.figure.colorbar(mesh, cbar_ax, ax, **cbar_kws) # Reset the grid state if x_grid: ax.grid(True, axis="x") if y_grid: ax.grid(True, axis="y") # --- Finalize the plot ax = self.ax if self.ax is not None else self.facets.axes.flat[0] self._add_axis_labels(ax) if "hue" in self.variables and legend: # TODO if possible, I would like to move the contour # intensity information into the legend too and label the # iso proportions rather than the raw density values artist_kws = {} artist = partial(mpl.patches.Patch) ax_obj = self.ax if self.ax is not None else self.facets self._add_legend( ax_obj, artist, True, False, "layer", 1, artist_kws, {}, )
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L744-L899
26
[ 0, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 26, 27, 28, 29, 30, 31, 32, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 47, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 62, 63, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 87, 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, 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 ]
77.564103
[ 60, 88 ]
1.282051
false
96.354167
156
33
98.717949
0
def plot_bivariate_histogram( self, common_bins, common_norm, thresh, pthresh, pmax, color, legend, cbar, cbar_ax, cbar_kws, estimate_kws, **plot_kws, ): # Default keyword dicts cbar_kws = {} if cbar_kws is None else cbar_kws.copy() # Now initialize the Histogram estimator estimator = Histogram(**estimate_kws) # Do pre-compute housekeeping related to multiple groups if set(self.variables) - {"x", "y"}: all_data = self.comp_data.dropna() if common_bins: estimator.define_bin_params( all_data["x"], all_data["y"], all_data.get("weights", None), ) else: common_norm = False # -- Determine colormap threshold and norm based on the full data full_heights = [] for _, sub_data in self.iter_data(from_comp_data=True): sub_heights, _ = estimator( sub_data["x"], sub_data["y"], sub_data.get("weights", None) ) full_heights.append(sub_heights) common_color_norm = not set(self.variables) - {"x", "y"} or common_norm if pthresh is not None and common_color_norm: thresh = self._quantile_to_level(full_heights, pthresh) plot_kws.setdefault("vmin", 0) if common_color_norm: if pmax is not None: vmax = self._quantile_to_level(full_heights, pmax) else: vmax = plot_kws.pop("vmax", max(map(np.max, full_heights))) else: vmax = None # Get a default color # (We won't follow the color cycle here, as multiple plots are unlikely) if color is None: color = "C0" # --- Loop over data (subsets) and draw the histograms for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True): if sub_data.empty: continue # Do the histogram computation heights, (x_edges, y_edges) = estimator( sub_data["x"], sub_data["y"], weights=sub_data.get("weights", None), ) # Check for log scaling on the data axis if self._log_scaled("x"): x_edges = np.power(10, x_edges) if self._log_scaled("y"): y_edges = np.power(10, y_edges) # Apply scaling to normalize across groups if estimator.stat != "count" and common_norm: heights *= len(sub_data) / len(all_data) # Define the specific kwargs for this artist artist_kws = plot_kws.copy() if "hue" in self.variables: color = self._hue_map(sub_vars["hue"]) cmap = self._cmap_from_color(color) artist_kws["cmap"] = cmap else: cmap = artist_kws.pop("cmap", None) if isinstance(cmap, str): cmap = color_palette(cmap, as_cmap=True) elif cmap is None: cmap = self._cmap_from_color(color) artist_kws["cmap"] = cmap # Set the upper norm on the colormap if not common_color_norm and pmax is not None: vmax = self._quantile_to_level(heights, pmax) if vmax is not None: artist_kws["vmax"] = vmax # Make cells at or below the threshold transparent if not common_color_norm and pthresh: thresh = self._quantile_to_level(heights, pthresh) if thresh is not None: heights = np.ma.masked_less_equal(heights, thresh) # Get the axes for this plot ax = self._get_axes(sub_vars) # pcolormesh is going to turn the grid off, but we want to keep it # I'm not sure if there's a better way to get the grid state x_grid = any([l.get_visible() for l in ax.xaxis.get_gridlines()]) y_grid = any([l.get_visible() for l in ax.yaxis.get_gridlines()]) mesh = ax.pcolormesh( x_edges, y_edges, heights.T, **artist_kws, ) # pcolormesh sets sticky edges, but we only want them if not thresholding if thresh is not None: mesh.sticky_edges.x[:] = [] mesh.sticky_edges.y[:] = [] # Add an optional colorbar # Note, we want to improve this. When hue is used, it will stack # multiple colorbars with redundant ticks in an ugly way. # But it's going to take some work to have multiple colorbars that # share ticks nicely. if cbar: ax.figure.colorbar(mesh, cbar_ax, ax, **cbar_kws) # Reset the grid state if x_grid: ax.grid(True, axis="x") if y_grid: ax.grid(True, axis="y") # --- Finalize the plot ax = self.ax if self.ax is not None else self.facets.axes.flat[0] self._add_axis_labels(ax) if "hue" in self.variables and legend: # TODO if possible, I would like to move the contour # intensity information into the legend too and label the # iso proportions rather than the raw density values artist_kws = {} artist = partial(mpl.patches.Patch) ax_obj = self.ax if self.ax is not None else self.facets self._add_legend( ax_obj, artist, True, False, "layer", 1, artist_kws, {}, )
19,231
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter.plot_univariate_density
( self, multiple, common_norm, common_grid, warn_singular, fill, color, legend, estimate_kws, **plot_kws, )
901
1,034
def plot_univariate_density( self, multiple, common_norm, common_grid, warn_singular, fill, color, legend, estimate_kws, **plot_kws, ): # Handle conditional defaults if fill is None: fill = multiple in ("stack", "fill") # Preprocess the matplotlib keyword dictionaries if fill: artist = mpl.collections.PolyCollection else: artist = mpl.lines.Line2D plot_kws = _normalize_kwargs(plot_kws, artist) # Input checking _check_argument("multiple", ["layer", "stack", "fill"], multiple) # Always share the evaluation grid when stacking subsets = bool(set(self.variables) - {"x", "y"}) if subsets and multiple in ("stack", "fill"): common_grid = True # Check if the data axis is log scaled log_scale = self._log_scaled(self.data_variable) # Do the computation densities = self._compute_univariate_density( self.data_variable, common_norm, common_grid, estimate_kws, log_scale, warn_singular, ) # Adjust densities based on the `multiple` rule densities, baselines = self._resolve_multiple(densities, multiple) # Control the interaction with autoscaling by defining sticky_edges # i.e. we don't want autoscale margins below the density curve sticky_density = (0, 1) if multiple == "fill" else (0, np.inf) if multiple == "fill": # Filled plots should not have any margins sticky_support = densities.index.min(), densities.index.max() else: sticky_support = [] if fill: if multiple == "layer": default_alpha = .25 else: default_alpha = .75 else: default_alpha = 1 alpha = plot_kws.pop("alpha", default_alpha) # TODO make parameter? # Now iterate through the subsets and draw the densities # We go backwards so stacked densities read from top-to-bottom for sub_vars, _ in self.iter_data("hue", reverse=True): # Extract the support grid and density curve for this level key = tuple(sub_vars.items()) try: density = densities[key] except KeyError: continue support = density.index fill_from = baselines[key] ax = self._get_axes(sub_vars) if "hue" in self.variables: sub_color = self._hue_map(sub_vars["hue"]) else: sub_color = color artist_kws = self._artist_kws( plot_kws, fill, False, multiple, sub_color, alpha ) # Either plot a curve with observation values on the x axis if "x" in self.variables: if fill: artist = ax.fill_between(support, fill_from, density, **artist_kws) else: artist, = ax.plot(support, density, **artist_kws) artist.sticky_edges.x[:] = sticky_support artist.sticky_edges.y[:] = sticky_density # Or plot a curve with observation values on the y axis else: if fill: artist = ax.fill_betweenx(support, fill_from, density, **artist_kws) else: artist, = ax.plot(density, support, **artist_kws) artist.sticky_edges.x[:] = sticky_density artist.sticky_edges.y[:] = sticky_support # --- Finalize the plot ---- ax = self.ax if self.ax is not None else self.facets.axes.flat[0] default_x = default_y = "" if self.data_variable == "x": default_y = "Density" if self.data_variable == "y": default_x = "Density" self._add_axis_labels(ax, default_x, default_y) if "hue" in self.variables and legend: if fill: artist = partial(mpl.patches.Patch) else: artist = partial(mpl.lines.Line2D, [], []) ax_obj = self.ax if self.ax is not None else self.facets self._add_legend( ax_obj, artist, fill, False, multiple, alpha, plot_kws, {}, )
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L901-L1034
26
[ 0, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 62, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 85, 86, 87, 91, 92, 93, 94, 95, 96, 98, 99, 100, 101, 102, 103, 105, 106, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 128, 129, 130, 131 ]
74.626866
[]
0
false
96.354167
134
19
100
0
def plot_univariate_density( self, multiple, common_norm, common_grid, warn_singular, fill, color, legend, estimate_kws, **plot_kws, ): # Handle conditional defaults if fill is None: fill = multiple in ("stack", "fill") # Preprocess the matplotlib keyword dictionaries if fill: artist = mpl.collections.PolyCollection else: artist = mpl.lines.Line2D plot_kws = _normalize_kwargs(plot_kws, artist) # Input checking _check_argument("multiple", ["layer", "stack", "fill"], multiple) # Always share the evaluation grid when stacking subsets = bool(set(self.variables) - {"x", "y"}) if subsets and multiple in ("stack", "fill"): common_grid = True # Check if the data axis is log scaled log_scale = self._log_scaled(self.data_variable) # Do the computation densities = self._compute_univariate_density( self.data_variable, common_norm, common_grid, estimate_kws, log_scale, warn_singular, ) # Adjust densities based on the `multiple` rule densities, baselines = self._resolve_multiple(densities, multiple) # Control the interaction with autoscaling by defining sticky_edges # i.e. we don't want autoscale margins below the density curve sticky_density = (0, 1) if multiple == "fill" else (0, np.inf) if multiple == "fill": # Filled plots should not have any margins sticky_support = densities.index.min(), densities.index.max() else: sticky_support = [] if fill: if multiple == "layer": default_alpha = .25 else: default_alpha = .75 else: default_alpha = 1 alpha = plot_kws.pop("alpha", default_alpha) # TODO make parameter? # Now iterate through the subsets and draw the densities # We go backwards so stacked densities read from top-to-bottom for sub_vars, _ in self.iter_data("hue", reverse=True): # Extract the support grid and density curve for this level key = tuple(sub_vars.items()) try: density = densities[key] except KeyError: continue support = density.index fill_from = baselines[key] ax = self._get_axes(sub_vars) if "hue" in self.variables: sub_color = self._hue_map(sub_vars["hue"]) else: sub_color = color artist_kws = self._artist_kws( plot_kws, fill, False, multiple, sub_color, alpha ) # Either plot a curve with observation values on the x axis if "x" in self.variables: if fill: artist = ax.fill_between(support, fill_from, density, **artist_kws) else: artist, = ax.plot(support, density, **artist_kws) artist.sticky_edges.x[:] = sticky_support artist.sticky_edges.y[:] = sticky_density # Or plot a curve with observation values on the y axis else: if fill: artist = ax.fill_betweenx(support, fill_from, density, **artist_kws) else: artist, = ax.plot(density, support, **artist_kws) artist.sticky_edges.x[:] = sticky_density artist.sticky_edges.y[:] = sticky_support # --- Finalize the plot ---- ax = self.ax if self.ax is not None else self.facets.axes.flat[0] default_x = default_y = "" if self.data_variable == "x": default_y = "Density" if self.data_variable == "y": default_x = "Density" self._add_axis_labels(ax, default_x, default_y) if "hue" in self.variables and legend: if fill: artist = partial(mpl.patches.Patch) else: artist = partial(mpl.lines.Line2D, [], []) ax_obj = self.ax if self.ax is not None else self.facets self._add_legend( ax_obj, artist, fill, False, multiple, alpha, plot_kws, {}, )
19,232
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter.plot_bivariate_density
( self, common_norm, fill, levels, thresh, color, legend, cbar, warn_singular, cbar_ax, cbar_kws, estimate_kws, **contour_kws, )
1,036
1,220
def plot_bivariate_density( self, common_norm, fill, levels, thresh, color, legend, cbar, warn_singular, cbar_ax, cbar_kws, estimate_kws, **contour_kws, ): contour_kws = contour_kws.copy() estimator = KDE(**estimate_kws) if not set(self.variables) - {"x", "y"}: common_norm = False all_data = self.plot_data.dropna() # Loop through the subsets and estimate the KDEs densities, supports = {}, {} for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True): # Extract the data points from this sub set observations = sub_data[["x", "y"]] min_variance = observations.var().fillna(0).min() observations = observations["x"], observations["y"] # Extract the weights for this subset of observations if "weights" in self.variables: weights = sub_data["weights"] else: weights = None # Estimate the density of observations at this level singular = math.isclose(min_variance, 0) try: if not singular: density, support = estimator(*observations, weights=weights) except np.linalg.LinAlgError: # Testing for 0 variance doesn't catch all cases where scipy raises, # but we can also get a ValueError, so we need this convoluted approach singular = True if singular: msg = ( "KDE cannot be estimated (0 variance or perfect covariance). " "Pass `warn_singular=False` to disable this warning." ) if warn_singular: warnings.warn(msg, UserWarning, stacklevel=3) continue # Transform the support grid back to the original scale xx, yy = support if self._log_scaled("x"): xx = np.power(10, xx) if self._log_scaled("y"): yy = np.power(10, yy) support = xx, yy # Apply a scaling factor so that the integral over all subsets is 1 if common_norm: density *= len(sub_data) / len(all_data) key = tuple(sub_vars.items()) densities[key] = density supports[key] = support # Define a grid of iso-proportion levels if thresh is None: thresh = 0 if isinstance(levels, Number): levels = np.linspace(thresh, 1, levels) else: if min(levels) < 0 or max(levels) > 1: raise ValueError("levels must be in [0, 1]") # Transform from iso-proportions to iso-densities if common_norm: common_levels = self._quantile_to_level( list(densities.values()), levels, ) draw_levels = {k: common_levels for k in densities} else: draw_levels = { k: self._quantile_to_level(d, levels) for k, d in densities.items() } # Define the coloring of the contours if "hue" in self.variables: for param in ["cmap", "colors"]: if param in contour_kws: msg = f"{param} parameter ignored when using hue mapping." warnings.warn(msg, UserWarning) contour_kws.pop(param) else: # Work out a default coloring of the contours coloring_given = set(contour_kws) & {"cmap", "colors"} if fill and not coloring_given: cmap = self._cmap_from_color(color) contour_kws["cmap"] = cmap if not fill and not coloring_given: contour_kws["colors"] = [color] # Use our internal colormap lookup cmap = contour_kws.pop("cmap", None) if isinstance(cmap, str): cmap = color_palette(cmap, as_cmap=True) if cmap is not None: contour_kws["cmap"] = cmap # Loop through the subsets again and plot the data for sub_vars, _ in self.iter_data("hue"): if "hue" in sub_vars: color = self._hue_map(sub_vars["hue"]) if fill: contour_kws["cmap"] = self._cmap_from_color(color) else: contour_kws["colors"] = [color] ax = self._get_axes(sub_vars) # Choose the function to plot with # TODO could add a pcolormesh based option as well # Which would look something like element="raster" if fill: contour_func = ax.contourf else: contour_func = ax.contour key = tuple(sub_vars.items()) if key not in densities: continue density = densities[key] xx, yy = supports[key] label = contour_kws.pop("label", None) cset = contour_func( xx, yy, density, levels=draw_levels[key], **contour_kws, ) if "hue" not in self.variables: cset.collections[0].set_label(label) # Add a color bar representing the contour heights # Note: this shows iso densities, not iso proportions # See more notes in histplot about how this could be improved if cbar: cbar_kws = {} if cbar_kws is None else cbar_kws ax.figure.colorbar(cset, cbar_ax, ax, **cbar_kws) # --- Finalize the plot ax = self.ax if self.ax is not None else self.facets.axes.flat[0] self._add_axis_labels(ax) if "hue" in self.variables and legend: # TODO if possible, I would like to move the contour # intensity information into the legend too and label the # iso proportions rather than the raw density values artist_kws = {} if fill: artist = partial(mpl.patches.Patch) else: artist = partial(mpl.lines.Line2D, [], []) ax_obj = self.ax if self.ax is not None else self.facets self._add_legend( ax_obj, artist, fill, False, "layer", 1, artist_kws, {}, )
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L1036-L1220
26
[ 0, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 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, 82, 83, 84, 85, 86, 87, 90, 92, 97, 98, 99, 100, 101, 102, 103, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 129, 130, 131, 132, 133, 134, 135, 136, 137, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 179, 180, 181, 182 ]
79.459459
[ 117 ]
0.540541
false
96.354167
185
35
99.459459
0
def plot_bivariate_density( self, common_norm, fill, levels, thresh, color, legend, cbar, warn_singular, cbar_ax, cbar_kws, estimate_kws, **contour_kws, ): contour_kws = contour_kws.copy() estimator = KDE(**estimate_kws) if not set(self.variables) - {"x", "y"}: common_norm = False all_data = self.plot_data.dropna() # Loop through the subsets and estimate the KDEs densities, supports = {}, {} for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True): # Extract the data points from this sub set observations = sub_data[["x", "y"]] min_variance = observations.var().fillna(0).min() observations = observations["x"], observations["y"] # Extract the weights for this subset of observations if "weights" in self.variables: weights = sub_data["weights"] else: weights = None # Estimate the density of observations at this level singular = math.isclose(min_variance, 0) try: if not singular: density, support = estimator(*observations, weights=weights) except np.linalg.LinAlgError: # Testing for 0 variance doesn't catch all cases where scipy raises, # but we can also get a ValueError, so we need this convoluted approach singular = True if singular: msg = ( "KDE cannot be estimated (0 variance or perfect covariance). " "Pass `warn_singular=False` to disable this warning." ) if warn_singular: warnings.warn(msg, UserWarning, stacklevel=3) continue # Transform the support grid back to the original scale xx, yy = support if self._log_scaled("x"): xx = np.power(10, xx) if self._log_scaled("y"): yy = np.power(10, yy) support = xx, yy # Apply a scaling factor so that the integral over all subsets is 1 if common_norm: density *= len(sub_data) / len(all_data) key = tuple(sub_vars.items()) densities[key] = density supports[key] = support # Define a grid of iso-proportion levels if thresh is None: thresh = 0 if isinstance(levels, Number): levels = np.linspace(thresh, 1, levels) else: if min(levels) < 0 or max(levels) > 1: raise ValueError("levels must be in [0, 1]") # Transform from iso-proportions to iso-densities if common_norm: common_levels = self._quantile_to_level( list(densities.values()), levels, ) draw_levels = {k: common_levels for k in densities} else: draw_levels = { k: self._quantile_to_level(d, levels) for k, d in densities.items() } # Define the coloring of the contours if "hue" in self.variables: for param in ["cmap", "colors"]: if param in contour_kws: msg = f"{param} parameter ignored when using hue mapping." warnings.warn(msg, UserWarning) contour_kws.pop(param) else: # Work out a default coloring of the contours coloring_given = set(contour_kws) & {"cmap", "colors"} if fill and not coloring_given: cmap = self._cmap_from_color(color) contour_kws["cmap"] = cmap if not fill and not coloring_given: contour_kws["colors"] = [color] # Use our internal colormap lookup cmap = contour_kws.pop("cmap", None) if isinstance(cmap, str): cmap = color_palette(cmap, as_cmap=True) if cmap is not None: contour_kws["cmap"] = cmap # Loop through the subsets again and plot the data for sub_vars, _ in self.iter_data("hue"): if "hue" in sub_vars: color = self._hue_map(sub_vars["hue"]) if fill: contour_kws["cmap"] = self._cmap_from_color(color) else: contour_kws["colors"] = [color] ax = self._get_axes(sub_vars) # Choose the function to plot with # TODO could add a pcolormesh based option as well # Which would look something like element="raster" if fill: contour_func = ax.contourf else: contour_func = ax.contour key = tuple(sub_vars.items()) if key not in densities: continue density = densities[key] xx, yy = supports[key] label = contour_kws.pop("label", None) cset = contour_func( xx, yy, density, levels=draw_levels[key], **contour_kws, ) if "hue" not in self.variables: cset.collections[0].set_label(label) # Add a color bar representing the contour heights # Note: this shows iso densities, not iso proportions # See more notes in histplot about how this could be improved if cbar: cbar_kws = {} if cbar_kws is None else cbar_kws ax.figure.colorbar(cset, cbar_ax, ax, **cbar_kws) # --- Finalize the plot ax = self.ax if self.ax is not None else self.facets.axes.flat[0] self._add_axis_labels(ax) if "hue" in self.variables and legend: # TODO if possible, I would like to move the contour # intensity information into the legend too and label the # iso proportions rather than the raw density values artist_kws = {} if fill: artist = partial(mpl.patches.Patch) else: artist = partial(mpl.lines.Line2D, [], []) ax_obj = self.ax if self.ax is not None else self.facets self._add_legend( ax_obj, artist, fill, False, "layer", 1, artist_kws, {}, )
19,233
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter.plot_univariate_ecdf
(self, estimate_kws, legend, **plot_kws)
1,222
1,289
def plot_univariate_ecdf(self, estimate_kws, legend, **plot_kws): estimator = ECDF(**estimate_kws) # Set the draw style to step the right way for the data variable drawstyles = dict(x="steps-post", y="steps-pre") plot_kws["drawstyle"] = drawstyles[self.data_variable] # Loop through the subsets, transform and plot the data for sub_vars, sub_data in self.iter_data( "hue", reverse=True, from_comp_data=True, ): # Compute the ECDF if sub_data.empty: continue observations = sub_data[self.data_variable] weights = sub_data.get("weights", None) stat, vals = estimator(observations, weights=weights) # Assign attributes based on semantic mapping artist_kws = plot_kws.copy() if "hue" in self.variables: artist_kws["color"] = self._hue_map(sub_vars["hue"]) # Return the data variable to the linear domain # This needs an automatic solution; see GH2409 if self._log_scaled(self.data_variable): vals = np.power(10, vals) vals[0] = -np.inf # Work out the orientation of the plot if self.data_variable == "x": plot_args = vals, stat stat_variable = "y" else: plot_args = stat, vals stat_variable = "x" if estimator.stat == "count": top_edge = len(observations) else: top_edge = 1 # Draw the line for this subset ax = self._get_axes(sub_vars) artist, = ax.plot(*plot_args, **artist_kws) sticky_edges = getattr(artist.sticky_edges, stat_variable) sticky_edges[:] = 0, top_edge # --- Finalize the plot ---- ax = self.ax if self.ax is not None else self.facets.axes.flat[0] stat = estimator.stat.capitalize() default_x = default_y = "" if self.data_variable == "x": default_y = stat if self.data_variable == "y": default_x = stat self._add_axis_labels(ax, default_x, default_y) if "hue" in self.variables and legend: artist = partial(mpl.lines.Line2D, [], []) alpha = plot_kws.get("alpha", 1) ax_obj = self.ax if self.ax is not None else self.facets self._add_legend( ax_obj, artist, False, False, None, alpha, plot_kws, {}, )
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L1222-L1289
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65 ]
88.235294
[ 15 ]
1.470588
false
96.354167
68
11
98.529412
0
def plot_univariate_ecdf(self, estimate_kws, legend, **plot_kws): estimator = ECDF(**estimate_kws) # Set the draw style to step the right way for the data variable drawstyles = dict(x="steps-post", y="steps-pre") plot_kws["drawstyle"] = drawstyles[self.data_variable] # Loop through the subsets, transform and plot the data for sub_vars, sub_data in self.iter_data( "hue", reverse=True, from_comp_data=True, ): # Compute the ECDF if sub_data.empty: continue observations = sub_data[self.data_variable] weights = sub_data.get("weights", None) stat, vals = estimator(observations, weights=weights) # Assign attributes based on semantic mapping artist_kws = plot_kws.copy() if "hue" in self.variables: artist_kws["color"] = self._hue_map(sub_vars["hue"]) # Return the data variable to the linear domain # This needs an automatic solution; see GH2409 if self._log_scaled(self.data_variable): vals = np.power(10, vals) vals[0] = -np.inf # Work out the orientation of the plot if self.data_variable == "x": plot_args = vals, stat stat_variable = "y" else: plot_args = stat, vals stat_variable = "x" if estimator.stat == "count": top_edge = len(observations) else: top_edge = 1 # Draw the line for this subset ax = self._get_axes(sub_vars) artist, = ax.plot(*plot_args, **artist_kws) sticky_edges = getattr(artist.sticky_edges, stat_variable) sticky_edges[:] = 0, top_edge # --- Finalize the plot ---- ax = self.ax if self.ax is not None else self.facets.axes.flat[0] stat = estimator.stat.capitalize() default_x = default_y = "" if self.data_variable == "x": default_y = stat if self.data_variable == "y": default_x = stat self._add_axis_labels(ax, default_x, default_y) if "hue" in self.variables and legend: artist = partial(mpl.lines.Line2D, [], []) alpha = plot_kws.get("alpha", 1) ax_obj = self.ax if self.ax is not None else self.facets self._add_legend( ax_obj, artist, False, False, None, alpha, plot_kws, {}, )
19,234
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter.plot_rug
(self, height, expand_margins, legend, **kws)
1,291
1,323
def plot_rug(self, height, expand_margins, legend, **kws): for sub_vars, sub_data, in self.iter_data(from_comp_data=True): ax = self._get_axes(sub_vars) kws.setdefault("linewidth", 1) if expand_margins: xmarg, ymarg = ax.margins() if "x" in self.variables: ymarg += height * 2 if "y" in self.variables: xmarg += height * 2 ax.margins(x=xmarg, y=ymarg) if "hue" in self.variables: kws.pop("c", None) kws.pop("color", None) if "x" in self.variables: self._plot_single_rug(sub_data, "x", height, ax, kws) if "y" in self.variables: self._plot_single_rug(sub_data, "y", height, ax, kws) # --- Finalize the plot self._add_axis_labels(ax) if "hue" in self.variables and legend: # TODO ideally i'd like the legend artist to look like a rug legend_artist = partial(mpl.lines.Line2D, [], []) self._add_legend( ax, legend_artist, False, False, None, 1, {}, {}, )
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L1291-L1323
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 ]
93.939394
[]
0
false
96.354167
33
10
100
0
def plot_rug(self, height, expand_margins, legend, **kws): for sub_vars, sub_data, in self.iter_data(from_comp_data=True): ax = self._get_axes(sub_vars) kws.setdefault("linewidth", 1) if expand_margins: xmarg, ymarg = ax.margins() if "x" in self.variables: ymarg += height * 2 if "y" in self.variables: xmarg += height * 2 ax.margins(x=xmarg, y=ymarg) if "hue" in self.variables: kws.pop("c", None) kws.pop("color", None) if "x" in self.variables: self._plot_single_rug(sub_data, "x", height, ax, kws) if "y" in self.variables: self._plot_single_rug(sub_data, "y", height, ax, kws) # --- Finalize the plot self._add_axis_labels(ax) if "hue" in self.variables and legend: # TODO ideally i'd like the legend artist to look like a rug legend_artist = partial(mpl.lines.Line2D, [], []) self._add_legend( ax, legend_artist, False, False, None, 1, {}, {}, )
19,235
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/distributions.py
_DistributionPlotter._plot_single_rug
(self, sub_data, var, height, ax, kws)
Draw a rugplot along one axis of the plot.
Draw a rugplot along one axis of the plot.
1,325
1,362
def _plot_single_rug(self, sub_data, var, height, ax, kws): """Draw a rugplot along one axis of the plot.""" vector = sub_data[var] n = len(vector) # Return data to linear domain # This needs an automatic solution; see GH2409 if self._log_scaled(var): vector = np.power(10, vector) # We'll always add a single collection with varying colors if "hue" in self.variables: colors = self._hue_map(sub_data["hue"]) else: colors = None # Build the array of values for the LineCollection if var == "x": trans = tx.blended_transform_factory(ax.transData, ax.transAxes) xy_pairs = np.column_stack([ np.repeat(vector, 2), np.tile([0, height], n) ]) if var == "y": trans = tx.blended_transform_factory(ax.transAxes, ax.transData) xy_pairs = np.column_stack([ np.tile([0, height], n), np.repeat(vector, 2) ]) # Draw the lines on the plot line_segs = xy_pairs.reshape([n, 2, 2]) ax.add_collection(LineCollection( line_segs, transform=trans, colors=colors, **kws )) ax.autoscale_view(scalex=var == "x", scaley=var == "y")
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/distributions.py#L1325-L1362
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 ]
100
[]
0
true
96.354167
38
5
100
1
def _plot_single_rug(self, sub_data, var, height, ax, kws): vector = sub_data[var] n = len(vector) # Return data to linear domain # This needs an automatic solution; see GH2409 if self._log_scaled(var): vector = np.power(10, vector) # We'll always add a single collection with varying colors if "hue" in self.variables: colors = self._hue_map(sub_data["hue"]) else: colors = None # Build the array of values for the LineCollection if var == "x": trans = tx.blended_transform_factory(ax.transData, ax.transAxes) xy_pairs = np.column_stack([ np.repeat(vector, 2), np.tile([0, height], n) ]) if var == "y": trans = tx.blended_transform_factory(ax.transAxes, ax.transData) xy_pairs = np.column_stack([ np.tile([0, height], n), np.repeat(vector, 2) ]) # Draw the lines on the plot line_segs = xy_pairs.reshape([n, 2, 2]) ax.add_collection(LineCollection( line_segs, transform=trans, colors=colors, **kws )) ax.autoscale_view(scalex=var == "x", scaley=var == "y")
19,236
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
lmplot
( data=None, *, x=None, y=None, hue=None, col=None, row=None, palette=None, col_wrap=None, height=5, aspect=1, markers="o", sharex=None, sharey=None, hue_order=None, col_order=None, row_order=None, legend=True, legend_out=None, x_estimator=None, x_bins=None, x_ci="ci", scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, seed=None, order=1, logistic=False, lowess=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=True, x_jitter=None, y_jitter=None, scatter_kws=None, line_kws=None, facet_kws=None, )
return facets
560
641
def lmplot( data=None, *, x=None, y=None, hue=None, col=None, row=None, palette=None, col_wrap=None, height=5, aspect=1, markers="o", sharex=None, sharey=None, hue_order=None, col_order=None, row_order=None, legend=True, legend_out=None, x_estimator=None, x_bins=None, x_ci="ci", scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, seed=None, order=1, logistic=False, lowess=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=True, x_jitter=None, y_jitter=None, scatter_kws=None, line_kws=None, facet_kws=None, ): if facet_kws is None: facet_kws = {} def facet_kw_deprecation(key, val): msg = ( f"{key} is deprecated from the `lmplot` function signature. " "Please update your code to pass it using `facet_kws`." ) if val is not None: warnings.warn(msg, UserWarning) facet_kws[key] = val facet_kw_deprecation("sharex", sharex) facet_kw_deprecation("sharey", sharey) facet_kw_deprecation("legend_out", legend_out) if data is None: raise TypeError("Missing required keyword argument `data`.") # Reduce the dataframe to only needed columns need_cols = [x, y, hue, col, row, units, x_partial, y_partial] cols = np.unique([a for a in need_cols if a is not None]).tolist() data = data[cols] # Initialize the grid facets = FacetGrid( data, row=row, col=col, hue=hue, palette=palette, row_order=row_order, col_order=col_order, hue_order=hue_order, height=height, aspect=aspect, col_wrap=col_wrap, **facet_kws, ) # Add the markers here as FacetGrid has figured out how many levels of the # hue variable are needed and we don't want to duplicate that process if facets.hue_names is None: n_markers = 1 else: n_markers = len(facets.hue_names) if not isinstance(markers, list): markers = [markers] * n_markers if len(markers) != n_markers: raise ValueError("markers must be a singleton or a list of markers " "for each level of the hue variable") facets.hue_kws = {"marker": markers} def update_datalim(data, x, y, ax, **kws): xys = data[[x, y]].to_numpy().astype(float) ax.update_datalim(xys, updatey=False) ax.autoscale_view(scaley=False) facets.map_dataframe(update_datalim, x=x, y=y) # Draw the regression plot on each facet regplot_kws = dict( x_estimator=x_estimator, x_bins=x_bins, x_ci=x_ci, scatter=scatter, fit_reg=fit_reg, ci=ci, n_boot=n_boot, units=units, seed=seed, order=order, logistic=logistic, lowess=lowess, robust=robust, logx=logx, x_partial=x_partial, y_partial=y_partial, truncate=truncate, x_jitter=x_jitter, y_jitter=y_jitter, scatter_kws=scatter_kws, line_kws=line_kws, ) facets.map_dataframe(regplot, x=x, y=y, **regplot_kws) facets.set_axis_labels(x, y) # Add a legend if legend and (hue is not None) and (hue not in [col, row]): facets.add_legend() return facets
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L560-L641
26
[ 0, 12, 13, 14, 15, 16, 17, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 47, 48, 49, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 75, 76, 77, 78, 79, 80, 81 ]
62.195122
[]
0
false
87.037037
82
13
100
0
def lmplot( data=None, *, x=None, y=None, hue=None, col=None, row=None, palette=None, col_wrap=None, height=5, aspect=1, markers="o", sharex=None, sharey=None, hue_order=None, col_order=None, row_order=None, legend=True, legend_out=None, x_estimator=None, x_bins=None, x_ci="ci", scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, seed=None, order=1, logistic=False, lowess=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=True, x_jitter=None, y_jitter=None, scatter_kws=None, line_kws=None, facet_kws=None, ): if facet_kws is None: facet_kws = {} def facet_kw_deprecation(key, val): msg = ( f"{key} is deprecated from the `lmplot` function signature. " "Please update your code to pass it using `facet_kws`." ) if val is not None: warnings.warn(msg, UserWarning) facet_kws[key] = val facet_kw_deprecation("sharex", sharex) facet_kw_deprecation("sharey", sharey) facet_kw_deprecation("legend_out", legend_out) if data is None: raise TypeError("Missing required keyword argument `data`.") # Reduce the dataframe to only needed columns need_cols = [x, y, hue, col, row, units, x_partial, y_partial] cols = np.unique([a for a in need_cols if a is not None]).tolist() data = data[cols] # Initialize the grid facets = FacetGrid( data, row=row, col=col, hue=hue, palette=palette, row_order=row_order, col_order=col_order, hue_order=hue_order, height=height, aspect=aspect, col_wrap=col_wrap, **facet_kws, ) # Add the markers here as FacetGrid has figured out how many levels of the # hue variable are needed and we don't want to duplicate that process if facets.hue_names is None: n_markers = 1 else: n_markers = len(facets.hue_names) if not isinstance(markers, list): markers = [markers] * n_markers if len(markers) != n_markers: raise ValueError("markers must be a singleton or a list of markers " "for each level of the hue variable") facets.hue_kws = {"marker": markers} def update_datalim(data, x, y, ax, **kws): xys = data[[x, y]].to_numpy().astype(float) ax.update_datalim(xys, updatey=False) ax.autoscale_view(scaley=False) facets.map_dataframe(update_datalim, x=x, y=y) # Draw the regression plot on each facet regplot_kws = dict( x_estimator=x_estimator, x_bins=x_bins, x_ci=x_ci, scatter=scatter, fit_reg=fit_reg, ci=ci, n_boot=n_boot, units=units, seed=seed, order=order, logistic=logistic, lowess=lowess, robust=robust, logx=logx, x_partial=x_partial, y_partial=y_partial, truncate=truncate, x_jitter=x_jitter, y_jitter=y_jitter, scatter_kws=scatter_kws, line_kws=line_kws, ) facets.map_dataframe(regplot, x=x, y=y, **regplot_kws) facets.set_axis_labels(x, y) # Add a legend if legend and (hue is not None) and (hue not in [col, row]): facets.add_legend() return facets
19,237
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
regplot
( data=None, *, x=None, y=None, x_estimator=None, x_bins=None, x_ci="ci", scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, seed=None, order=1, logistic=False, lowess=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=True, dropna=True, x_jitter=None, y_jitter=None, label=None, color=None, marker="o", scatter_kws=None, line_kws=None, ax=None )
return ax
736
760
def regplot( data=None, *, x=None, y=None, x_estimator=None, x_bins=None, x_ci="ci", scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, seed=None, order=1, logistic=False, lowess=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=True, dropna=True, x_jitter=None, y_jitter=None, label=None, color=None, marker="o", scatter_kws=None, line_kws=None, ax=None ): plotter = _RegressionPlotter(x, y, data, x_estimator, x_bins, x_ci, scatter, fit_reg, ci, n_boot, units, seed, order, logistic, lowess, robust, logx, x_partial, y_partial, truncate, dropna, x_jitter, y_jitter, color, label) if ax is None: ax = plt.gca() scatter_kws = {} if scatter_kws is None else copy.copy(scatter_kws) scatter_kws["marker"] = marker line_kws = {} if line_kws is None else copy.copy(line_kws) plotter.plot(ax, scatter_kws, line_kws) return ax
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L736-L760
26
[ 0, 10, 11, 16, 17, 18, 19, 20, 21, 22, 23, 24 ]
48
[]
0
false
87.037037
25
2
100
0
def regplot( data=None, *, x=None, y=None, x_estimator=None, x_bins=None, x_ci="ci", scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, seed=None, order=1, logistic=False, lowess=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=True, dropna=True, x_jitter=None, y_jitter=None, label=None, color=None, marker="o", scatter_kws=None, line_kws=None, ax=None ): plotter = _RegressionPlotter(x, y, data, x_estimator, x_bins, x_ci, scatter, fit_reg, ci, n_boot, units, seed, order, logistic, lowess, robust, logx, x_partial, y_partial, truncate, dropna, x_jitter, y_jitter, color, label) if ax is None: ax = plt.gca() scatter_kws = {} if scatter_kws is None else copy.copy(scatter_kws) scatter_kws["marker"] = marker line_kws = {} if line_kws is None else copy.copy(line_kws) plotter.plot(ax, scatter_kws, line_kws) return ax
19,238
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
residplot
( data=None, *, x=None, y=None, x_partial=None, y_partial=None, lowess=False, order=1, robust=False, dropna=True, label=None, color=None, scatter_kws=None, line_kws=None, ax=None )
return ax
Plot the residuals of a linear regression. This function will regress y on x (possibly as a robust or polynomial regression) and then draw a scatterplot of the residuals. You can optionally fit a lowess smoother to the residual plot, which can help in determining if there is structure to the residuals. Parameters ---------- data : DataFrame, optional DataFrame to use if `x` and `y` are column names. x : vector or string Data or column name in `data` for the predictor variable. y : vector or string Data or column name in `data` for the response variable. {x, y}_partial : vectors or string(s) , optional These variables are treated as confounding and are removed from the `x` or `y` variables before plotting. lowess : boolean, optional Fit a lowess smoother to the residual scatterplot. order : int, optional Order of the polynomial to fit when calculating the residuals. robust : boolean, optional Fit a robust linear regression when calculating the residuals. dropna : boolean, optional If True, ignore observations with missing data when fitting and plotting. label : string, optional Label that will be used in any plot legends. color : matplotlib color, optional Color to use for all elements of the plot. {scatter, line}_kws : dictionaries, optional Additional keyword arguments passed to scatter() and plot() for drawing the components of the plot. ax : matplotlib axis, optional Plot into this axis, otherwise grab the current axis or make a new one if not existing. Returns ------- ax: matplotlib axes Axes with the regression plot. See Also -------- regplot : Plot a simple linear regression model. jointplot : Draw a :func:`residplot` with univariate marginal distributions (when used with ``kind="resid"``). Examples -------- .. include:: ../docstrings/residplot.rst
Plot the residuals of a linear regression.
838
924
def residplot( data=None, *, x=None, y=None, x_partial=None, y_partial=None, lowess=False, order=1, robust=False, dropna=True, label=None, color=None, scatter_kws=None, line_kws=None, ax=None ): """Plot the residuals of a linear regression. This function will regress y on x (possibly as a robust or polynomial regression) and then draw a scatterplot of the residuals. You can optionally fit a lowess smoother to the residual plot, which can help in determining if there is structure to the residuals. Parameters ---------- data : DataFrame, optional DataFrame to use if `x` and `y` are column names. x : vector or string Data or column name in `data` for the predictor variable. y : vector or string Data or column name in `data` for the response variable. {x, y}_partial : vectors or string(s) , optional These variables are treated as confounding and are removed from the `x` or `y` variables before plotting. lowess : boolean, optional Fit a lowess smoother to the residual scatterplot. order : int, optional Order of the polynomial to fit when calculating the residuals. robust : boolean, optional Fit a robust linear regression when calculating the residuals. dropna : boolean, optional If True, ignore observations with missing data when fitting and plotting. label : string, optional Label that will be used in any plot legends. color : matplotlib color, optional Color to use for all elements of the plot. {scatter, line}_kws : dictionaries, optional Additional keyword arguments passed to scatter() and plot() for drawing the components of the plot. ax : matplotlib axis, optional Plot into this axis, otherwise grab the current axis or make a new one if not existing. Returns ------- ax: matplotlib axes Axes with the regression plot. See Also -------- regplot : Plot a simple linear regression model. jointplot : Draw a :func:`residplot` with univariate marginal distributions (when used with ``kind="resid"``). Examples -------- .. include:: ../docstrings/residplot.rst """ plotter = _RegressionPlotter(x, y, data, ci=None, order=order, robust=robust, x_partial=x_partial, y_partial=y_partial, dropna=dropna, color=color, label=label) if ax is None: ax = plt.gca() # Calculate the residual from a linear regression _, yhat, _ = plotter.fit_regression(grid=plotter.x) plotter.y = plotter.y - yhat # Set the regression option on the plotter if lowess: plotter.lowess = True else: plotter.fit_reg = False # Plot a horizontal line at 0 ax.axhline(0, ls=":", c=".2") # Draw the scatterplot scatter_kws = {} if scatter_kws is None else scatter_kws.copy() line_kws = {} if line_kws is None else line_kws.copy() plotter.plot(ax, scatter_kws, line_kws) return ax
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L838-L924
26
[ 0, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86 ]
31.034483
[ 75 ]
1.149425
false
87.037037
87
3
98.850575
53
def residplot( data=None, *, x=None, y=None, x_partial=None, y_partial=None, lowess=False, order=1, robust=False, dropna=True, label=None, color=None, scatter_kws=None, line_kws=None, ax=None ): plotter = _RegressionPlotter(x, y, data, ci=None, order=order, robust=robust, x_partial=x_partial, y_partial=y_partial, dropna=dropna, color=color, label=label) if ax is None: ax = plt.gca() # Calculate the residual from a linear regression _, yhat, _ = plotter.fit_regression(grid=plotter.x) plotter.y = plotter.y - yhat # Set the regression option on the plotter if lowess: plotter.lowess = True else: plotter.fit_reg = False # Plot a horizontal line at 0 ax.axhline(0, ls=":", c=".2") # Draw the scatterplot scatter_kws = {} if scatter_kws is None else scatter_kws.copy() line_kws = {} if line_kws is None else line_kws.copy() plotter.plot(ax, scatter_kws, line_kws) return ax
19,239
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_LinearPlotter.establish_variables
(self, data, **kws)
Extract variables from data or use directly.
Extract variables from data or use directly.
32
54
def establish_variables(self, data, **kws): """Extract variables from data or use directly.""" self.data = data # Validate the inputs any_strings = any([isinstance(v, str) for v in kws.values()]) if any_strings and data is None: raise ValueError("Must pass `data` if using named variables.") # Set the variables for var, val in kws.items(): if isinstance(val, str): vector = data[val] elif isinstance(val, list): vector = np.asarray(val) else: vector = val if vector is not None and vector.shape != (1,): vector = np.squeeze(vector) if np.ndim(vector) > 1: err = "regplot inputs must be 1d" raise ValueError(err) setattr(self, var, vector)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L32-L54
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
87.037037
23
10
100
1
def establish_variables(self, data, **kws): self.data = data # Validate the inputs any_strings = any([isinstance(v, str) for v in kws.values()]) if any_strings and data is None: raise ValueError("Must pass `data` if using named variables.") # Set the variables for var, val in kws.items(): if isinstance(val, str): vector = data[val] elif isinstance(val, list): vector = np.asarray(val) else: vector = val if vector is not None and vector.shape != (1,): vector = np.squeeze(vector) if np.ndim(vector) > 1: err = "regplot inputs must be 1d" raise ValueError(err) setattr(self, var, vector)
19,240
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_LinearPlotter.dropna
(self, *vars)
Remove observations with missing data.
Remove observations with missing data.
56
64
def dropna(self, *vars): """Remove observations with missing data.""" vals = [getattr(self, var) for var in vars] vals = [v for v in vals if v is not None] not_na = np.all(np.column_stack([pd.notnull(v) for v in vals]), axis=1) for var in vars: val = getattr(self, var) if val is not None: setattr(self, var, val[not_na])
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L56-L64
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
87.037037
9
6
100
1
def dropna(self, *vars): vals = [getattr(self, var) for var in vars] vals = [v for v in vals if v is not None] not_na = np.all(np.column_stack([pd.notnull(v) for v in vals]), axis=1) for var in vars: val = getattr(self, var) if val is not None: setattr(self, var, val[not_na])
19,241
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_RegressionPlotter.__init__
(self, x, y, data=None, x_estimator=None, x_bins=None, x_ci="ci", scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, seed=None, order=1, logistic=False, lowess=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=False, dropna=True, x_jitter=None, y_jitter=None, color=None, label=None)
76
134
def __init__(self, x, y, data=None, x_estimator=None, x_bins=None, x_ci="ci", scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, seed=None, order=1, logistic=False, lowess=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=False, dropna=True, x_jitter=None, y_jitter=None, color=None, label=None): # Set member attributes self.x_estimator = x_estimator self.ci = ci self.x_ci = ci if x_ci == "ci" else x_ci self.n_boot = n_boot self.seed = seed self.scatter = scatter self.fit_reg = fit_reg self.order = order self.logistic = logistic self.lowess = lowess self.robust = robust self.logx = logx self.truncate = truncate self.x_jitter = x_jitter self.y_jitter = y_jitter self.color = color self.label = label # Validate the regression options: if sum((order > 1, logistic, robust, lowess, logx)) > 1: raise ValueError("Mutually exclusive regression options.") # Extract the data vals from the arguments or passed dataframe self.establish_variables(data, x=x, y=y, units=units, x_partial=x_partial, y_partial=y_partial) # Drop null observations if dropna: self.dropna("x", "y", "units", "x_partial", "y_partial") # Regress nuisance variables out of the data if self.x_partial is not None: self.x = self.regress_out(self.x, self.x_partial) if self.y_partial is not None: self.y = self.regress_out(self.y, self.y_partial) # Possibly bin the predictor variable, which implies a point estimate if x_bins is not None: self.x_estimator = np.mean if x_estimator is None else x_estimator x_discrete, x_bins = self.bin_predictor(x_bins) self.x_discrete = x_discrete else: self.x_discrete = self.x # Disable regression in case of singleton inputs if len(self.x) <= 1: self.fit_reg = False # Save the range of the x variable for the grid later if self.fit_reg: self.x_range = self.x.min(), self.x.max()
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L76-L134
26
[ 0, 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, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50, 51, 52, 53, 54, 55, 56, 57, 58 ]
84.745763
[]
0
false
87.037037
59
8
100
0
def __init__(self, x, y, data=None, x_estimator=None, x_bins=None, x_ci="ci", scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, seed=None, order=1, logistic=False, lowess=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=False, dropna=True, x_jitter=None, y_jitter=None, color=None, label=None): # Set member attributes self.x_estimator = x_estimator self.ci = ci self.x_ci = ci if x_ci == "ci" else x_ci self.n_boot = n_boot self.seed = seed self.scatter = scatter self.fit_reg = fit_reg self.order = order self.logistic = logistic self.lowess = lowess self.robust = robust self.logx = logx self.truncate = truncate self.x_jitter = x_jitter self.y_jitter = y_jitter self.color = color self.label = label # Validate the regression options: if sum((order > 1, logistic, robust, lowess, logx)) > 1: raise ValueError("Mutually exclusive regression options.") # Extract the data vals from the arguments or passed dataframe self.establish_variables(data, x=x, y=y, units=units, x_partial=x_partial, y_partial=y_partial) # Drop null observations if dropna: self.dropna("x", "y", "units", "x_partial", "y_partial") # Regress nuisance variables out of the data if self.x_partial is not None: self.x = self.regress_out(self.x, self.x_partial) if self.y_partial is not None: self.y = self.regress_out(self.y, self.y_partial) # Possibly bin the predictor variable, which implies a point estimate if x_bins is not None: self.x_estimator = np.mean if x_estimator is None else x_estimator x_discrete, x_bins = self.bin_predictor(x_bins) self.x_discrete = x_discrete else: self.x_discrete = self.x # Disable regression in case of singleton inputs if len(self.x) <= 1: self.fit_reg = False # Save the range of the x variable for the grid later if self.fit_reg: self.x_range = self.x.min(), self.x.max()
19,242
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_RegressionPlotter.scatter_data
(self)
return x, y
Data where each observation is a point.
Data where each observation is a point.
137
151
def scatter_data(self): """Data where each observation is a point.""" x_j = self.x_jitter if x_j is None: x = self.x else: x = self.x + np.random.uniform(-x_j, x_j, len(self.x)) y_j = self.y_jitter if y_j is None: y = self.y else: y = self.y + np.random.uniform(-y_j, y_j, len(self.y)) return x, y
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L137-L151
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
87.037037
15
3
100
1
def scatter_data(self): x_j = self.x_jitter if x_j is None: x = self.x else: x = self.x + np.random.uniform(-x_j, x_j, len(self.x)) y_j = self.y_jitter if y_j is None: y = self.y else: y = self.y + np.random.uniform(-y_j, y_j, len(self.y)) return x, y
19,243
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_RegressionPlotter.estimate_data
(self)
return vals, points, cis
Data with a point estimate and CI for each discrete x value.
Data with a point estimate and CI for each discrete x value.
154
186
def estimate_data(self): """Data with a point estimate and CI for each discrete x value.""" x, y = self.x_discrete, self.y vals = sorted(np.unique(x)) points, cis = [], [] for val in vals: # Get the point estimate of the y variable _y = y[x == val] est = self.x_estimator(_y) points.append(est) # Compute the confidence interval for this estimate if self.x_ci is None: cis.append(None) else: units = None if self.x_ci == "sd": sd = np.std(_y) _ci = est - sd, est + sd else: if self.units is not None: units = self.units[x == val] boots = algo.bootstrap(_y, func=self.x_estimator, n_boot=self.n_boot, units=units, seed=self.seed) _ci = utils.ci(boots, self.x_ci) cis.append(_ci) return vals, points, cis
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L154-L186
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ]
93.939394
[ 19, 20 ]
6.060606
false
87.037037
33
5
93.939394
1
def estimate_data(self): x, y = self.x_discrete, self.y vals = sorted(np.unique(x)) points, cis = [], [] for val in vals: # Get the point estimate of the y variable _y = y[x == val] est = self.x_estimator(_y) points.append(est) # Compute the confidence interval for this estimate if self.x_ci is None: cis.append(None) else: units = None if self.x_ci == "sd": sd = np.std(_y) _ci = est - sd, est + sd else: if self.units is not None: units = self.units[x == val] boots = algo.bootstrap(_y, func=self.x_estimator, n_boot=self.n_boot, units=units, seed=self.seed) _ci = utils.ci(boots, self.x_ci) cis.append(_ci) return vals, points, cis
19,244
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_RegressionPlotter.fit_regression
(self, ax=None, x_range=None, grid=None)
return grid, yhat, err_bands
Fit the regression model.
Fit the regression model.
188
227
def fit_regression(self, ax=None, x_range=None, grid=None): """Fit the regression model.""" # Create the grid for the regression if grid is None: if self.truncate: x_min, x_max = self.x_range else: if ax is None: x_min, x_max = x_range else: x_min, x_max = ax.get_xlim() grid = np.linspace(x_min, x_max, 100) ci = self.ci # Fit the regression if self.order > 1: yhat, yhat_boots = self.fit_poly(grid, self.order) elif self.logistic: from statsmodels.genmod.generalized_linear_model import GLM from statsmodels.genmod.families import Binomial yhat, yhat_boots = self.fit_statsmodels(grid, GLM, family=Binomial()) elif self.lowess: ci = None grid, yhat = self.fit_lowess() elif self.robust: from statsmodels.robust.robust_linear_model import RLM yhat, yhat_boots = self.fit_statsmodels(grid, RLM) elif self.logx: yhat, yhat_boots = self.fit_logx(grid) else: yhat, yhat_boots = self.fit_fast(grid) # Compute the confidence interval at each grid point if ci is None: err_bands = None else: err_bands = utils.ci(yhat_boots, ci, axis=0) return grid, yhat, err_bands
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L188-L227
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 17, 21, 22, 25, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39 ]
75
[ 8, 16, 18, 19, 20, 23, 24, 26, 27, 29 ]
25
false
87.037037
40
10
75
1
def fit_regression(self, ax=None, x_range=None, grid=None): # Create the grid for the regression if grid is None: if self.truncate: x_min, x_max = self.x_range else: if ax is None: x_min, x_max = x_range else: x_min, x_max = ax.get_xlim() grid = np.linspace(x_min, x_max, 100) ci = self.ci # Fit the regression if self.order > 1: yhat, yhat_boots = self.fit_poly(grid, self.order) elif self.logistic: from statsmodels.genmod.generalized_linear_model import GLM from statsmodels.genmod.families import Binomial yhat, yhat_boots = self.fit_statsmodels(grid, GLM, family=Binomial()) elif self.lowess: ci = None grid, yhat = self.fit_lowess() elif self.robust: from statsmodels.robust.robust_linear_model import RLM yhat, yhat_boots = self.fit_statsmodels(grid, RLM) elif self.logx: yhat, yhat_boots = self.fit_logx(grid) else: yhat, yhat_boots = self.fit_fast(grid) # Compute the confidence interval at each grid point if ci is None: err_bands = None else: err_bands = utils.ci(yhat_boots, ci, axis=0) return grid, yhat, err_bands
19,245
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_RegressionPlotter.fit_fast
(self, grid)
return yhat, yhat_boots
Low-level regression and prediction using linear algebra.
Low-level regression and prediction using linear algebra.
229
246
def fit_fast(self, grid): """Low-level regression and prediction using linear algebra.""" def reg_func(_x, _y): return np.linalg.pinv(_x).dot(_y) X, y = np.c_[np.ones(len(self.x)), self.x], self.y grid = np.c_[np.ones(len(grid)), grid] yhat = grid.dot(reg_func(X, y)) if self.ci is None: return yhat, None beta_boots = algo.bootstrap(X, y, func=reg_func, n_boot=self.n_boot, units=self.units, seed=self.seed).T yhat_boots = grid.dot(beta_boots).T return yhat, yhat_boots
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L229-L246
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
100
[]
0
true
87.037037
18
3
100
1
def fit_fast(self, grid): def reg_func(_x, _y): return np.linalg.pinv(_x).dot(_y) X, y = np.c_[np.ones(len(self.x)), self.x], self.y grid = np.c_[np.ones(len(grid)), grid] yhat = grid.dot(reg_func(X, y)) if self.ci is None: return yhat, None beta_boots = algo.bootstrap(X, y, func=reg_func, n_boot=self.n_boot, units=self.units, seed=self.seed).T yhat_boots = grid.dot(beta_boots).T return yhat, yhat_boots
19,246
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_RegressionPlotter.fit_poly
(self, grid, order)
return yhat, yhat_boots
Regression using numpy polyfit for higher-order trends.
Regression using numpy polyfit for higher-order trends.
248
263
def fit_poly(self, grid, order): """Regression using numpy polyfit for higher-order trends.""" def reg_func(_x, _y): return np.polyval(np.polyfit(_x, _y, order), grid) x, y = self.x, self.y yhat = reg_func(x, y) if self.ci is None: return yhat, None yhat_boots = algo.bootstrap(x, y, func=reg_func, n_boot=self.n_boot, units=self.units, seed=self.seed) return yhat, yhat_boots
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L248-L263
26
[ 0, 1 ]
12.5
[ 2, 3, 5, 6, 7, 8, 10, 15 ]
50
false
87.037037
16
3
50
1
def fit_poly(self, grid, order): def reg_func(_x, _y): return np.polyval(np.polyfit(_x, _y, order), grid) x, y = self.x, self.y yhat = reg_func(x, y) if self.ci is None: return yhat, None yhat_boots = algo.bootstrap(x, y, func=reg_func, n_boot=self.n_boot, units=self.units, seed=self.seed) return yhat, yhat_boots
19,247
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_RegressionPlotter.fit_statsmodels
(self, grid, model, **kwargs)
return yhat, yhat_boots
More general regression function using statsmodels objects.
More general regression function using statsmodels objects.
265
288
def fit_statsmodels(self, grid, model, **kwargs): """More general regression function using statsmodels objects.""" import statsmodels.genmod.generalized_linear_model as glm X, y = np.c_[np.ones(len(self.x)), self.x], self.y grid = np.c_[np.ones(len(grid)), grid] def reg_func(_x, _y): try: yhat = model(_y, _x, **kwargs).fit().predict(grid) except glm.PerfectSeparationError: yhat = np.empty(len(grid)) yhat.fill(np.nan) return yhat yhat = reg_func(X, y) if self.ci is None: return yhat, None yhat_boots = algo.bootstrap(X, y, func=reg_func, n_boot=self.n_boot, units=self.units, seed=self.seed) return yhat, yhat_boots
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L265-L288
26
[ 0, 1 ]
8.333333
[ 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 18, 23 ]
62.5
false
87.037037
24
4
37.5
1
def fit_statsmodels(self, grid, model, **kwargs): import statsmodels.genmod.generalized_linear_model as glm X, y = np.c_[np.ones(len(self.x)), self.x], self.y grid = np.c_[np.ones(len(grid)), grid] def reg_func(_x, _y): try: yhat = model(_y, _x, **kwargs).fit().predict(grid) except glm.PerfectSeparationError: yhat = np.empty(len(grid)) yhat.fill(np.nan) return yhat yhat = reg_func(X, y) if self.ci is None: return yhat, None yhat_boots = algo.bootstrap(X, y, func=reg_func, n_boot=self.n_boot, units=self.units, seed=self.seed) return yhat, yhat_boots
19,248
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_RegressionPlotter.fit_lowess
(self)
return grid, yhat
Fit a locally-weighted regression, which returns its own grid.
Fit a locally-weighted regression, which returns its own grid.
290
294
def fit_lowess(self): """Fit a locally-weighted regression, which returns its own grid.""" from statsmodels.nonparametric.smoothers_lowess import lowess grid, yhat = lowess(self.y, self.x).T return grid, yhat
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L290-L294
26
[ 0, 1 ]
40
[ 2, 3, 4 ]
60
false
87.037037
5
1
40
1
def fit_lowess(self): from statsmodels.nonparametric.smoothers_lowess import lowess grid, yhat = lowess(self.y, self.x).T return grid, yhat
19,249
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_RegressionPlotter.fit_logx
(self, grid)
return yhat, yhat_boots
Fit the model in log-space.
Fit the model in log-space.
296
315
def fit_logx(self, grid): """Fit the model in log-space.""" X, y = np.c_[np.ones(len(self.x)), self.x], self.y grid = np.c_[np.ones(len(grid)), np.log(grid)] def reg_func(_x, _y): _x = np.c_[_x[:, 0], np.log(_x[:, 1])] return np.linalg.pinv(_x).dot(_y) yhat = grid.dot(reg_func(X, y)) if self.ci is None: return yhat, None beta_boots = algo.bootstrap(X, y, func=reg_func, n_boot=self.n_boot, units=self.units, seed=self.seed).T yhat_boots = grid.dot(beta_boots).T return yhat, yhat_boots
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L296-L315
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19 ]
95
[ 11 ]
5
false
87.037037
20
3
95
1
def fit_logx(self, grid): X, y = np.c_[np.ones(len(self.x)), self.x], self.y grid = np.c_[np.ones(len(grid)), np.log(grid)] def reg_func(_x, _y): _x = np.c_[_x[:, 0], np.log(_x[:, 1])] return np.linalg.pinv(_x).dot(_y) yhat = grid.dot(reg_func(X, y)) if self.ci is None: return yhat, None beta_boots = algo.bootstrap(X, y, func=reg_func, n_boot=self.n_boot, units=self.units, seed=self.seed).T yhat_boots = grid.dot(beta_boots).T return yhat, yhat_boots
19,250
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_RegressionPlotter.bin_predictor
(self, bins)
return x_binned, bins
Discretize a predictor by assigning value to closest bin.
Discretize a predictor by assigning value to closest bin.
317
329
def bin_predictor(self, bins): """Discretize a predictor by assigning value to closest bin.""" x = np.asarray(self.x) if np.isscalar(bins): percentiles = np.linspace(0, 100, bins + 2)[1:-1] bins = np.percentile(x, percentiles) else: bins = np.ravel(bins) dist = np.abs(np.subtract.outer(x, bins)) x_binned = bins[np.argmin(dist, axis=1)].ravel() return x_binned, bins
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L317-L329
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
87.037037
13
2
100
1
def bin_predictor(self, bins): x = np.asarray(self.x) if np.isscalar(bins): percentiles = np.linspace(0, 100, bins + 2)[1:-1] bins = np.percentile(x, percentiles) else: bins = np.ravel(bins) dist = np.abs(np.subtract.outer(x, bins)) x_binned = bins[np.argmin(dist, axis=1)].ravel() return x_binned, bins
19,251
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_RegressionPlotter.regress_out
(self, a, b)
return np.asarray(a_prime + a_mean).reshape(a.shape)
Regress b from a keeping a's original mean.
Regress b from a keeping a's original mean.
331
338
def regress_out(self, a, b): """Regress b from a keeping a's original mean.""" a_mean = a.mean() a = a - a_mean b = b - b.mean() b = np.c_[b] a_prime = a - b.dot(np.linalg.pinv(b).dot(a)) return np.asarray(a_prime + a_mean).reshape(a.shape)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L331-L338
26
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
87.037037
8
1
100
1
def regress_out(self, a, b): a_mean = a.mean() a = a - a_mean b = b - b.mean() b = np.c_[b] a_prime = a - b.dot(np.linalg.pinv(b).dot(a)) return np.asarray(a_prime + a_mean).reshape(a.shape)
19,252
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_RegressionPlotter.plot
(self, ax, scatter_kws, line_kws)
Draw the full plot.
Draw the full plot.
340
374
def plot(self, ax, scatter_kws, line_kws): """Draw the full plot.""" # Insert the plot label into the correct set of keyword arguments if self.scatter: scatter_kws["label"] = self.label else: line_kws["label"] = self.label # Use the current color cycle state as a default if self.color is None: lines, = ax.plot([], []) color = lines.get_color() lines.remove() else: color = self.color # Ensure that color is hex to avoid matplotlib weirdness color = mpl.colors.rgb2hex(mpl.colors.colorConverter.to_rgb(color)) # Let color in keyword arguments override overall plot color scatter_kws.setdefault("color", color) line_kws.setdefault("color", color) # Draw the constituent plots if self.scatter: self.scatterplot(ax, scatter_kws) if self.fit_reg: self.lineplot(ax, line_kws) # Label the axes if hasattr(self.x, "name"): ax.set_xlabel(self.x.name) if hasattr(self.y, "name"): ax.set_ylabel(self.y.name)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L340-L374
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
87.037037
35
7
100
1
def plot(self, ax, scatter_kws, line_kws): # Insert the plot label into the correct set of keyword arguments if self.scatter: scatter_kws["label"] = self.label else: line_kws["label"] = self.label # Use the current color cycle state as a default if self.color is None: lines, = ax.plot([], []) color = lines.get_color() lines.remove() else: color = self.color # Ensure that color is hex to avoid matplotlib weirdness color = mpl.colors.rgb2hex(mpl.colors.colorConverter.to_rgb(color)) # Let color in keyword arguments override overall plot color scatter_kws.setdefault("color", color) line_kws.setdefault("color", color) # Draw the constituent plots if self.scatter: self.scatterplot(ax, scatter_kws) if self.fit_reg: self.lineplot(ax, line_kws) # Label the axes if hasattr(self.x, "name"): ax.set_xlabel(self.x.name) if hasattr(self.y, "name"): ax.set_ylabel(self.y.name)
19,253
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_RegressionPlotter.scatterplot
(self, ax, kws)
Draw the data.
Draw the data.
376
408
def scatterplot(self, ax, kws): """Draw the data.""" # Treat the line-based markers specially, explicitly setting larger # linewidth than is provided by the seaborn style defaults. # This would ideally be handled better in matplotlib (i.e., distinguish # between edgewidth for solid glyphs and linewidth for line glyphs # but this should do for now. line_markers = ["1", "2", "3", "4", "+", "x", "|", "_"] if self.x_estimator is None: if "marker" in kws and kws["marker"] in line_markers: lw = mpl.rcParams["lines.linewidth"] else: lw = mpl.rcParams["lines.markeredgewidth"] kws.setdefault("linewidths", lw) if not hasattr(kws['color'], 'shape') or kws['color'].shape[1] < 4: kws.setdefault("alpha", .8) x, y = self.scatter_data ax.scatter(x, y, **kws) else: # TODO abstraction ci_kws = {"color": kws["color"]} if "alpha" in kws: ci_kws["alpha"] = kws["alpha"] ci_kws["linewidth"] = mpl.rcParams["lines.linewidth"] * 1.75 kws.setdefault("s", 50) xs, ys, cis = self.estimate_data if [ci for ci in cis if ci is not None]: for x, ci in zip(xs, cis): ax.plot([x, x], ci, **ci_kws) ax.scatter(xs, ys, **kws)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L376-L408
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
87.037037
33
10
100
1
def scatterplot(self, ax, kws): # Treat the line-based markers specially, explicitly setting larger # linewidth than is provided by the seaborn style defaults. # This would ideally be handled better in matplotlib (i.e., distinguish # between edgewidth for solid glyphs and linewidth for line glyphs # but this should do for now. line_markers = ["1", "2", "3", "4", "+", "x", "|", "_"] if self.x_estimator is None: if "marker" in kws and kws["marker"] in line_markers: lw = mpl.rcParams["lines.linewidth"] else: lw = mpl.rcParams["lines.markeredgewidth"] kws.setdefault("linewidths", lw) if not hasattr(kws['color'], 'shape') or kws['color'].shape[1] < 4: kws.setdefault("alpha", .8) x, y = self.scatter_data ax.scatter(x, y, **kws) else: # TODO abstraction ci_kws = {"color": kws["color"]} if "alpha" in kws: ci_kws["alpha"] = kws["alpha"] ci_kws["linewidth"] = mpl.rcParams["lines.linewidth"] * 1.75 kws.setdefault("s", 50) xs, ys, cis = self.estimate_data if [ci for ci in cis if ci is not None]: for x, ci in zip(xs, cis): ax.plot([x, x], ci, **ci_kws) ax.scatter(xs, ys, **kws)
19,254
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/regression.py
_RegressionPlotter.lineplot
(self, ax, kws)
Draw the model.
Draw the model.
410
426
def lineplot(self, ax, kws): """Draw the model.""" # Fit the regression model grid, yhat, err_bands = self.fit_regression(ax) edges = grid[0], grid[-1] # Get set default aesthetics fill_color = kws["color"] lw = kws.pop("lw", mpl.rcParams["lines.linewidth"] * 1.5) kws.setdefault("linewidth", lw) # Draw the regression line and confidence interval line, = ax.plot(grid, yhat, **kws) if not self.truncate: line.sticky_edges.x[:] = edges # Prevent mpl from adding margin if err_bands is not None: ax.fill_between(grid, *err_bands, facecolor=fill_color, alpha=.15)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/regression.py#L410-L426
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
100
[]
0
true
87.037037
17
3
100
1
def lineplot(self, ax, kws): # Fit the regression model grid, yhat, err_bands = self.fit_regression(ax) edges = grid[0], grid[-1] # Get set default aesthetics fill_color = kws["color"] lw = kws.pop("lw", mpl.rcParams["lines.linewidth"] * 1.5) kws.setdefault("linewidth", lw) # Draw the regression line and confidence interval line, = ax.plot(grid, yhat, **kws) if not self.truncate: line.sticky_edges.x[:] = edges # Prevent mpl from adding margin if err_bands is not None: ax.fill_between(grid, *err_bands, facecolor=fill_color, alpha=.15)
19,255
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/miscplot.py
palplot
(pal, size=1)
Plot the values in a color palette as a horizontal array. Parameters ---------- pal : sequence of matplotlib colors colors, i.e. as returned by seaborn.color_palette() size : scaling factor for size of plot
Plot the values in a color palette as a horizontal array.
9
30
def palplot(pal, size=1): """Plot the values in a color palette as a horizontal array. Parameters ---------- pal : sequence of matplotlib colors colors, i.e. as returned by seaborn.color_palette() size : scaling factor for size of plot """ n = len(pal) f, ax = plt.subplots(1, 1, figsize=(n * size, size)) ax.imshow(np.arange(n).reshape(1, n), cmap=mpl.colors.ListedColormap(list(pal)), interpolation="nearest", aspect="auto") ax.set_xticks(np.arange(n) - .5) ax.set_yticks([-.5, .5]) # Ensure nice border between colors ax.set_xticklabels(["" for _ in range(n)]) # The proper way to set no ticks ax.yaxis.set_major_locator(ticker.NullLocator())
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/miscplot.py#L9-L30
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
92.592593
22
2
100
8
def palplot(pal, size=1): n = len(pal) f, ax = plt.subplots(1, 1, figsize=(n * size, size)) ax.imshow(np.arange(n).reshape(1, n), cmap=mpl.colors.ListedColormap(list(pal)), interpolation="nearest", aspect="auto") ax.set_xticks(np.arange(n) - .5) ax.set_yticks([-.5, .5]) # Ensure nice border between colors ax.set_xticklabels(["" for _ in range(n)]) # The proper way to set no ticks ax.yaxis.set_major_locator(ticker.NullLocator())
19,256
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/miscplot.py
dogplot
(*_, **__)
Who's a good boy?
Who's a good boy?
33
48
def dogplot(*_, **__): """Who's a good boy?""" try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen from io import BytesIO url = "https://github.com/mwaskom/seaborn-data/raw/master/png/img{}.png" pic = np.random.randint(2, 7) data = BytesIO(urlopen(url.format(pic)).read()) img = plt.imread(data) f, ax = plt.subplots(figsize=(5, 5), dpi=100) f.subplots_adjust(0, 0, 1, 1) ax.imshow(img) ax.set_axis_off()
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/miscplot.py#L33-L48
26
[ 0, 1, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
87.5
[ 4, 5 ]
12.5
false
92.592593
16
2
87.5
1
def dogplot(*_, **__): try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen from io import BytesIO url = "https://github.com/mwaskom/seaborn-data/raw/master/png/img{}.png" pic = np.random.randint(2, 7) data = BytesIO(urlopen(url.format(pic)).read()) img = plt.imread(data) f, ax = plt.subplots(figsize=(5, 5), dpi=100) f.subplots_adjust(0, 0, 1, 1) ax.imshow(img) ax.set_axis_off()
19,257
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/dot.py
DotBase._resolve_paths
(self, data)
return paths
29
45
def _resolve_paths(self, data): paths = [] path_cache = {} marker = data["marker"] def get_transformed_path(m): return m.get_path().transformed(m.get_transform()) if isinstance(marker, mpl.markers.MarkerStyle): return get_transformed_path(marker) for m in marker: if m not in path_cache: path_cache[m] = get_transformed_path(m) paths.append(path_cache[m]) return paths
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/dot.py#L29-L45
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
100
[]
0
true
100
17
5
100
0
def _resolve_paths(self, data): paths = [] path_cache = {} marker = data["marker"] def get_transformed_path(m): return m.get_path().transformed(m.get_transform()) if isinstance(marker, mpl.markers.MarkerStyle): return get_transformed_path(marker) for m in marker: if m not in path_cache: path_cache[m] = get_transformed_path(m) paths.append(path_cache[m]) return paths
19,258
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/dot.py
DotBase._resolve_properties
(self, data, scales)
return resolved
47
60
def _resolve_properties(self, data, scales): resolved = resolve_properties(self, data, scales) resolved["path"] = self._resolve_paths(resolved) resolved["size"] = resolved["pointsize"] ** 2 if isinstance(data, dict): # Properties for single dot filled_marker = resolved["marker"].is_filled() else: filled_marker = [m.is_filled() for m in resolved["marker"]] resolved["fill"] = resolved["fill"] * filled_marker return resolved
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/dot.py#L47-L60
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13 ]
92.857143
[]
0
false
100
14
3
100
0
def _resolve_properties(self, data, scales): resolved = resolve_properties(self, data, scales) resolved["path"] = self._resolve_paths(resolved) resolved["size"] = resolved["pointsize"] ** 2 if isinstance(data, dict): # Properties for single dot filled_marker = resolved["marker"].is_filled() else: filled_marker = [m.is_filled() for m in resolved["marker"]] resolved["fill"] = resolved["fill"] * filled_marker return resolved
19,259
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/dot.py
DotBase._plot
(self, split_gen, scales, orient)
62
85
def _plot(self, split_gen, scales, orient): # TODO Not backcompat with allowed (but nonfunctional) univariate plots # (That should be solved upstream by defaulting to "" for unset x/y?) # (Be mindful of xmin/xmax, etc!) for _, data, ax in split_gen(): offsets = np.column_stack([data["x"], data["y"]]) data = self._resolve_properties(data, scales) points = mpl.collections.PathCollection( offsets=offsets, paths=data["path"], sizes=data["size"], facecolors=data["facecolor"], edgecolors=data["edgecolor"], linewidths=data["linewidth"], linestyles=data["edgestyle"], transOffset=ax.transData, transform=mpl.transforms.IdentityTransform(), **self.artist_kws, ) ax.add_collection(points)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/dot.py#L62-L85
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 23 ]
54.166667
[]
0
false
100
24
2
100
0
def _plot(self, split_gen, scales, orient): # TODO Not backcompat with allowed (but nonfunctional) univariate plots # (That should be solved upstream by defaulting to "" for unset x/y?) # (Be mindful of xmin/xmax, etc!) for _, data, ax in split_gen(): offsets = np.column_stack([data["x"], data["y"]]) data = self._resolve_properties(data, scales) points = mpl.collections.PathCollection( offsets=offsets, paths=data["path"], sizes=data["size"], facecolors=data["facecolor"], edgecolors=data["edgecolor"], linewidths=data["linewidth"], linestyles=data["edgestyle"], transOffset=ax.transData, transform=mpl.transforms.IdentityTransform(), **self.artist_kws, ) ax.add_collection(points)
19,260
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/dot.py
DotBase._legend_artist
( self, variables: list[str], value: Any, scales: dict[str, Scale], )
return mpl.collections.PathCollection( paths=[res["path"]], sizes=[res["size"]], facecolors=[res["facecolor"]], edgecolors=[res["edgecolor"]], linewidths=[res["linewidth"]], linestyles=[res["edgestyle"]], transform=mpl.transforms.IdentityTransform(), **self.artist_kws, )
87
103
def _legend_artist( self, variables: list[str], value: Any, scales: dict[str, Scale], ) -> Artist: key = {v: value for v in variables} res = self._resolve_properties(key, scales) return mpl.collections.PathCollection( paths=[res["path"]], sizes=[res["size"]], facecolors=[res["facecolor"]], edgecolors=[res["edgecolor"]], linewidths=[res["linewidth"]], linestyles=[res["edgestyle"]], transform=mpl.transforms.IdentityTransform(), **self.artist_kws, )
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/dot.py#L87-L103
26
[ 0, 3, 4, 5, 6, 7 ]
35.294118
[]
0
false
100
17
1
100
0
def _legend_artist( self, variables: list[str], value: Any, scales: dict[str, Scale], ) -> Artist: key = {v: value for v in variables} res = self._resolve_properties(key, scales) return mpl.collections.PathCollection( paths=[res["path"]], sizes=[res["size"]], facecolors=[res["facecolor"]], edgecolors=[res["edgecolor"]], linewidths=[res["linewidth"]], linestyles=[res["edgestyle"]], transform=mpl.transforms.IdentityTransform(), **self.artist_kws, )
19,261
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/bar.py
BarBase._make_patches
(self, data, scales, orient)
return bars, vals
30
73
def _make_patches(self, data, scales, orient): kws = self._resolve_properties(data, scales) if orient == "x": kws["x"] = (data["x"] - data["width"] / 2).to_numpy() kws["y"] = data["baseline"].to_numpy() kws["w"] = data["width"].to_numpy() kws["h"] = (data["y"] - data["baseline"]).to_numpy() else: kws["x"] = data["baseline"].to_numpy() kws["y"] = (data["y"] - data["width"] / 2).to_numpy() kws["w"] = (data["x"] - data["baseline"]).to_numpy() kws["h"] = data["width"].to_numpy() kws.pop("width", None) kws.pop("baseline", None) val_dim = {"x": "h", "y": "w"}[orient] bars, vals = [], [] for i in range(len(data)): row = {k: v[i] for k, v in kws.items()} # Skip bars with no value. It's possible we'll want to make this # an option (i.e so you have an artist for animating or annotating), # but let's keep things simple for now. if not np.nan_to_num(row[val_dim]): continue bar = mpl.patches.Rectangle( xy=(row["x"], row["y"]), width=row["w"], height=row["h"], facecolor=row["facecolor"], edgecolor=row["edgecolor"], linestyle=row["edgestyle"], linewidth=row["edgewidth"], **self.artist_kws, ) bars.append(bar) vals.append(row[val_dim]) return bars, vals
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/bar.py#L30-L73
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 40, 41, 42, 43 ]
77.272727
[]
0
false
99.193548
44
4
100
0
def _make_patches(self, data, scales, orient): kws = self._resolve_properties(data, scales) if orient == "x": kws["x"] = (data["x"] - data["width"] / 2).to_numpy() kws["y"] = data["baseline"].to_numpy() kws["w"] = data["width"].to_numpy() kws["h"] = (data["y"] - data["baseline"]).to_numpy() else: kws["x"] = data["baseline"].to_numpy() kws["y"] = (data["y"] - data["width"] / 2).to_numpy() kws["w"] = (data["x"] - data["baseline"]).to_numpy() kws["h"] = data["width"].to_numpy() kws.pop("width", None) kws.pop("baseline", None) val_dim = {"x": "h", "y": "w"}[orient] bars, vals = [], [] for i in range(len(data)): row = {k: v[i] for k, v in kws.items()} # Skip bars with no value. It's possible we'll want to make this # an option (i.e so you have an artist for animating or annotating), # but let's keep things simple for now. if not np.nan_to_num(row[val_dim]): continue bar = mpl.patches.Rectangle( xy=(row["x"], row["y"]), width=row["w"], height=row["h"], facecolor=row["facecolor"], edgecolor=row["edgecolor"], linestyle=row["edgestyle"], linewidth=row["edgewidth"], **self.artist_kws, ) bars.append(bar) vals.append(row[val_dim]) return bars, vals
19,262
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/bar.py
BarBase._resolve_properties
(self, data, scales)
return resolved
75
89
def _resolve_properties(self, data, scales): resolved = resolve_properties(self, data, scales) resolved["facecolor"] = resolve_color(self, data, "", scales) resolved["edgecolor"] = resolve_color(self, data, "edge", scales) fc = resolved["facecolor"] if isinstance(fc, tuple): resolved["facecolor"] = fc[0], fc[1], fc[2], fc[3] * resolved["fill"] else: fc[:, 3] = fc[:, 3] * resolved["fill"] # TODO Is inplace mod a problem? resolved["facecolor"] = fc return resolved
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/bar.py#L75-L89
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14 ]
93.333333
[]
0
false
99.193548
15
2
100
0
def _resolve_properties(self, data, scales): resolved = resolve_properties(self, data, scales) resolved["facecolor"] = resolve_color(self, data, "", scales) resolved["edgecolor"] = resolve_color(self, data, "edge", scales) fc = resolved["facecolor"] if isinstance(fc, tuple): resolved["facecolor"] = fc[0], fc[1], fc[2], fc[3] * resolved["fill"] else: fc[:, 3] = fc[:, 3] * resolved["fill"] # TODO Is inplace mod a problem? resolved["facecolor"] = fc return resolved
19,263
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/bar.py
BarBase._legend_artist
( self, variables: list[str], value: Any, scales: dict[str, Scale], )
return artist
91
103
def _legend_artist( self, variables: list[str], value: Any, scales: dict[str, Scale], ) -> Artist: # TODO return some sensible default? key = {v: value for v in variables} key = self._resolve_properties(key, scales) artist = mpl.patches.Patch( facecolor=key["facecolor"], edgecolor=key["edgecolor"], linewidth=key["edgewidth"], linestyle=key["edgestyle"], ) return artist
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/bar.py#L91-L103
26
[ 0, 3, 4, 5, 6, 12 ]
46.153846
[]
0
false
99.193548
13
1
100
0
def _legend_artist( self, variables: list[str], value: Any, scales: dict[str, Scale], ) -> Artist: # TODO return some sensible default? key = {v: value for v in variables} key = self._resolve_properties(key, scales) artist = mpl.patches.Patch( facecolor=key["facecolor"], edgecolor=key["edgecolor"], linewidth=key["edgewidth"], linestyle=key["edgestyle"], ) return artist
19,264
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/base.py
resolve_properties
( mark: Mark, data: DataFrame, scales: dict[str, Scale] )
return props
231
238
def resolve_properties( mark: Mark, data: DataFrame, scales: dict[str, Scale] ) -> dict[str, Any]: props = { name: mark._resolve(data, name, scales) for name in mark._mappable_props } return props
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/base.py#L231-L238
26
[ 0, 3, 4, 7 ]
50
[]
0
false
98.473282
8
1
100
0
def resolve_properties( mark: Mark, data: DataFrame, scales: dict[str, Scale] ) -> dict[str, Any]: props = { name: mark._resolve(data, name, scales) for name in mark._mappable_props } return props
19,265
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/base.py
resolve_color
( mark: Mark, data: DataFrame | dict, prefix: str = "", scales: dict[str, Scale] | None = None, )
Obtain a default, specified, or mapped value for a color feature. This method exists separately to support the relationship between a color and its corresponding alpha. We want to respect alpha values that are passed in specified (or mapped) color values but also make use of a separate `alpha` variable, which can be mapped. This approach may also be extended to support mapping of specific color channels (i.e. luminance, chroma) in the future. Parameters ---------- mark : Mark with the color property. data : Container with data values for features that will be semantically mapped. prefix : Support "color", "fillcolor", etc.
Obtain a default, specified, or mapped value for a color feature.
241
291
def resolve_color( mark: Mark, data: DataFrame | dict, prefix: str = "", scales: dict[str, Scale] | None = None, ) -> RGBATuple | ndarray: """ Obtain a default, specified, or mapped value for a color feature. This method exists separately to support the relationship between a color and its corresponding alpha. We want to respect alpha values that are passed in specified (or mapped) color values but also make use of a separate `alpha` variable, which can be mapped. This approach may also be extended to support mapping of specific color channels (i.e. luminance, chroma) in the future. Parameters ---------- mark : Mark with the color property. data : Container with data values for features that will be semantically mapped. prefix : Support "color", "fillcolor", etc. """ color = mark._resolve(data, f"{prefix}color", scales) if f"{prefix}alpha" in mark._mappable_props: alpha = mark._resolve(data, f"{prefix}alpha", scales) else: alpha = mark._resolve(data, "alpha", scales) def visible(x, axis=None): """Detect "invisible" colors to set alpha appropriately.""" # TODO First clause only needed to handle non-rgba arrays, # which we are trying to handle upstream return np.array(x).dtype.kind != "f" or np.isfinite(x).all(axis) # Second check here catches vectors of strings with identity scale # It could probably be handled better upstream. This is a tricky problem if np.ndim(color) < 2 and all(isinstance(x, float) for x in color): if len(color) == 4: return mpl.colors.to_rgba(color) alpha = alpha if visible(color) else np.nan return mpl.colors.to_rgba(color, alpha) else: if np.ndim(color) == 2 and color.shape[1] == 4: return mpl.colors.to_rgba_array(color) alpha = np.where(visible(color, axis=1), alpha, np.nan) return mpl.colors.to_rgba_array(color, alpha)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/base.py#L241-L291
26
[ 0, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 49, 50 ]
50.980392
[ 48 ]
1.960784
false
98.473282
51
9
98.039216
17
def resolve_color( mark: Mark, data: DataFrame | dict, prefix: str = "", scales: dict[str, Scale] | None = None, ) -> RGBATuple | ndarray: color = mark._resolve(data, f"{prefix}color", scales) if f"{prefix}alpha" in mark._mappable_props: alpha = mark._resolve(data, f"{prefix}alpha", scales) else: alpha = mark._resolve(data, "alpha", scales) def visible(x, axis=None): # TODO First clause only needed to handle non-rgba arrays, # which we are trying to handle upstream return np.array(x).dtype.kind != "f" or np.isfinite(x).all(axis) # Second check here catches vectors of strings with identity scale # It could probably be handled better upstream. This is a tricky problem if np.ndim(color) < 2 and all(isinstance(x, float) for x in color): if len(color) == 4: return mpl.colors.to_rgba(color) alpha = alpha if visible(color) else np.nan return mpl.colors.to_rgba(color, alpha) else: if np.ndim(color) == 2 and color.shape[1] == 4: return mpl.colors.to_rgba_array(color) alpha = np.where(visible(color, axis=1), alpha, np.nan) return mpl.colors.to_rgba_array(color, alpha)
19,266
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/base.py
document_properties
(mark)
return mark
297
316
def document_properties(mark): properties = [f.name for f in fields(mark) if isinstance(f.default, Mappable)] text = [ "", " This mark defines the following properties:", textwrap.fill( ", ".join([f"|{p}|" for p in properties]), width=78, initial_indent=" " * 8, subsequent_indent=" " * 8, ), ] docstring_lines = mark.__doc__.split("\n") new_docstring = "\n".join([ *docstring_lines[:2], *text, *docstring_lines[2:], ]) mark.__doc__ = new_docstring return mark
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/base.py#L297-L316
26
[ 0, 1, 2, 3, 11, 12, 13, 18, 19 ]
45
[]
0
false
98.473282
20
3
100
0
def document_properties(mark): properties = [f.name for f in fields(mark) if isinstance(f.default, Mappable)] text = [ "", " This mark defines the following properties:", textwrap.fill( ", ".join([f"|{p}|" for p in properties]), width=78, initial_indent=" " * 8, subsequent_indent=" " * 8, ), ] docstring_lines = mark.__doc__.split("\n") new_docstring = "\n".join([ *docstring_lines[:2], *text, *docstring_lines[2:], ]) mark.__doc__ = new_docstring return mark
19,267
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/base.py
Mappable.__init__
( self, val: Any = None, depend: str | None = None, rc: str | None = None, auto: bool = False, grouping: bool = True, )
Property that can be mapped from data or set directly, with flexible defaults. Parameters ---------- val : Any Use this value as the default. depend : str Use the value of this feature as the default. rc : str Use the value of this rcParam as the default. auto : bool The default value will depend on other parameters at compile time. grouping : bool If True, use the mapped variable to define groups.
Property that can be mapped from data or set directly, with flexible defaults.
27
61
def __init__( self, val: Any = None, depend: str | None = None, rc: str | None = None, auto: bool = False, grouping: bool = True, ): """ Property that can be mapped from data or set directly, with flexible defaults. Parameters ---------- val : Any Use this value as the default. depend : str Use the value of this feature as the default. rc : str Use the value of this rcParam as the default. auto : bool The default value will depend on other parameters at compile time. grouping : bool If True, use the mapped variable to define groups. """ if depend is not None: assert depend in PROPERTIES if rc is not None: assert rc in mpl.rcParams self._val = val self._rc = rc self._depend = depend self._auto = auto self._grouping = grouping
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/base.py#L27-L61
26
[ 0, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34 ]
34.285714
[]
0
false
98.473282
35
5
100
14
def __init__( self, val: Any = None, depend: str | None = None, rc: str | None = None, auto: bool = False, grouping: bool = True, ): if depend is not None: assert depend in PROPERTIES if rc is not None: assert rc in mpl.rcParams self._val = val self._rc = rc self._depend = depend self._auto = auto self._grouping = grouping
19,268
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/base.py
Mappable.__repr__
(self)
return s
Nice formatting for when object appears in Mark init signature.
Nice formatting for when object appears in Mark init signature.
63
75
def __repr__(self): """Nice formatting for when object appears in Mark init signature.""" if self._val is not None: s = f"<{repr(self._val)}>" elif self._depend is not None: s = f"<depend:{self._depend}>" elif self._rc is not None: s = f"<rc:{self._rc}>" elif self._auto: s = "<auto>" else: s = "<undefined>" return s
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/base.py#L63-L75
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12 ]
92.307692
[ 11 ]
7.692308
false
98.473282
13
5
92.307692
1
def __repr__(self): if self._val is not None: s = f"<{repr(self._val)}>" elif self._depend is not None: s = f"<depend:{self._depend}>" elif self._rc is not None: s = f"<rc:{self._rc}>" elif self._auto: s = "<auto>" else: s = "<undefined>" return s
19,269
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/base.py
Mappable.depend
(self)
return self._depend
Return the name of the feature to source a default value from.
Return the name of the feature to source a default value from.
78
80
def depend(self) -> Any: """Return the name of the feature to source a default value from.""" return self._depend
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/base.py#L78-L80
26
[ 0, 1, 2 ]
100
[]
0
true
98.473282
3
1
100
1
def depend(self) -> Any: return self._depend
19,270
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/base.py
Mappable.grouping
(self)
return self._grouping
83
84
def grouping(self) -> bool: return self._grouping
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/base.py#L83-L84
26
[ 0, 1 ]
100
[]
0
true
98.473282
2
1
100
0
def grouping(self) -> bool: return self._grouping
19,271
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/base.py
Mappable.default
(self)
return mpl.rcParams.get(self._rc)
Get the default value for this feature, or access the relevant rcParam.
Get the default value for this feature, or access the relevant rcParam.
87
91
def default(self) -> Any: """Get the default value for this feature, or access the relevant rcParam.""" if self._val is not None: return self._val return mpl.rcParams.get(self._rc)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/base.py#L87-L91
26
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
98.473282
5
2
100
1
def default(self) -> Any: if self._val is not None: return self._val return mpl.rcParams.get(self._rc)
19,272
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/area.py
AreaBase._plot
(self, split_gen, scales, orient)
23
51
def _plot(self, split_gen, scales, orient): patches = defaultdict(list) for keys, data, ax in split_gen(): kws = {} data = self._standardize_coordinate_parameters(data, orient) resolved = resolve_properties(self, keys, scales) verts = self._get_verts(data, orient) ax.update_datalim(verts) # TODO should really move this logic into resolve_color fc = resolve_color(self, keys, "", scales) if not resolved["fill"]: fc = mpl.colors.to_rgba(fc, 0) kws["facecolor"] = fc kws["edgecolor"] = resolve_color(self, keys, "edge", scales) kws["linewidth"] = resolved["edgewidth"] kws["linestyle"] = resolved["edgestyle"] patches[ax].append(mpl.patches.Polygon(verts, **kws)) for ax, ax_patches in patches.items(): for patch in ax_patches: self._postprocess_artist(patch, ax, orient) ax.add_patch(patch)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/area.py#L23-L51
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 ]
100
[]
0
true
96.511628
29
5
100
0
def _plot(self, split_gen, scales, orient): patches = defaultdict(list) for keys, data, ax in split_gen(): kws = {} data = self._standardize_coordinate_parameters(data, orient) resolved = resolve_properties(self, keys, scales) verts = self._get_verts(data, orient) ax.update_datalim(verts) # TODO should really move this logic into resolve_color fc = resolve_color(self, keys, "", scales) if not resolved["fill"]: fc = mpl.colors.to_rgba(fc, 0) kws["facecolor"] = fc kws["edgecolor"] = resolve_color(self, keys, "edge", scales) kws["linewidth"] = resolved["edgewidth"] kws["linestyle"] = resolved["edgestyle"] patches[ax].append(mpl.patches.Polygon(verts, **kws)) for ax, ax_patches in patches.items(): for patch in ax_patches: self._postprocess_artist(patch, ax, orient) ax.add_patch(patch)
19,273
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/area.py
AreaBase._standardize_coordinate_parameters
(self, data, orient)
return data
53
54
def _standardize_coordinate_parameters(self, data, orient): return data
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/area.py#L53-L54
26
[ 0 ]
50
[ 1 ]
50
false
96.511628
2
1
50
0
def _standardize_coordinate_parameters(self, data, orient): return data
19,274
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/area.py
AreaBase._get_verts
(self, data, orient)
return verts
59
69
def _get_verts(self, data, orient): dv = {"x": "y", "y": "x"}[orient] data = data.sort_values(orient, kind="mergesort") verts = np.concatenate([ data[[orient, f"{dv}min"]].to_numpy(), data[[orient, f"{dv}max"]].to_numpy()[::-1], ]) if orient == "y": verts = verts[:, ::-1] return verts
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/area.py#L59-L69
26
[ 0, 1, 2, 3, 4, 8, 10 ]
63.636364
[ 9 ]
9.090909
false
96.511628
11
2
90.909091
0
def _get_verts(self, data, orient): dv = {"x": "y", "y": "x"}[orient] data = data.sort_values(orient, kind="mergesort") verts = np.concatenate([ data[[orient, f"{dv}min"]].to_numpy(), data[[orient, f"{dv}max"]].to_numpy()[::-1], ]) if orient == "y": verts = verts[:, ::-1] return verts
19,275
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_marks/area.py
AreaBase._legend_artist
(self, variables, value, scales)
return mpl.patches.Patch( facecolor=fc, edgecolor=resolve_color(self, keys, "edge", scales), linewidth=resolved["edgewidth"], linestyle=resolved["edgestyle"], **self.artist_kws, )
71
86
def _legend_artist(self, variables, value, scales): keys = {v: value for v in variables} resolved = resolve_properties(self, keys, scales) fc = resolve_color(self, keys, "", scales) if not resolved["fill"]: fc = mpl.colors.to_rgba(fc, 0) return mpl.patches.Patch( facecolor=fc, edgecolor=resolve_color(self, keys, "edge", scales), linewidth=resolved["edgewidth"], linestyle=resolved["edgestyle"], **self.artist_kws, )
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_marks/area.py#L71-L86
26
[ 0, 1, 2, 3, 4, 5, 6, 8, 9 ]
56.25
[ 7 ]
6.25
false
96.511628
16
2
93.75
0
def _legend_artist(self, variables, value, scales): keys = {v: value for v in variables} resolved = resolve_properties(self, keys, scales) fc = resolve_color(self, keys, "", scales) if not resolved["fill"]: fc = mpl.colors.to_rgba(fc, 0) return mpl.patches.Patch( facecolor=fc, edgecolor=resolve_color(self, keys, "edge", scales), linewidth=resolved["edgewidth"], linestyle=resolved["edgestyle"], **self.artist_kws, )
19,276
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/plot.py
theme_context
(params: dict[str, Any])
Temporarily modify specifc matplotlib rcParams.
Temporarily modify specifc matplotlib rcParams.
94
111
def theme_context(params: dict[str, Any]) -> Generator: """Temporarily modify specifc matplotlib rcParams.""" orig_params = {k: mpl.rcParams[k] for k in params} color_codes = "bgrmyck" nice_colors = [*color_palette("deep6"), (.15, .15, .15)] orig_colors = [mpl.colors.colorConverter.colors[x] for x in color_codes] # TODO how to allow this to reflect the color cycle when relevant? try: mpl.rcParams.update(params) for (code, color) in zip(color_codes, nice_colors): mpl.colors.colorConverter.colors[code] = color mpl.colors.colorConverter.cache[code] = color yield finally: mpl.rcParams.update(orig_params) for (code, color) in zip(color_codes, orig_colors): mpl.colors.colorConverter.colors[code] = color mpl.colors.colorConverter.cache[code] = color
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/plot.py#L94-L111
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
100
[]
0
true
98.089172
18
4
100
1
def theme_context(params: dict[str, Any]) -> Generator: orig_params = {k: mpl.rcParams[k] for k in params} color_codes = "bgrmyck" nice_colors = [*color_palette("deep6"), (.15, .15, .15)] orig_colors = [mpl.colors.colorConverter.colors[x] for x in color_codes] # TODO how to allow this to reflect the color cycle when relevant? try: mpl.rcParams.update(params) for (code, color) in zip(color_codes, nice_colors): mpl.colors.colorConverter.colors[code] = color mpl.colors.colorConverter.cache[code] = color yield finally: mpl.rcParams.update(orig_params) for (code, color) in zip(color_codes, orig_colors): mpl.colors.colorConverter.colors[code] = color mpl.colors.colorConverter.cache[code] = color
19,277
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/plot.py
build_plot_signature
(cls)
return cls
Decorator function for giving Plot a useful signature. Currently this mostly saves us some duplicated typing, but we would like eventually to have a way of registering new semantic properties, at which point dynamic signature generation would become more important.
Decorator function for giving Plot a useful signature.
114
143
def build_plot_signature(cls): """ Decorator function for giving Plot a useful signature. Currently this mostly saves us some duplicated typing, but we would like eventually to have a way of registering new semantic properties, at which point dynamic signature generation would become more important. """ sig = inspect.signature(cls) params = [ inspect.Parameter("args", inspect.Parameter.VAR_POSITIONAL), inspect.Parameter("data", inspect.Parameter.KEYWORD_ONLY, default=None) ] params.extend([ inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, default=None) for name in PROPERTIES ]) new_sig = sig.replace(parameters=params) cls.__signature__ = new_sig known_properties = textwrap.fill( ", ".join([f"|{p}|" for p in PROPERTIES]), width=78, subsequent_indent=" " * 8, ) if cls.__doc__ is not None: # support python -OO mode cls.__doc__ = cls.__doc__.format(known_properties=known_properties) return cls
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/plot.py#L114-L143
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
98.089172
30
4
100
5
def build_plot_signature(cls): sig = inspect.signature(cls) params = [ inspect.Parameter("args", inspect.Parameter.VAR_POSITIONAL), inspect.Parameter("data", inspect.Parameter.KEYWORD_ONLY, default=None) ] params.extend([ inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, default=None) for name in PROPERTIES ]) new_sig = sig.replace(parameters=params) cls.__signature__ = new_sig known_properties = textwrap.fill( ", ".join([f"|{p}|" for p in PROPERTIES]), width=78, subsequent_indent=" " * 8, ) if cls.__doc__ is not None: # support python -OO mode cls.__doc__ = cls.__doc__.format(known_properties=known_properties) return cls
19,278
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/plot.py
__init__
(self)
159
161
def __init__(self): super().__init__() self.reset()
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/plot.py#L159-L161
26
[ 0, 1, 2 ]
100
[]
0
true
98.089172
3
1
100
0
def __init__(self): super().__init__() self.reset()
19,279
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/plot.py
_default
(self)
return { **self._filter_params(mpl.rcParamsDefault), **axes_style("darkgrid"), **plotting_context("notebook"), "axes.prop_cycle": cycler("color", color_palette("deep")), }
164
171
def _default(self) -> dict[str, Any]: return { **self._filter_params(mpl.rcParamsDefault), **axes_style("darkgrid"), **plotting_context("notebook"), "axes.prop_cycle": cycler("color", color_palette("deep")), }
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/plot.py#L164-L171
26
[ 0, 1, 2 ]
37.5
[]
0
false
98.089172
8
1
100
0
def _default(self) -> dict[str, Any]: return { **self._filter_params(mpl.rcParamsDefault), **axes_style("darkgrid"), **plotting_context("notebook"), "axes.prop_cycle": cycler("color", color_palette("deep")), }
19,280
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/plot.py
reset
(self)
Update the theme dictionary with seaborn's default values.
Update the theme dictionary with seaborn's default values.
173
175
def reset(self) -> None: """Update the theme dictionary with seaborn's default values.""" self.update(self._default)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/plot.py#L173-L175
26
[ 0, 1, 2 ]
100
[]
0
true
98.089172
3
1
100
1
def reset(self) -> None: self.update(self._default)
19,281
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/subplots.py
Subplots.__init__
( self, subplot_spec: dict, # TODO define as TypedDict facet_spec: FacetSpec, pair_spec: PairSpec, )
32
44
def __init__( self, subplot_spec: dict, # TODO define as TypedDict facet_spec: FacetSpec, pair_spec: PairSpec, ): self.subplot_spec = subplot_spec self._check_dimension_uniqueness(facet_spec, pair_spec) self._determine_grid_dimensions(facet_spec, pair_spec) self._handle_wrapping(facet_spec, pair_spec) self._determine_axis_sharing(pair_spec)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/subplots.py#L32-L44
26
[ 0, 6, 7, 8, 9, 10, 11, 12 ]
61.538462
[]
0
false
98.611111
13
1
100
0
def __init__( self, subplot_spec: dict, # TODO define as TypedDict facet_spec: FacetSpec, pair_spec: PairSpec, ): self.subplot_spec = subplot_spec self._check_dimension_uniqueness(facet_spec, pair_spec) self._determine_grid_dimensions(facet_spec, pair_spec) self._handle_wrapping(facet_spec, pair_spec) self._determine_axis_sharing(pair_spec)
19,282
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/subplots.py
Subplots._check_dimension_uniqueness
( self, facet_spec: FacetSpec, pair_spec: PairSpec )
Reject specs that pair and facet on (or wrap to) same figure dimension.
Reject specs that pair and facet on (or wrap to) same figure dimension.
46
76
def _check_dimension_uniqueness( self, facet_spec: FacetSpec, pair_spec: PairSpec ) -> None: """Reject specs that pair and facet on (or wrap to) same figure dimension.""" err = None facet_vars = facet_spec.get("variables", {}) if facet_spec.get("wrap") and {"col", "row"} <= set(facet_vars): err = "Cannot wrap facets when specifying both `col` and `row`." elif ( pair_spec.get("wrap") and pair_spec.get("cross", True) and len(pair_spec.get("structure", {}).get("x", [])) > 1 and len(pair_spec.get("structure", {}).get("y", [])) > 1 ): err = "Cannot wrap subplots when pairing on both `x` and `y`." collisions = {"x": ["columns", "rows"], "y": ["rows", "columns"]} for pair_axis, (multi_dim, wrap_dim) in collisions.items(): if pair_axis not in pair_spec.get("structure", {}): continue elif multi_dim[:3] in facet_vars: err = f"Cannot facet the {multi_dim} while pairing on `{pair_axis}``." elif wrap_dim[:3] in facet_vars and facet_spec.get("wrap"): err = f"Cannot wrap the {wrap_dim} while pairing on `{pair_axis}``." elif wrap_dim[:3] in facet_vars and pair_spec.get("wrap"): err = f"Cannot wrap the {multi_dim} while faceting the {wrap_dim}." if err is not None: raise RuntimeError(err)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/subplots.py#L46-L76
26
[ 0, 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 ]
93.548387
[]
0
false
98.611111
31
15
100
1
def _check_dimension_uniqueness( self, facet_spec: FacetSpec, pair_spec: PairSpec ) -> None: err = None facet_vars = facet_spec.get("variables", {}) if facet_spec.get("wrap") and {"col", "row"} <= set(facet_vars): err = "Cannot wrap facets when specifying both `col` and `row`." elif ( pair_spec.get("wrap") and pair_spec.get("cross", True) and len(pair_spec.get("structure", {}).get("x", [])) > 1 and len(pair_spec.get("structure", {}).get("y", [])) > 1 ): err = "Cannot wrap subplots when pairing on both `x` and `y`." collisions = {"x": ["columns", "rows"], "y": ["rows", "columns"]} for pair_axis, (multi_dim, wrap_dim) in collisions.items(): if pair_axis not in pair_spec.get("structure", {}): continue elif multi_dim[:3] in facet_vars: err = f"Cannot facet the {multi_dim} while pairing on `{pair_axis}``." elif wrap_dim[:3] in facet_vars and facet_spec.get("wrap"): err = f"Cannot wrap the {wrap_dim} while pairing on `{pair_axis}``." elif wrap_dim[:3] in facet_vars and pair_spec.get("wrap"): err = f"Cannot wrap the {multi_dim} while faceting the {wrap_dim}." if err is not None: raise RuntimeError(err)
19,283
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/subplots.py
Subplots._determine_grid_dimensions
( self, facet_spec: FacetSpec, pair_spec: PairSpec )
Parse faceting and pairing information to define figure structure.
Parse faceting and pairing information to define figure structure.
78
100
def _determine_grid_dimensions( self, facet_spec: FacetSpec, pair_spec: PairSpec ) -> None: """Parse faceting and pairing information to define figure structure.""" self.grid_dimensions: dict[str, list] = {} for dim, axis in zip(["col", "row"], ["x", "y"]): facet_vars = facet_spec.get("variables", {}) if dim in facet_vars: self.grid_dimensions[dim] = facet_spec["structure"][dim] elif axis in pair_spec.get("structure", {}): self.grid_dimensions[dim] = [ None for _ in pair_spec.get("structure", {})[axis] ] else: self.grid_dimensions[dim] = [None] self.subplot_spec[f"n{dim}s"] = len(self.grid_dimensions[dim]) if not pair_spec.get("cross", True): self.subplot_spec["nrows"] = 1 self.n_subplots = self.subplot_spec["ncols"] * self.subplot_spec["nrows"]
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/subplots.py#L78-L100
26
[ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
91.304348
[]
0
false
98.611111
23
6
100
1
def _determine_grid_dimensions( self, facet_spec: FacetSpec, pair_spec: PairSpec ) -> None: self.grid_dimensions: dict[str, list] = {} for dim, axis in zip(["col", "row"], ["x", "y"]): facet_vars = facet_spec.get("variables", {}) if dim in facet_vars: self.grid_dimensions[dim] = facet_spec["structure"][dim] elif axis in pair_spec.get("structure", {}): self.grid_dimensions[dim] = [ None for _ in pair_spec.get("structure", {})[axis] ] else: self.grid_dimensions[dim] = [None] self.subplot_spec[f"n{dim}s"] = len(self.grid_dimensions[dim]) if not pair_spec.get("cross", True): self.subplot_spec["nrows"] = 1 self.n_subplots = self.subplot_spec["ncols"] * self.subplot_spec["nrows"]
19,284
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/subplots.py
Subplots._handle_wrapping
( self, facet_spec: FacetSpec, pair_spec: PairSpec )
Update figure structure parameters based on facet/pair wrapping.
Update figure structure parameters based on facet/pair wrapping.
102
119
def _handle_wrapping( self, facet_spec: FacetSpec, pair_spec: PairSpec ) -> None: """Update figure structure parameters based on facet/pair wrapping.""" self.wrap = wrap = facet_spec.get("wrap") or pair_spec.get("wrap") if not wrap: return wrap_dim = "row" if self.subplot_spec["nrows"] > 1 else "col" flow_dim = {"row": "col", "col": "row"}[wrap_dim] n_subplots = self.subplot_spec[f"n{wrap_dim}s"] flow = int(np.ceil(n_subplots / wrap)) if wrap < self.subplot_spec[f"n{wrap_dim}s"]: self.subplot_spec[f"n{wrap_dim}s"] = wrap self.subplot_spec[f"n{flow_dim}s"] = flow self.n_subplots = n_subplots self.wrap_dim = wrap_dim
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/subplots.py#L102-L119
26
[ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
88.888889
[]
0
false
98.611111
18
4
100
1
def _handle_wrapping( self, facet_spec: FacetSpec, pair_spec: PairSpec ) -> None: self.wrap = wrap = facet_spec.get("wrap") or pair_spec.get("wrap") if not wrap: return wrap_dim = "row" if self.subplot_spec["nrows"] > 1 else "col" flow_dim = {"row": "col", "col": "row"}[wrap_dim] n_subplots = self.subplot_spec[f"n{wrap_dim}s"] flow = int(np.ceil(n_subplots / wrap)) if wrap < self.subplot_spec[f"n{wrap_dim}s"]: self.subplot_spec[f"n{wrap_dim}s"] = wrap self.subplot_spec[f"n{flow_dim}s"] = flow self.n_subplots = n_subplots self.wrap_dim = wrap_dim
19,285
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/subplots.py
Subplots._determine_axis_sharing
(self, pair_spec: PairSpec)
Update subplot spec with default or specified axis sharing parameters.
Update subplot spec with default or specified axis sharing parameters.
121
140
def _determine_axis_sharing(self, pair_spec: PairSpec) -> None: """Update subplot spec with default or specified axis sharing parameters.""" axis_to_dim = {"x": "col", "y": "row"} key: str val: str | bool for axis in "xy": key = f"share{axis}" # Always use user-specified value, if present if key not in self.subplot_spec: if axis in pair_spec.get("structure", {}): # Paired axes are shared along one dimension by default if self.wrap is None and pair_spec.get("cross", True): val = axis_to_dim[axis] else: val = False else: # This will pick up faceted plots, as well as single subplot # figures, where the value doesn't really matter val = True self.subplot_spec[key] = val
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/subplots.py#L121-L140
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
100
[]
0
true
98.611111
20
6
100
1
def _determine_axis_sharing(self, pair_spec: PairSpec) -> None: axis_to_dim = {"x": "col", "y": "row"} key: str val: str | bool for axis in "xy": key = f"share{axis}" # Always use user-specified value, if present if key not in self.subplot_spec: if axis in pair_spec.get("structure", {}): # Paired axes are shared along one dimension by default if self.wrap is None and pair_spec.get("cross", True): val = axis_to_dim[axis] else: val = False else: # This will pick up faceted plots, as well as single subplot # figures, where the value doesn't really matter val = True self.subplot_spec[key] = val
19,286
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/subplots.py
Subplots.init_figure
( self, pair_spec: PairSpec, pyplot: bool = False, figure_kws: dict | None = None, target: Axes | Figure | SubFigure = None, )
return figure
Initialize matplotlib objects and add seaborn-relevant metadata.
Initialize matplotlib objects and add seaborn-relevant metadata.
142
261
def init_figure( self, pair_spec: PairSpec, pyplot: bool = False, figure_kws: dict | None = None, target: Axes | Figure | SubFigure = None, ) -> Figure: """Initialize matplotlib objects and add seaborn-relevant metadata.""" # TODO reduce need to pass pair_spec here? if figure_kws is None: figure_kws = {} if isinstance(target, mpl.axes.Axes): if max(self.subplot_spec["nrows"], self.subplot_spec["ncols"]) > 1: err = " ".join([ "Cannot create multiple subplots after calling `Plot.on` with", f"a {mpl.axes.Axes} object.", ]) try: err += f" You may want to use a {mpl.figure.SubFigure} instead." except AttributeError: # SubFigure added in mpl 3.4 pass raise RuntimeError(err) self._subplot_list = [{ "ax": target, "left": True, "right": True, "top": True, "bottom": True, "col": None, "row": None, "x": "x", "y": "y", }] self._figure = target.figure return self._figure elif ( hasattr(mpl.figure, "SubFigure") # Added in mpl 3.4 and isinstance(target, mpl.figure.SubFigure) ): figure = target.figure elif isinstance(target, mpl.figure.Figure): figure = target else: if pyplot: figure = plt.figure(**figure_kws) else: figure = mpl.figure.Figure(**figure_kws) target = figure self._figure = figure axs = target.subplots(**self.subplot_spec, squeeze=False) if self.wrap: # Remove unused Axes and flatten the rest into a (2D) vector axs_flat = axs.ravel({"col": "C", "row": "F"}[self.wrap_dim]) axs, extra = np.split(axs_flat, [self.n_subplots]) for ax in extra: ax.remove() if self.wrap_dim == "col": axs = axs[np.newaxis, :] else: axs = axs[:, np.newaxis] # Get i, j coordinates for each Axes object # Note that i, j are with respect to faceting/pairing, # not the subplot grid itself, (which only matters in the case of wrapping). iter_axs: np.ndenumerate | zip if not pair_spec.get("cross", True): indices = np.arange(self.n_subplots) iter_axs = zip(zip(indices, indices), axs.flat) else: iter_axs = np.ndenumerate(axs) self._subplot_list = [] for (i, j), ax in iter_axs: info = {"ax": ax} nrows, ncols = self.subplot_spec["nrows"], self.subplot_spec["ncols"] if not self.wrap: info["left"] = j % ncols == 0 info["right"] = (j + 1) % ncols == 0 info["top"] = i == 0 info["bottom"] = i == nrows - 1 elif self.wrap_dim == "col": info["left"] = j % ncols == 0 info["right"] = ((j + 1) % ncols == 0) or ((j + 1) == self.n_subplots) info["top"] = j < ncols info["bottom"] = j >= (self.n_subplots - ncols) elif self.wrap_dim == "row": info["left"] = i < nrows info["right"] = i >= self.n_subplots - nrows info["top"] = i % nrows == 0 info["bottom"] = ((i + 1) % nrows == 0) or ((i + 1) == self.n_subplots) if not pair_spec.get("cross", True): info["top"] = j < ncols info["bottom"] = j >= self.n_subplots - ncols for dim in ["row", "col"]: idx = {"row": i, "col": j}[dim] info[dim] = self.grid_dimensions[dim][idx] for axis in "xy": idx = {"x": j, "y": i}[axis] if axis in pair_spec.get("structure", {}): key = f"{axis}{idx}" else: key = axis info[axis] = key self._subplot_list.append(info) return figure
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/subplots.py#L142-L261
26
[ 0, 9, 10, 11, 12, 13, 14, 15, 16, 20, 21, 24, 25, 26, 37, 38, 39, 40, 44, 45, 46, 48, 49, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68, 69, 70, 72, 73, 74, 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, 114, 115, 116, 117, 118, 119 ]
73.333333
[ 22, 23 ]
1.666667
false
98.611111
120
23
98.333333
1
def init_figure( self, pair_spec: PairSpec, pyplot: bool = False, figure_kws: dict | None = None, target: Axes | Figure | SubFigure = None, ) -> Figure: # TODO reduce need to pass pair_spec here? if figure_kws is None: figure_kws = {} if isinstance(target, mpl.axes.Axes): if max(self.subplot_spec["nrows"], self.subplot_spec["ncols"]) > 1: err = " ".join([ "Cannot create multiple subplots after calling `Plot.on` with", f"a {mpl.axes.Axes} object.", ]) try: err += f" You may want to use a {mpl.figure.SubFigure} instead." except AttributeError: # SubFigure added in mpl 3.4 pass raise RuntimeError(err) self._subplot_list = [{ "ax": target, "left": True, "right": True, "top": True, "bottom": True, "col": None, "row": None, "x": "x", "y": "y", }] self._figure = target.figure return self._figure elif ( hasattr(mpl.figure, "SubFigure") # Added in mpl 3.4 and isinstance(target, mpl.figure.SubFigure) ): figure = target.figure elif isinstance(target, mpl.figure.Figure): figure = target else: if pyplot: figure = plt.figure(**figure_kws) else: figure = mpl.figure.Figure(**figure_kws) target = figure self._figure = figure axs = target.subplots(**self.subplot_spec, squeeze=False) if self.wrap: # Remove unused Axes and flatten the rest into a (2D) vector axs_flat = axs.ravel({"col": "C", "row": "F"}[self.wrap_dim]) axs, extra = np.split(axs_flat, [self.n_subplots]) for ax in extra: ax.remove() if self.wrap_dim == "col": axs = axs[np.newaxis, :] else: axs = axs[:, np.newaxis] # Get i, j coordinates for each Axes object # Note that i, j are with respect to faceting/pairing, # not the subplot grid itself, (which only matters in the case of wrapping). iter_axs: np.ndenumerate | zip if not pair_spec.get("cross", True): indices = np.arange(self.n_subplots) iter_axs = zip(zip(indices, indices), axs.flat) else: iter_axs = np.ndenumerate(axs) self._subplot_list = [] for (i, j), ax in iter_axs: info = {"ax": ax} nrows, ncols = self.subplot_spec["nrows"], self.subplot_spec["ncols"] if not self.wrap: info["left"] = j % ncols == 0 info["right"] = (j + 1) % ncols == 0 info["top"] = i == 0 info["bottom"] = i == nrows - 1 elif self.wrap_dim == "col": info["left"] = j % ncols == 0 info["right"] = ((j + 1) % ncols == 0) or ((j + 1) == self.n_subplots) info["top"] = j < ncols info["bottom"] = j >= (self.n_subplots - ncols) elif self.wrap_dim == "row": info["left"] = i < nrows info["right"] = i >= self.n_subplots - nrows info["top"] = i % nrows == 0 info["bottom"] = ((i + 1) % nrows == 0) or ((i + 1) == self.n_subplots) if not pair_spec.get("cross", True): info["top"] = j < ncols info["bottom"] = j >= self.n_subplots - ncols for dim in ["row", "col"]: idx = {"row": i, "col": j}[dim] info[dim] = self.grid_dimensions[dim][idx] for axis in "xy": idx = {"x": j, "y": i}[axis] if axis in pair_spec.get("structure", {}): key = f"{axis}{idx}" else: key = axis info[axis] = key self._subplot_list.append(info) return figure
19,287
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/subplots.py
Subplots.__iter__
(self)
Yield each subplot dictionary with Axes object and metadata.
Yield each subplot dictionary with Axes object and metadata.
263
265
def __iter__(self) -> Generator[dict, None, None]: # TODO TypedDict? """Yield each subplot dictionary with Axes object and metadata.""" yield from self._subplot_list
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/subplots.py#L263-L265
26
[ 0, 1, 2 ]
100
[]
0
true
98.611111
3
1
100
1
def __iter__(self) -> Generator[dict, None, None]: # TODO TypedDict? yield from self._subplot_list
19,288
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/subplots.py
Subplots.__len__
(self)
return len(self._subplot_list)
Return the number of subplots in this figure.
Return the number of subplots in this figure.
267
269
def __len__(self) -> int: """Return the number of subplots in this figure.""" return len(self._subplot_list)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/subplots.py#L267-L269
26
[ 0, 1, 2 ]
100
[]
0
true
98.611111
3
1
100
1
def __len__(self) -> int: return len(self._subplot_list)
19,289
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/groupby.py
GroupBy.__init__
(self, order: list[str] | dict[str, list | None])
Initialize the GroupBy from grouping variables and optional level orders. Parameters ---------- order List of variable names or dict mapping names to desired level orders. Level order values can be None to use default ordering rules. The variables can include names that are not expected to appear in the data; these will be dropped before the groups are defined.
Initialize the GroupBy from grouping variables and optional level orders.
29
47
def __init__(self, order: list[str] | dict[str, list | None]): """ Initialize the GroupBy from grouping variables and optional level orders. Parameters ---------- order List of variable names or dict mapping names to desired level orders. Level order values can be None to use default ordering rules. The variables can include names that are not expected to appear in the data; these will be dropped before the groups are defined. """ if not order: raise ValueError("GroupBy requires at least one grouping variable") if isinstance(order, list): order = {k: None for k in order} self.order = order
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/groupby.py#L29-L47
26
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
100
[]
0
true
100
19
3
100
9
def __init__(self, order: list[str] | dict[str, list | None]): if not order: raise ValueError("GroupBy requires at least one grouping variable") if isinstance(order, list): order = {k: None for k in order} self.order = order
19,290
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/groupby.py
GroupBy._get_groups
( self, data: DataFrame )
return grouper, groups
Return index with Cartesian product of ordered grouping variable levels.
Return index with Cartesian product of ordered grouping variable levels.
49
71
def _get_groups( self, data: DataFrame ) -> tuple[str | list[str], Index | MultiIndex]: """Return index with Cartesian product of ordered grouping variable levels.""" levels = {} for var, order in self.order.items(): if var in data: if order is None: order = categorical_order(data[var]) levels[var] = order grouper: str | list[str] groups: Index | MultiIndex if not levels: grouper = [] groups = pd.Index([]) elif len(levels) > 1: grouper = list(levels) groups = pd.MultiIndex.from_product(levels.values(), names=grouper) else: grouper, = list(levels) groups = pd.Index(levels[grouper], name=grouper) return grouper, groups
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/groupby.py#L49-L71
26
[ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
91.304348
[]
0
false
100
23
6
100
1
def _get_groups( self, data: DataFrame ) -> tuple[str | list[str], Index | MultiIndex]: levels = {} for var, order in self.order.items(): if var in data: if order is None: order = categorical_order(data[var]) levels[var] = order grouper: str | list[str] groups: Index | MultiIndex if not levels: grouper = [] groups = pd.Index([]) elif len(levels) > 1: grouper = list(levels) groups = pd.MultiIndex.from_product(levels.values(), names=grouper) else: grouper, = list(levels) groups = pd.Index(levels[grouper], name=grouper) return grouper, groups
19,291
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/groupby.py
GroupBy._reorder_columns
(self, res, data)
return res.reindex(columns=pd.Index(cols))
Reorder result columns to match original order with new columns appended.
Reorder result columns to match original order with new columns appended.
73
77
def _reorder_columns(self, res, data): """Reorder result columns to match original order with new columns appended.""" cols = [c for c in data if c in res] cols += [c for c in res if c not in data] return res.reindex(columns=pd.Index(cols))
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/groupby.py#L73-L77
26
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
100
5
3
100
1
def _reorder_columns(self, res, data): cols = [c for c in data if c in res] cols += [c for c in res if c not in data] return res.reindex(columns=pd.Index(cols))
19,292
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/groupby.py
GroupBy.agg
(self, data: DataFrame, *args, **kwargs)
return res
Reduce each group to a single row in the output. The output will have a row for each unique combination of the grouping variable levels with null values for the aggregated variable(s) where those combinations do not appear in the dataset.
Reduce each group to a single row in the output.
79
103
def agg(self, data: DataFrame, *args, **kwargs) -> DataFrame: """ Reduce each group to a single row in the output. The output will have a row for each unique combination of the grouping variable levels with null values for the aggregated variable(s) where those combinations do not appear in the dataset. """ grouper, groups = self._get_groups(data) if not grouper: # We will need to see whether there are valid usecases that end up here raise ValueError("No grouping variables are present in dataframe") res = ( data .groupby(grouper, sort=False, observed=True) .agg(*args, **kwargs) .reindex(groups) .reset_index() .pipe(self._reorder_columns, data) ) return res
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/groupby.py#L79-L103
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
100
25
2
100
5
def agg(self, data: DataFrame, *args, **kwargs) -> DataFrame: grouper, groups = self._get_groups(data) if not grouper: # We will need to see whether there are valid usecases that end up here raise ValueError("No grouping variables are present in dataframe") res = ( data .groupby(grouper, sort=False, observed=True) .agg(*args, **kwargs) .reindex(groups) .reset_index() .pipe(self._reorder_columns, data) ) return res
19,293
mwaskom/seaborn
a47b97e4b98c809db55cbd283de21acba89fe186
seaborn/_core/groupby.py
GroupBy.apply
( self, data: DataFrame, func: Callable[..., DataFrame], *args, **kwargs, )
return self._reorder_columns(res, data)
Apply a DataFrame -> DataFrame mapping to each group.
Apply a DataFrame -> DataFrame mapping to each group.
105
129
def apply( self, data: DataFrame, func: Callable[..., DataFrame], *args, **kwargs, ) -> DataFrame: """Apply a DataFrame -> DataFrame mapping to each group.""" grouper, groups = self._get_groups(data) if not grouper: return self._reorder_columns(func(data, *args, **kwargs), data) parts = {} for key, part_df in data.groupby(grouper, sort=False): parts[key] = func(part_df, *args, **kwargs) stack = [] for key in groups: if key in parts: if isinstance(grouper, list): # Implies that we had a MultiIndex so key is iterable group_ids = dict(zip(grouper, cast(Iterable, key))) else: group_ids = {grouper: key} stack.append(parts[key].assign(**group_ids)) res = pd.concat(stack, ignore_index=True) return self._reorder_columns(res, data)
https://github.com/mwaskom/seaborn/blob/a47b97e4b98c809db55cbd283de21acba89fe186/project26/seaborn/_core/groupby.py#L105-L129
26
[ 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 ]
88
[]
0
false
100
25
6
100
1
def apply( self, data: DataFrame, func: Callable[..., DataFrame], *args, **kwargs, ) -> DataFrame: grouper, groups = self._get_groups(data) if not grouper: return self._reorder_columns(func(data, *args, **kwargs), data) parts = {} for key, part_df in data.groupby(grouper, sort=False): parts[key] = func(part_df, *args, **kwargs) stack = [] for key in groups: if key in parts: if isinstance(grouper, list): # Implies that we had a MultiIndex so key is iterable group_ids = dict(zip(grouper, cast(Iterable, key))) else: group_ids = {grouper: key} stack.append(parts[key].assign(**group_ids)) res = pd.concat(stack, ignore_index=True) return self._reorder_columns(res, data)
19,294