# Standard use for single aesthetic. The default is to split labels to
# disentangle aesthetics that are already crossed (by e.g. `paste()`)
ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = paste(year, drv))) +
guides(colour = "legend_cross")
# If legends should be merged between identical aesthetics, both need the
# same legend type.
ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = paste(year, drv), shape = paste(year, drv))) +
guides(colour = "legend_cross", shape = "legend_cross")
# Crossing two aesthetics requires a shared title and `key = "auto"`. The
# easy way to achieve this is to predefine a shared guide.
my_guide <- guide_legend_cross(key = "auto", title = "My title")
ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = drv, shape = factor(year))) +
guides(colour = my_guide, shape = my_guide)
# You can cross more than 2 aesthetics but not more than 2 unique aesthetics.
ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = drv, shape = factor(year), size = factor(drv))) +
scale_size_ordinal() +
guides(colour = my_guide, shape = my_guide, size = my_guide)
# You can merge an aesthetic that is already crossed with an aesthetic that
# contributes to only one side of the cross.
ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = paste(year, drv), shape = drv)) +
guides(
colour = guide_legend_cross(title = "My Title"),
shape = guide_legend_cross(title = "My Title", key = "auto")
)
Run the code above in your browser using DataLab