A Grammar of Graphics for Python providing a declarative approach to data visualization similar to R's ggplot2
—
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.
Core functions for controlling guides and legends across all aesthetic mappings.
def guides(**kwargs):
"""
Set guides for multiple aesthetics simultaneously.
Central function for controlling the appearance and behavior of all
plot guides including color legends, size legends, and shape legends.
Parameters:
- color/colour: guide specification for color aesthetic
- fill: guide specification for fill aesthetic
- size: guide specification for size aesthetic
- shape: guide specification for shape aesthetic
- alpha: guide specification for alpha aesthetic
- linetype: guide specification for linetype aesthetic
- **kwargs: any other aesthetic guide specifications
Guide specifications can be:
- 'auto': automatic guide (default)
- 'none' or False: no guide (hide legend)
- guide object: custom guide (guide_legend(), guide_colorbar(), etc.)
Usage: Preferred method for setting multiple guides at once
"""
def guide_legend(title=None, title_position=None, title_theme=None,
title_hjust=None, title_vjust=None, label=True,
label_position=None, label_theme=None, label_hjust=None,
label_vjust=None, keywidth=None, keyheight=None,
direction=None, default_unit='line', override_aes=None,
nrow=None, ncol=None, byrow=None, reverse=False, **kwargs):
"""
Legend guide for discrete scales.
Creates traditional legends with discrete keys for categorical data
and discrete scales. Provides extensive customization options.
Parameters:
- title: str, legend title text
- title_position: str, title position ('top', 'bottom', 'left', 'right')
- title_theme: element_text, title text styling
- title_hjust, title_vjust: float, title alignment
- label: bool, whether to show labels
- label_position: str, label position relative to keys
- label_theme: element_text, label text styling
- label_hjust, label_vjust: float, label alignment
- keywidth, keyheight: unit, size of legend keys
- direction: str, layout direction ('horizontal', 'vertical')
- default_unit: str, default unit for measurements
- override_aes: dict, override aesthetics for legend keys
- nrow, ncol: int, number of rows/columns in legend
- byrow: bool, whether to fill legend by rows
- reverse: bool, whether to reverse the order of legend items
"""
def guide_colorbar(title=None, title_position=None, title_theme=None,
title_hjust=None, title_vjust=None, label=True,
label_position=None, label_theme=None, label_hjust=None,
label_vjust=None, barwidth=None, barheight=None,
nbin=20, raster=True, frame_colour=None, frame_linewidth=0.5,
frame_linetype=1, ticks=True, ticks_colour='white',
ticks_linewidth=0.5, draw_ulim=True, draw_llim=True,
direction=None, default_unit='line', reverse=False, **kwargs):
"""
Colorbar guide for continuous color and fill scales.
Creates continuous color bars showing gradients for continuous data.
Essential for heatmaps, choropleth maps, and continuous color mappings.
Parameters:
- title: str, colorbar title
- title_position: str, title position
- title_theme: element_text, title styling
- title_hjust, title_vjust: float, title alignment
- label: bool, whether to show tick labels
- label_position: str, label position
- label_theme: element_text, label styling
- label_hjust, label_vjust: float, label alignment
- barwidth, barheight: unit, colorbar dimensions
- nbin: int, number of color bins in continuous bar
- raster: bool, whether to use raster for drawing (faster)
- frame_colour: str, color of colorbar frame
- frame_linewidth: float, width of frame
- frame_linetype: line type for frame
- ticks: bool, whether to show tick marks
- ticks_colour: str, color of tick marks
- ticks_linewidth: float, width of tick marks
- draw_ulim, draw_llim: bool, whether to draw upper/lower limit ticks
- direction: str, colorbar orientation
- reverse: bool, whether to reverse color order
"""
# British spelling aliases
def guide_colourbar(**kwargs):
"""Alias for guide_colorbar() with British spelling."""
return guide_colorbar(**kwargs)# Hide all legends
ggplot(data, aes(x='x', y='y', color='group')) + \
geom_point() + \
guides(color='none')
# Hide specific legend
ggplot(data, aes(x='x', y='y', color='group', size='value')) + \
geom_point() + \
guides(color='auto', size='none') # Keep color, hide size
# Use theme to hide all legends (alternative method)
ggplot(data, aes(x='x', y='y', color='group')) + \
geom_point() + \
theme(legend_position='none')# Position legends using theme
ggplot(data, aes(x='x', y='y', color='group')) + \
geom_point() + \
theme(legend_position='bottom') # 'top', 'left', 'right', 'none'
# Custom legend position with coordinates (0-1 scale)
ggplot(data, aes(x='x', y='y', color='group')) + \
geom_point() + \
theme(legend_position=(0.8, 0.2)) # x=0.8, y=0.2 from bottom-left
# Legend direction
ggplot(data, aes(x='x', y='y', color='group')) + \
geom_point() + \
theme(legend_position='bottom', legend_direction='horizontal')# Custom discrete legend
ggplot(data, aes(x='x', y='y', color='treatment', shape='gender')) + \
geom_point(size=3) + \
guides(
color=guide_legend(
title='Treatment\nGroup',
title_position='top',
nrow=2,
override_aes={'size': 4} # Make legend keys larger
),
shape=guide_legend(
title='Gender',
direction='horizontal'
)
)
# Override aesthetics in legend
ggplot(data, aes(x='x', y='y', color='group')) + \
geom_point(alpha=0.5) + \
guides(color=guide_legend(override_aes={'alpha': 1, 'size': 3}))# Custom colorbar for continuous color scale
ggplot(data, aes(x='x', y='y', color='temperature')) + \
geom_point() + \
scale_color_gradient(low='blue', high='red') + \
guides(color=guide_colorbar(
title='Temperature\n(°C)',
title_position='top',
barwidth=10,
barheight=0.5,
direction='horizontal',
label_position='bottom'
)) + \
theme(legend_position='bottom')
# Vertical colorbar with custom styling
ggplot(heatmap_data, aes(x='x', y='y', fill='value')) + \
geom_tile() + \
scale_fill_viridis_c() + \
guides(fill=guide_colorbar(
title='Values',
barwidth=1,
barheight=8,
frame_colour='black',
ticks_colour='black'
))# Control multiple legends
ggplot(data, aes(x='x', y='y', color='group', size='importance', shape='type')) + \
geom_point() + \
guides(
color=guide_legend(
title='Group',
order=1, # First legend
override_aes={'size': 3}
),
size=guide_legend(
title='Importance',
order=2, # Second legend
override_aes={'shape': 'circle'}
),
shape=guide_legend(
title='Type',
order=3 # Third legend
)
) + \
theme(legend_position='right')# Custom legend titles and labels
group_labels = {'A': 'Treatment A', 'B': 'Treatment B', 'C': 'Control'}
ggplot(data, aes(x='x', y='y', color='group')) + \
geom_point() + \
scale_color_discrete(name='Study Group', labels=group_labels.values()) + \
guides(color=guide_legend(
title='Study Group',
title_theme=element_text(size=12, face='bold'),
label_theme=element_text(size=10)
))
# Remove legend title
ggplot(data, aes(x='x', y='y', fill='category')) + \
geom_col() + \
guides(fill=guide_legend(title=None))# Horizontal legend with multiple rows
ggplot(data, aes(x='x', y='y', color='category')) + \
geom_point() + \
guides(color=guide_legend(
nrow=2,
byrow=True,
direction='horizontal'
)) + \
theme(legend_position='bottom')
# Custom key sizes
ggplot(data, aes(x='x', y='y', linetype='group', color='treatment')) + \
geom_line(size=1) + \
guides(
linetype=guide_legend(
keywidth=unit(3, 'cm'),
keyheight=unit(0.3, 'cm')
),
color=guide_legend(
keywidth=unit(1, 'cm'),
keyheight=unit(1, 'cm')
)
)# Manual scale with custom guide
colors = {'Low': 'blue', 'Medium': 'yellow', 'High': 'red'}
ggplot(data, aes(x='x', y='y', color='risk_level')) + \
geom_point(size=3) + \
scale_color_manual(
values=colors,
name='Risk Level',
breaks=['Low', 'Medium', 'High']
) + \
guides(color=guide_legend(
title='Risk Assessment',
override_aes={'size': 5},
reverse=True # High to Low order
))# Separate colorbars for fill and color
ggplot(data, aes(x='x', y='y', color='temp', fill='humidity')) + \
geom_point(shape='circle_filled', size=4) + \
scale_color_gradient(low='blue', high='red') + \
scale_fill_gradient(low='white', high='green') + \
guides(
color=guide_colorbar(
title='Temperature',
barwidth=8, barheight=0.5,
direction='horizontal'
),
fill=guide_colorbar(
title='Humidity',
barwidth=0.5, barheight=8,
direction='vertical'
)
) + \
theme(legend_position='bottom')# Professional legend styling
ggplot(data, aes(x='x', y='y', color='group', shape='treatment')) + \
geom_point(size=3) + \
guides(
color=guide_legend(
title='Population Group',
override_aes={'size': 4}
),
shape=guide_legend(
title='Treatment Type'
)
) + \
theme_bw() + \
theme(
legend_position='bottom',
legend_box='horizontal',
legend_title=element_text(size=11, face='bold'),
legend_text=element_text(size=9),
legend_key=element_rect(fill='white', color='gray80'),
legend_background=element_rect(fill='gray95', color='black')
)# Map with custom colorbar
ggplot(map_data, aes(x='longitude', y='latitude', fill='population')) + \
geom_polygon(aes(group='region'), color='white', size=0.1) + \
scale_fill_viridis_c(trans='log10', name='Population') + \
guides(fill=guide_colorbar(
title='Population\n(log scale)',
title_position='top',
barwidth=12,
barheight=0.8,
direction='horizontal',
ticks=True,
frame_colour='black'
)) + \
coord_fixed() + \
theme_void() + \
theme(legend_position='bottom')
# Heatmap with positioned colorbar
ggplot(correlation_data, aes(x='var1', y='var2', fill='correlation')) + \
geom_tile() + \
scale_fill_gradient2(low='blue', mid='white', high='red',
midpoint=0, name='Correlation') + \
guides(fill=guide_colorbar(
barwidth=1, barheight=6,
frame_colour='black',
ticks_colour='black'
)) + \
theme_minimal() + \
theme(
axis_text_x=element_text(angle=45, hjust=1),
legend_position='right'
)# Fix overlapping legends
ggplot(data, aes(x='x', y='y', color='group', size='value')) + \
geom_point() + \
theme(
legend_position='bottom',
legend_box='horizontal', # Arrange legends horizontally
legend_margin=margin(t=10) # Add margin above legends
)
# Ensure consistent legend key sizes across layers
ggplot(data, aes(x='x', y='y', color='group')) + \
geom_point(size=2) + \
geom_smooth(se=False, size=1) + \
guides(color=guide_legend(
override_aes={'size': 3, 'linetype': 'solid'}
))
# Handle long legend labels
ggplot(data, aes(x='x', y='y', color='very_long_category_names')) + \
geom_point() + \
guides(color=guide_legend(
title='Categories',
ncol=1, # Single column for long labels
label_theme=element_text(size=8)
)) + \
theme(legend_position='bottom')Install with Tessl CLI
npx tessl i tessl/pypi-plotnine