0
# Grid Plots
1
2
Build complex multi-panel figures with FacetGrid, PairGrid, and JointGrid for comprehensive data exploration, pairwise relationship analysis, and bivariate plots with marginal distributions. These classes provide flexible frameworks for creating sophisticated statistical visualizations.
3
4
## Capabilities
5
6
### FacetGrid Class
7
8
Multi-plot grid for plotting conditional relationships across subsets of data.
9
10
```python { .api }
11
class FacetGrid:
12
def __init__(
13
self,
14
data,
15
*,
16
row=None,
17
col=None,
18
hue=None,
19
col_wrap=None,
20
sharex=True,
21
sharey=True,
22
height=3,
23
aspect=1,
24
palette=None,
25
row_order=None,
26
col_order=None,
27
hue_order=None,
28
hue_kws=None,
29
dropna=False,
30
legend_out=True,
31
despine=True,
32
margin_titles=False,
33
xlim=None,
34
ylim=None,
35
subplot_kws=None,
36
gridspec_kws=None,
37
**kwargs
38
):
39
"""
40
Initialize the matplotlib figure and FacetGrid object.
41
42
Parameters:
43
- data: DataFrame, tidy dataset for plotting
44
- row, col: str, variables for faceting into subplots
45
- hue: str, grouping variable for color mapping
46
- col_wrap: int, wrap columns after this number
47
- sharex, sharey: bool, share axes across subplots
48
- height: float, height of each facet in inches
49
- aspect: float, aspect ratio of each facet
50
- palette: str or list, colors for hue levels
51
- row_order, col_order, hue_order: list, order for categorical levels
52
- dropna: bool, drop missing values before plotting
53
- legend_out: bool, draw legend outside the figure
54
- margin_titles: bool, draw titles on the margins
55
"""
56
57
def map(self, func, *args, **kwargs):
58
"""
59
Apply a plotting function to each facet's subset of data.
60
61
Parameters:
62
- func: callable, plotting function
63
- args: positional arguments for func
64
- kwargs: keyword arguments for func
65
"""
66
67
def map_dataframe(self, func, *args, **kwargs):
68
"""
69
Like map but passes the DataFrame to the function.
70
"""
71
72
def add_legend(self, legend_data=None, title=None, label_order=None, **kwargs):
73
"""Add a legend to the figure."""
74
75
def savefig(self, *args, **kwargs):
76
"""Save the figure."""
77
```
78
79
### PairGrid Class
80
81
Subplot grid for plotting pairwise relationships in a dataset.
82
83
```python { .api }
84
class PairGrid:
85
def __init__(
86
self,
87
data,
88
*,
89
hue=None,
90
vars=None,
91
x_vars=None,
92
y_vars=None,
93
hue_order=None,
94
palette=None,
95
hue_kws=None,
96
corner=False,
97
diag_sharey=True,
98
height=2.5,
99
aspect=1,
100
layout_pad=0.5,
101
despine=True,
102
dropna=False,
103
**kwargs
104
):
105
"""
106
Initialize the plot figure and PairGrid object.
107
108
Parameters:
109
- data: DataFrame, tidy dataset for plotting
110
- hue: str, grouping variable for color mapping
111
- vars: list, variables to include in grid
112
- x_vars, y_vars: list, separate variables for x and y axes
113
- corner: bool, plot only lower triangle
114
- diag_sharey: bool, share y-axis on diagonal plots
115
- height: float, height of each facet in inches
116
- aspect: float, aspect ratio of each facet
117
"""
118
119
def map(self, func, **kwargs):
120
"""Plot with the same function in every subplot."""
121
122
def map_diag(self, func, **kwargs):
123
"""Plot with a univariate function on the diagonal subplots."""
124
125
def map_upper(self, func, **kwargs):
126
"""Plot with a bivariate function on the upper triangle."""
127
128
def map_lower(self, func, **kwargs):
129
"""Plot with a bivariate function on the lower triangle."""
130
131
def map_offdiag(self, func, **kwargs):
132
"""Plot with a bivariate function on the off-diagonal subplots."""
133
134
def add_legend(self, legend_data=None, title=None, label_order=None, **kwargs):
135
"""Add a legend to the figure."""
136
```
137
138
### JointGrid Class
139
140
Grid for drawing bivariate plots with marginal univariate plots.
141
142
```python { .api }
143
class JointGrid:
144
def __init__(
145
self,
146
data=None,
147
*,
148
x=None,
149
y=None,
150
hue=None,
151
height=6,
152
ratio=5,
153
space=0.2,
154
dropna=False,
155
xlim=None,
156
ylim=None,
157
marginal_ticks=False,
158
hue_order=None,
159
palette=None,
160
hue_kws=None,
161
**kwargs
162
):
163
"""
164
Set up the grid of subplots and store data internally.
165
166
Parameters:
167
- data: DataFrame, tidy dataset
168
- x, y: str, variable names in data
169
- hue: str, grouping variable for color mapping
170
- height: float, size of the figure (square)
171
- ratio: float, ratio of joint axes height to marginal axes height
172
- space: float, space between joint and marginal axes
173
- marginal_ticks: bool, show ticks on marginal axes
174
"""
175
176
def plot(self, joint_func, marginal_func, **kwargs):
177
"""Plot joint and marginal distributions."""
178
179
def plot_joint(self, func, **kwargs):
180
"""Draw a bivariate plot on the joint axes."""
181
182
def plot_marginals(self, func, **kwargs):
183
"""Draw univariate plots on the marginal axes."""
184
185
def refline(self, *, x=None, y=None, joint=True, marginal=True, **line_kws):
186
"""Add reference lines to the plot."""
187
```
188
189
### Pair Plot Function
190
191
Plot pairwise relationships in a dataset using a PairGrid.
192
193
```python { .api }
194
def pairplot(
195
data,
196
*,
197
hue=None,
198
hue_order=None,
199
palette=None,
200
vars=None,
201
x_vars=None,
202
y_vars=None,
203
kind="scatter",
204
diag_kind="auto",
205
markers=None,
206
height=2.5,
207
aspect=1,
208
corner=False,
209
dropna=False,
210
plot_kws=None,
211
diag_kws=None,
212
grid_kws=None,
213
**kwargs
214
):
215
"""
216
Plot pairwise relationships in a dataset.
217
218
Parameters:
219
- data: DataFrame, tidy dataset for plotting
220
- hue: str, grouping variable for color mapping
221
- vars: list, variables to include
222
- kind: str, plot type for off-diagonal ("scatter", "kde", "hist", "reg")
223
- diag_kind: str, plot type for diagonal ("auto", "hist", "kde", None)
224
- markers: str or list, marker styles for hue levels
225
- height: float, height of each facet
226
- corner: bool, plot only lower triangle
227
- plot_kws: dict, keyword arguments for off-diagonal plots
228
- diag_kws: dict, keyword arguments for diagonal plots
229
- grid_kws: dict, keyword arguments for PairGrid
230
231
Returns:
232
PairGrid object
233
"""
234
```
235
236
### Joint Plot Function
237
238
Draw bivariate plots with marginal univariate plots.
239
240
```python { .api }
241
def jointplot(
242
data=None,
243
*,
244
x=None,
245
y=None,
246
hue=None,
247
kind="scatter",
248
height=6,
249
ratio=5,
250
space=0.2,
251
dropna=False,
252
xlim=None,
253
ylim=None,
254
color=None,
255
palette=None,
256
hue_order=None,
257
hue_norm=None,
258
marginal_ticks=False,
259
joint_kws=None,
260
marginal_kws=None,
261
**kwargs
262
):
263
"""
264
Draw a plot of two variables with bivariate and univariate graphs.
265
266
Parameters:
267
- data: DataFrame, tidy dataset
268
- x, y: str, variable names in data
269
- hue: str, grouping variable for color mapping
270
- kind: str, plot type ("scatter", "kde", "hist", "hex", "reg", "resid")
271
- height: float, size of the figure (square)
272
- ratio: float, ratio of joint to marginal axes
273
- space: float, space between joint and marginal axes
274
- joint_kws: dict, keyword arguments for joint plot
275
- marginal_kws: dict, keyword arguments for marginal plots
276
277
Returns:
278
JointGrid object
279
"""
280
```
281
282
## Usage Examples
283
284
### FacetGrid with Custom Function
285
286
```python
287
import seaborn as sns
288
import matplotlib.pyplot as plt
289
290
tips = sns.load_dataset("tips")
291
292
# Create FacetGrid and map a plotting function
293
g = sns.FacetGrid(tips, col="time", row="smoker", height=4)
294
g.map(sns.scatterplot, "total_bill", "tip", alpha=0.7)
295
g.add_legend()
296
plt.show()
297
```
298
299
### FacetGrid with Multiple Functions
300
301
```python
302
# Map different functions to the same grid
303
g = sns.FacetGrid(tips, col="day", hue="smoker", height=4)
304
g.map(sns.scatterplot, "total_bill", "tip", alpha=0.7)
305
g.map(sns.regplot, "total_bill", "tip", scatter=False)
306
g.add_legend()
307
plt.show()
308
```
309
310
### PairGrid with Different Plot Types
311
312
```python
313
iris = sns.load_dataset("iris")
314
315
# Create PairGrid and map different functions
316
g = sns.PairGrid(iris, hue="species")
317
g.map_diag(sns.histplot)
318
g.map_upper(sns.scatterplot)
319
g.map_lower(sns.kdeplot)
320
g.add_legend()
321
plt.show()
322
```
323
324
### Pair Plot
325
326
```python
327
# Quick pairwise relationships
328
sns.pairplot(iris, hue="species", diag_kind="kde")
329
plt.show()
330
```
331
332
### JointGrid with Custom Plots
333
334
```python
335
# Create JointGrid and customize plots
336
g = sns.JointGrid(data=tips, x="total_bill", y="tip")
337
g.plot_joint(sns.scatterplot, alpha=0.7)
338
g.plot_marginals(sns.histplot, kde=True)
339
plt.show()
340
```
341
342
### Joint Plot
343
344
```python
345
# Quick bivariate plot with marginals
346
sns.jointplot(
347
data=tips, x="total_bill", y="tip",
348
kind="reg", height=8
349
)
350
plt.show()
351
```
352
353
### Corner Plot
354
355
```python
356
# Show only lower triangle
357
sns.pairplot(iris, hue="species", corner=True)
358
plt.show()
359
```
360
361
### JointGrid with Different Plot Types
362
363
```python
364
# Different combinations of joint and marginal plots
365
sns.jointplot(
366
data=tips, x="total_bill", y="tip",
367
kind="hex", # Hexbin for joint
368
marginal_kws=dict(bins=25) # Custom marginal bins
369
)
370
plt.show()
371
```
372
373
## Types
374
375
```python { .api }
376
# Grid classes
377
FacetGrid = seaborn.axisgrid.FacetGrid
378
PairGrid = seaborn.axisgrid.PairGrid
379
JointGrid = seaborn.axisgrid.JointGrid
380
381
# Plot kinds for pairplot
382
PairPlotKind = Literal["scatter", "kde", "hist", "reg"]
383
DiagKind = Literal["auto", "hist", "kde", None]
384
385
# Plot kinds for jointplot
386
JointPlotKind = Literal["scatter", "kde", "hist", "hex", "reg", "resid"]
387
```