0
# Guides and Legends
1
2
Guides and legends provide visual explanations of aesthetic mappings, helping users understand how data values correspond to colors, sizes, shapes, and other visual properties. Plotnine offers comprehensive control over legend appearance, positioning, and behavior, supporting both automatic and custom guide generation.
3
4
## Capabilities
5
6
### Basic Guide Functions
7
8
Core functions for controlling guides and legends across all aesthetic mappings.
9
10
```python { .api }
11
def guides(**kwargs):
12
"""
13
Set guides for multiple aesthetics simultaneously.
14
15
Central function for controlling the appearance and behavior of all
16
plot guides including color legends, size legends, and shape legends.
17
18
Parameters:
19
- color/colour: guide specification for color aesthetic
20
- fill: guide specification for fill aesthetic
21
- size: guide specification for size aesthetic
22
- shape: guide specification for shape aesthetic
23
- alpha: guide specification for alpha aesthetic
24
- linetype: guide specification for linetype aesthetic
25
- **kwargs: any other aesthetic guide specifications
26
27
Guide specifications can be:
28
- 'auto': automatic guide (default)
29
- 'none' or False: no guide (hide legend)
30
- guide object: custom guide (guide_legend(), guide_colorbar(), etc.)
31
32
Usage: Preferred method for setting multiple guides at once
33
"""
34
35
def guide_legend(title=None, title_position=None, title_theme=None,
36
title_hjust=None, title_vjust=None, label=True,
37
label_position=None, label_theme=None, label_hjust=None,
38
label_vjust=None, keywidth=None, keyheight=None,
39
direction=None, default_unit='line', override_aes=None,
40
nrow=None, ncol=None, byrow=None, reverse=False, **kwargs):
41
"""
42
Legend guide for discrete scales.
43
44
Creates traditional legends with discrete keys for categorical data
45
and discrete scales. Provides extensive customization options.
46
47
Parameters:
48
- title: str, legend title text
49
- title_position: str, title position ('top', 'bottom', 'left', 'right')
50
- title_theme: element_text, title text styling
51
- title_hjust, title_vjust: float, title alignment
52
- label: bool, whether to show labels
53
- label_position: str, label position relative to keys
54
- label_theme: element_text, label text styling
55
- label_hjust, label_vjust: float, label alignment
56
- keywidth, keyheight: unit, size of legend keys
57
- direction: str, layout direction ('horizontal', 'vertical')
58
- default_unit: str, default unit for measurements
59
- override_aes: dict, override aesthetics for legend keys
60
- nrow, ncol: int, number of rows/columns in legend
61
- byrow: bool, whether to fill legend by rows
62
- reverse: bool, whether to reverse the order of legend items
63
"""
64
65
def guide_colorbar(title=None, title_position=None, title_theme=None,
66
title_hjust=None, title_vjust=None, label=True,
67
label_position=None, label_theme=None, label_hjust=None,
68
label_vjust=None, barwidth=None, barheight=None,
69
nbin=20, raster=True, frame_colour=None, frame_linewidth=0.5,
70
frame_linetype=1, ticks=True, ticks_colour='white',
71
ticks_linewidth=0.5, draw_ulim=True, draw_llim=True,
72
direction=None, default_unit='line', reverse=False, **kwargs):
73
"""
74
Colorbar guide for continuous color and fill scales.
75
76
Creates continuous color bars showing gradients for continuous data.
77
Essential for heatmaps, choropleth maps, and continuous color mappings.
78
79
Parameters:
80
- title: str, colorbar title
81
- title_position: str, title position
82
- title_theme: element_text, title styling
83
- title_hjust, title_vjust: float, title alignment
84
- label: bool, whether to show tick labels
85
- label_position: str, label position
86
- label_theme: element_text, label styling
87
- label_hjust, label_vjust: float, label alignment
88
- barwidth, barheight: unit, colorbar dimensions
89
- nbin: int, number of color bins in continuous bar
90
- raster: bool, whether to use raster for drawing (faster)
91
- frame_colour: str, color of colorbar frame
92
- frame_linewidth: float, width of frame
93
- frame_linetype: line type for frame
94
- ticks: bool, whether to show tick marks
95
- ticks_colour: str, color of tick marks
96
- ticks_linewidth: float, width of tick marks
97
- draw_ulim, draw_llim: bool, whether to draw upper/lower limit ticks
98
- direction: str, colorbar orientation
99
- reverse: bool, whether to reverse color order
100
"""
101
102
# British spelling aliases
103
def guide_colourbar(**kwargs):
104
"""Alias for guide_colorbar() with British spelling."""
105
return guide_colorbar(**kwargs)
106
```
107
108
## Usage Patterns
109
110
### Basic Legend Control
111
```python
112
# Hide all legends
113
ggplot(data, aes(x='x', y='y', color='group')) + \
114
geom_point() + \
115
guides(color='none')
116
117
# Hide specific legend
118
ggplot(data, aes(x='x', y='y', color='group', size='value')) + \
119
geom_point() + \
120
guides(color='auto', size='none') # Keep color, hide size
121
122
# Use theme to hide all legends (alternative method)
123
ggplot(data, aes(x='x', y='y', color='group')) + \
124
geom_point() + \
125
theme(legend_position='none')
126
```
127
128
### Legend Positioning
129
```python
130
# Position legends using theme
131
ggplot(data, aes(x='x', y='y', color='group')) + \
132
geom_point() + \
133
theme(legend_position='bottom') # 'top', 'left', 'right', 'none'
134
135
# Custom legend position with coordinates (0-1 scale)
136
ggplot(data, aes(x='x', y='y', color='group')) + \
137
geom_point() + \
138
theme(legend_position=(0.8, 0.2)) # x=0.8, y=0.2 from bottom-left
139
140
# Legend direction
141
ggplot(data, aes(x='x', y='y', color='group')) + \
142
geom_point() + \
143
theme(legend_position='bottom', legend_direction='horizontal')
144
```
145
146
### Discrete Legend Customization
147
```python
148
# Custom discrete legend
149
ggplot(data, aes(x='x', y='y', color='treatment', shape='gender')) + \
150
geom_point(size=3) + \
151
guides(
152
color=guide_legend(
153
title='Treatment\nGroup',
154
title_position='top',
155
nrow=2,
156
override_aes={'size': 4} # Make legend keys larger
157
),
158
shape=guide_legend(
159
title='Gender',
160
direction='horizontal'
161
)
162
)
163
164
# Override aesthetics in legend
165
ggplot(data, aes(x='x', y='y', color='group')) + \
166
geom_point(alpha=0.5) + \
167
guides(color=guide_legend(override_aes={'alpha': 1, 'size': 3}))
168
```
169
170
### Continuous Legend (Colorbar) Customization
171
```python
172
# Custom colorbar for continuous color scale
173
ggplot(data, aes(x='x', y='y', color='temperature')) + \
174
geom_point() + \
175
scale_color_gradient(low='blue', high='red') + \
176
guides(color=guide_colorbar(
177
title='Temperature\n(°C)',
178
title_position='top',
179
barwidth=10,
180
barheight=0.5,
181
direction='horizontal',
182
label_position='bottom'
183
)) + \
184
theme(legend_position='bottom')
185
186
# Vertical colorbar with custom styling
187
ggplot(heatmap_data, aes(x='x', y='y', fill='value')) + \
188
geom_tile() + \
189
scale_fill_viridis_c() + \
190
guides(fill=guide_colorbar(
191
title='Values',
192
barwidth=1,
193
barheight=8,
194
frame_colour='black',
195
ticks_colour='black'
196
))
197
```
198
199
### Multiple Legends Layout
200
```python
201
# Control multiple legends
202
ggplot(data, aes(x='x', y='y', color='group', size='importance', shape='type')) + \
203
geom_point() + \
204
guides(
205
color=guide_legend(
206
title='Group',
207
order=1, # First legend
208
override_aes={'size': 3}
209
),
210
size=guide_legend(
211
title='Importance',
212
order=2, # Second legend
213
override_aes={'shape': 'circle'}
214
),
215
shape=guide_legend(
216
title='Type',
217
order=3 # Third legend
218
)
219
) + \
220
theme(legend_position='right')
221
```
222
223
### Legend Title and Label Customization
224
```python
225
# Custom legend titles and labels
226
group_labels = {'A': 'Treatment A', 'B': 'Treatment B', 'C': 'Control'}
227
228
ggplot(data, aes(x='x', y='y', color='group')) + \
229
geom_point() + \
230
scale_color_discrete(name='Study Group', labels=group_labels.values()) + \
231
guides(color=guide_legend(
232
title='Study Group',
233
title_theme=element_text(size=12, face='bold'),
234
label_theme=element_text(size=10)
235
))
236
237
# Remove legend title
238
ggplot(data, aes(x='x', y='y', fill='category')) + \
239
geom_col() + \
240
guides(fill=guide_legend(title=None))
241
```
242
243
### Advanced Legend Layouts
244
```python
245
# Horizontal legend with multiple rows
246
ggplot(data, aes(x='x', y='y', color='category')) + \
247
geom_point() + \
248
guides(color=guide_legend(
249
nrow=2,
250
byrow=True,
251
direction='horizontal'
252
)) + \
253
theme(legend_position='bottom')
254
255
# Custom key sizes
256
ggplot(data, aes(x='x', y='y', linetype='group', color='treatment')) + \
257
geom_line(size=1) + \
258
guides(
259
linetype=guide_legend(
260
keywidth=unit(3, 'cm'),
261
keyheight=unit(0.3, 'cm')
262
),
263
color=guide_legend(
264
keywidth=unit(1, 'cm'),
265
keyheight=unit(1, 'cm')
266
)
267
)
268
```
269
270
### Combining Scales and Guides
271
```python
272
# Manual scale with custom guide
273
colors = {'Low': 'blue', 'Medium': 'yellow', 'High': 'red'}
274
275
ggplot(data, aes(x='x', y='y', color='risk_level')) + \
276
geom_point(size=3) + \
277
scale_color_manual(
278
values=colors,
279
name='Risk Level',
280
breaks=['Low', 'Medium', 'High']
281
) + \
282
guides(color=guide_legend(
283
title='Risk Assessment',
284
override_aes={'size': 5},
285
reverse=True # High to Low order
286
))
287
```
288
289
### Colorbar for Fill and Color
290
```python
291
# Separate colorbars for fill and color
292
ggplot(data, aes(x='x', y='y', color='temp', fill='humidity')) + \
293
geom_point(shape='circle_filled', size=4) + \
294
scale_color_gradient(low='blue', high='red') + \
295
scale_fill_gradient(low='white', high='green') + \
296
guides(
297
color=guide_colorbar(
298
title='Temperature',
299
barwidth=8, barheight=0.5,
300
direction='horizontal'
301
),
302
fill=guide_colorbar(
303
title='Humidity',
304
barwidth=0.5, barheight=8,
305
direction='vertical'
306
)
307
) + \
308
theme(legend_position='bottom')
309
```
310
311
### Legend Integration with Themes
312
```python
313
# Professional legend styling
314
ggplot(data, aes(x='x', y='y', color='group', shape='treatment')) + \
315
geom_point(size=3) + \
316
guides(
317
color=guide_legend(
318
title='Population Group',
319
override_aes={'size': 4}
320
),
321
shape=guide_legend(
322
title='Treatment Type'
323
)
324
) + \
325
theme_bw() + \
326
theme(
327
legend_position='bottom',
328
legend_box='horizontal',
329
legend_title=element_text(size=11, face='bold'),
330
legend_text=element_text(size=9),
331
legend_key=element_rect(fill='white', color='gray80'),
332
legend_background=element_rect(fill='gray95', color='black')
333
)
334
```
335
336
### Specialized Guide Applications
337
```python
338
# Map with custom colorbar
339
ggplot(map_data, aes(x='longitude', y='latitude', fill='population')) + \
340
geom_polygon(aes(group='region'), color='white', size=0.1) + \
341
scale_fill_viridis_c(trans='log10', name='Population') + \
342
guides(fill=guide_colorbar(
343
title='Population\n(log scale)',
344
title_position='top',
345
barwidth=12,
346
barheight=0.8,
347
direction='horizontal',
348
ticks=True,
349
frame_colour='black'
350
)) + \
351
coord_fixed() + \
352
theme_void() + \
353
theme(legend_position='bottom')
354
355
# Heatmap with positioned colorbar
356
ggplot(correlation_data, aes(x='var1', y='var2', fill='correlation')) + \
357
geom_tile() + \
358
scale_fill_gradient2(low='blue', mid='white', high='red',
359
midpoint=0, name='Correlation') + \
360
guides(fill=guide_colorbar(
361
barwidth=1, barheight=6,
362
frame_colour='black',
363
ticks_colour='black'
364
)) + \
365
theme_minimal() + \
366
theme(
367
axis_text_x=element_text(angle=45, hjust=1),
368
legend_position='right'
369
)
370
```
371
372
### Troubleshooting Common Legend Issues
373
```python
374
# Fix overlapping legends
375
ggplot(data, aes(x='x', y='y', color='group', size='value')) + \
376
geom_point() + \
377
theme(
378
legend_position='bottom',
379
legend_box='horizontal', # Arrange legends horizontally
380
legend_margin=margin(t=10) # Add margin above legends
381
)
382
383
# Ensure consistent legend key sizes across layers
384
ggplot(data, aes(x='x', y='y', color='group')) + \
385
geom_point(size=2) + \
386
geom_smooth(se=False, size=1) + \
387
guides(color=guide_legend(
388
override_aes={'size': 3, 'linetype': 'solid'}
389
))
390
391
# Handle long legend labels
392
ggplot(data, aes(x='x', y='y', color='very_long_category_names')) + \
393
geom_point() + \
394
guides(color=guide_legend(
395
title='Categories',
396
ncol=1, # Single column for long labels
397
label_theme=element_text(size=8)
398
)) + \
399
theme(legend_position='bottom')
400
```