I want to make a legend in ggplot2
which is not defined by any sort of aes()
mapping, or color at all for that matter. I am plotting box and whisker plots for several categories of a variable, but label the categories with numbers 1:8. I simply want to make a legend using ggplot2
that maps each label on the discrete x axis (using scale_x_discrete()
) to the full name of the category. Using the actual name on the axis tick would crowd the plot, especially because I am using facet_wrap()
. I just want to use the numbers then have a number-to-scenario legend on the side.
Consider this example:
library(tidyverse)
iris_mod <- iris %>%
mutate(category = as.integer(as.factor(Species)),
big_length = ifelse(Sepal.Length > 6.2,1,0))
iris_ex <- ggplot(data = iris_mod, aes(x = Sepal.Width, y = as.factor(category))) +
geom_boxplot(alpha = 1, outlier.shape = NA, fill = 'steelblue') +
theme_bw() +
scale_y_discrete(name = "Scenario Label") +
scale_x_continuous(name = "Sepal Width", limits = c(-8,12)) +
geom_vline(xintercept = 0, lty = 2) +
coord_flip() +
facet_wrap( ~ big_length, scales = c('free_x'))
iris_ex
And here is the output. Imagine this with 8 boxplots for four facets, so that there are 8 discrete labels on the bottom axis. I do not want to color 8 plot with different colors. I just want to have numeric labels. I also do not want to put the labels under the plot because the names are somewhat long and would prefer putting them in a legend layer.
How can I do this? The expected output would be a typical legend layer behaving to the normal rules that can be modified in theme()
, but rather than having colors in squares, it would correspond to the number. something like
'Legend name'
1 - Flowers without\n Fertilizer
2 - Flowers with\n Fertilizer
3 - Flowers with\n Coarse Soil
Legends in ggplot2 are made to replicate the aesthetic mapping in the plot, so this seems like an off-label use of the legend. I'd suggest faking it with a separate plot like so:
library(patchwork)
(legend <- ggplot(
data.frame(row = 1:4, label = c('Legend name',
'1 - Flowers without\n Fertilizer',
'2 - Flowers with\n Fertilizer1',
'3 - Flowers with\n Coarse Soil')),
aes(1, -row, label = label)) +
geom_text(hjust = 0, lineheight = 0.8) +
coord_cartesian(xlim = c(1, 1.5), clip = "off") +
theme_void())
iris_ex + legend + plot_layout(widths = c(4,1))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.