0
# Utilities
1
2
Essential utility functions for plot customization, data loading, color manipulation, and legend management. These functions provide helpful tools for enhancing plots and working with seaborn's example datasets.
3
4
## Capabilities
5
6
### Plot Customization
7
8
Remove spines and customize plot appearance.
9
10
```python { .api }
11
def despine(
12
fig=None,
13
ax=None,
14
top=True,
15
right=True,
16
left=False,
17
bottom=False,
18
offset=None,
19
trim=False
20
):
21
"""
22
Remove the top and right spines from plot(s).
23
24
Parameters:
25
- fig: matplotlib Figure, figure to despine (if None, uses current figure)
26
- ax: matplotlib Axes or list, specific axes to despine
27
- top: bool, remove top spine
28
- right: bool, remove right spine
29
- left: bool, remove left spine
30
- bottom: bool, remove bottom spine
31
- offset: int or dict, offset spines by specified points
32
- trim: bool, limit spines to data range
33
"""
34
```
35
36
### Legend Management
37
38
Recreate and reposition plot legends with custom styling.
39
40
```python { .api }
41
def move_legend(
42
obj,
43
loc,
44
**kwargs
45
):
46
"""
47
Recreate a plot's legend with a new location or visual properties.
48
49
Parameters:
50
- obj: matplotlib object with legend (Figure, Axes, or legend-bearing Artist)
51
- loc: str or int, legend location
52
- **kwargs: additional legend properties (title, frameon, fancybox, etc.)
53
54
Common locations:
55
- "upper right", "upper left", "lower left", "lower right"
56
- "right", "center left", "center right", "lower center", "upper center", "center"
57
- "outside" (seaborn-specific, places legend outside plot area)
58
"""
59
```
60
61
### Color Manipulation
62
63
Modify color properties for custom styling.
64
65
```python { .api }
66
def desaturate(color, prop):
67
"""
68
Decrease the saturation channel of a color by some percent.
69
70
Parameters:
71
- color: str or RGB tuple, input color
72
- prop: float, proportion to desaturate (0-1)
73
74
Returns:
75
RGB tuple of desaturated color
76
"""
77
78
def saturate(color):
79
"""
80
Return a fully saturated color with the same hue.
81
82
Parameters:
83
- color: str or RGB tuple, input color
84
85
Returns:
86
RGB tuple of saturated color
87
"""
88
89
def set_hls_values(color, h=None, l=None, s=None):
90
"""
91
Independently manipulate the h, l, or s channels of a color.
92
93
Parameters:
94
- color: str or RGB tuple, input color
95
- h: float, hue value (0-360) or None to keep current
96
- l: float, lightness value (0-100) or None to keep current
97
- s: float, saturation value (0-100) or None to keep current
98
99
Returns:
100
RGB tuple of modified color
101
"""
102
```
103
104
### Dataset Loading
105
106
Load example datasets for learning and experimentation.
107
108
```python { .api }
109
def load_dataset(name, cache=True, data_home=None, **kwargs):
110
"""
111
Load an example dataset from the online repository (or cache).
112
113
Parameters:
114
- name: str, dataset name
115
- cache: bool, cache dataset locally
116
- data_home: str, directory for cached datasets
117
- **kwargs: additional arguments passed to pandas.read_csv
118
119
Returns:
120
pandas.DataFrame containing the dataset
121
122
Available datasets: tips, flights, iris, titanic, attention, dots,
123
exercise, fmri, gammas, geyser, mpg, penguins, taxis, etc.
124
"""
125
126
def get_dataset_names():
127
"""
128
Report available example datasets, useful for load_dataset().
129
130
Returns:
131
list of str, available dataset names
132
"""
133
134
def get_data_home(data_home=None):
135
"""
136
Return a path to the cache directory for example datasets.
137
138
Parameters:
139
- data_home: str, path to use as data directory
140
141
Returns:
142
str, path to data directory
143
"""
144
```
145
146
### Visualization Utilities
147
148
Display color palettes and novelty functions.
149
150
```python { .api }
151
def palplot(pal, size=1):
152
"""
153
Plot the values in a color palette as a horizontal array.
154
155
Parameters:
156
- pal: list or array, color palette
157
- size: float, scaling factor for plot size
158
"""
159
160
def dogplot():
161
"""
162
Novelty function that displays random dog images.
163
164
This is an easter egg function that shows dog photos from online sources.
165
Requires internet connection.
166
"""
167
```
168
169
## Usage Examples
170
171
### Despine Plots
172
173
```python
174
import seaborn as sns
175
import matplotlib.pyplot as plt
176
177
tips = sns.load_dataset("tips")
178
179
# Basic plot with default spines
180
sns.scatterplot(data=tips, x="total_bill", y="tip")
181
plt.show()
182
183
# Remove top and right spines (common style)
184
sns.scatterplot(data=tips, x="total_bill", y="tip")
185
sns.despine()
186
plt.show()
187
188
# Remove all spines except bottom
189
sns.scatterplot(data=tips, x="total_bill", y="tip")
190
sns.despine(left=True)
191
plt.show()
192
193
# Offset spines from axes
194
sns.scatterplot(data=tips, x="total_bill", y="tip")
195
sns.despine(offset=10)
196
plt.show()
197
```
198
199
### Move Legend
200
201
```python
202
# Create plot with legend
203
g = sns.scatterplot(data=tips, x="total_bill", y="tip", hue="smoker")
204
205
# Move legend outside plot area
206
sns.move_legend(g, "upper left", bbox_to_anchor=(1, 1))
207
plt.show()
208
209
# Move legend to bottom with horizontal orientation
210
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="time")
211
sns.move_legend(
212
plt.gca(),
213
"lower center",
214
bbox_to_anchor=(0.5, -0.15),
215
ncol=2
216
)
217
plt.show()
218
```
219
220
### Color Manipulation
221
222
```python
223
# Desaturate colors
224
original_color = "red"
225
desaturated = sns.desaturate(original_color, 0.5)
226
227
# Show color comparison
228
colors = [original_color, desaturated]
229
sns.palplot(colors)
230
plt.title("Original vs Desaturated")
231
plt.show()
232
233
# Manipulate HLS values
234
base_color = "skyblue"
235
modified_colors = [
236
base_color,
237
sns.set_hls_values(base_color, h=180), # Change hue
238
sns.set_hls_values(base_color, l=20), # Darken
239
sns.set_hls_values(base_color, s=80), # More saturated
240
]
241
242
sns.palplot(modified_colors)
243
plt.show()
244
```
245
246
### Dataset Loading
247
248
```python
249
# Load popular datasets
250
tips = sns.load_dataset("tips")
251
flights = sns.load_dataset("flights")
252
iris = sns.load_dataset("iris")
253
254
print(f"Tips dataset shape: {tips.shape}")
255
print(f"Tips columns: {list(tips.columns)}")
256
257
# See all available datasets
258
available_datasets = sns.get_dataset_names()
259
print(f"Available datasets: {available_datasets[:10]}...") # First 10
260
261
# Get data directory location
262
data_dir = sns.get_data_home()
263
print(f"Data cached at: {data_dir}")
264
```
265
266
### Palette Visualization
267
268
```python
269
# Visualize different palettes
270
palettes = {
271
"deep": sns.color_palette("deep"),
272
"muted": sns.color_palette("muted"),
273
"bright": sns.color_palette("bright"),
274
"pastel": sns.color_palette("pastel"),
275
}
276
277
fig, axes = plt.subplots(len(palettes), 1, figsize=(8, 6))
278
279
for i, (name, palette) in enumerate(palettes.items()):
280
sns.palplot(palette, size=0.8)
281
plt.title(f"{name.title()} Palette")
282
if i < len(palettes) - 1:
283
plt.gca().set_xticks([])
284
285
plt.tight_layout()
286
plt.show()
287
```
288
289
### Multi-Panel Plot Styling
290
291
```python
292
# Apply consistent styling across subplots
293
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
294
295
# Plot in each subplot
296
sns.histplot(data=tips, x="total_bill", ax=axes[0,0])
297
sns.boxplot(data=tips, x="day", y="total_bill", ax=axes[0,1])
298
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="smoker", ax=axes[1,0])
299
sns.barplot(data=tips, x="day", y="total_bill", ax=axes[1,1])
300
301
# Apply despine to all subplots
302
sns.despine(fig=fig)
303
304
plt.tight_layout()
305
plt.show()
306
```
307
308
### Color Palette with Desaturation
309
310
```python
311
# Create desaturated palette for subtle coloring
312
base_palette = sns.color_palette("husl", 6)
313
desaturated_palette = [sns.desaturate(color, 0.7) for color in base_palette]
314
315
# Compare original and desaturated
316
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 4))
317
318
plt.subplot(2, 1, 1)
319
sns.palplot(base_palette)
320
plt.title("Original Palette")
321
322
plt.subplot(2, 1, 2)
323
sns.palplot(desaturated_palette)
324
plt.title("Desaturated Palette")
325
326
plt.tight_layout()
327
plt.show()
328
```
329
330
### Comprehensive Dataset Exploration
331
332
```python
333
# Load and explore a dataset
334
penguins = sns.load_dataset("penguins")
335
336
print("Dataset info:")
337
print(f"Shape: {penguins.shape}")
338
print(f"Columns: {list(penguins.columns)}")
339
print(f"Species: {penguins['species'].unique()}")
340
341
# Quick visualization with styling
342
g = sns.pairplot(penguins, hue="species", corner=True)
343
sns.despine()
344
sns.move_legend(g, "upper left", bbox_to_anchor=(0.7, 0.9))
345
plt.show()
346
```
347
348
## Available Example Datasets
349
350
Common datasets available through `load_dataset()`:
351
352
- **tips**: Restaurant tip data with bill amounts and customer info
353
- **flights**: Passenger numbers over time (time series)
354
- **iris**: Classic iris flower measurements dataset
355
- **titanic**: Titanic passenger survival data
356
- **penguins**: Palmer penguins morphological data
357
- **mpg**: Car fuel efficiency data
358
- **exercise**: Exercise and heart rate data
359
- **fmri**: fMRI brain scan data
360
- **attention**: Psychology attention experiment data
361
- **car_crashes**: US state car crash statistics
362
- **diamonds**: Diamond characteristics and prices
363
- **dots**: Dot motion perception experiment
364
- **gammas**: Gamma-ray burst data
365
- **geyser**: Old Faithful geyser eruption data
366
- **taxis**: NYC taxi trip data
367
368
## Types
369
370
```python { .api }
371
# Legend locations
372
LegendLocation = str | int | tuple[float, float]
373
374
# Color specifications
375
ColorSpec = str | tuple[float, float, float] | tuple[float, float, float, float]
376
377
# Dataset names
378
DatasetName = str # Any of the available dataset names
379
```