I'm trying to alter part of the displayed legend using ggplot. For example, If I have some data and create a plot like this:
library(ggplot2)
dat <- data.frame(
nam = c('a','b','c','d','e','f','g','h','i'),
val = c(2,5,1,6,8,3,9,10,8)
)
col1 <- setNames(scales::hue_pal(c(0, 360) 15, 100, 64, 0, 1)(length(dat$nam[1:5])), dat$nam[1:5])
col2 <- setNames(rep('#e6e6e6', length(dat$nam[6:9])), dat$nam[6:9])
colFinal <- unname(c(col1, col2))
ggplot(dat, aes(x = nam, y = val, fill= nam ))
geom_bar(stat = 'identity')
scale_fill_manual(values = colFinal, name = 'name')
theme_bw()
As you can see, f
to i
are all coloured the same grey colour. I was wondering if it is possible to alter the legend by "merging" f
to i
to display only a single legend entry for these values. For example, I'm trying to do something like this:
But the caveat is Im trying to do this by altering the plot itself. It is not possible for me to go back and alter the data frame. I was thinking that maybe this could be achieved by using ggplot_build
but Im not sure!?
Any suggestions as to how I could do this?
CodePudding user response:
One option would be to manually set the breaks
and the labels
of the fill scale by manipulating the ggplot
object:
library(ggplot2)
dat <- data.frame(
nam = c('a','b','c','d','e','f','g','h','i'),
val = c(2,5,1,6,8,3,9,10,8)
)
col1 <- setNames(scales::hue_pal(c(0, 360) 15, 100, 64, 0, 1)(length(dat$nam[1:5])), dat$nam[1:5])
col2 <- setNames(rep('#e6e6e6', length(dat$nam[6:9])), dat$nam[6:9])
colFinal <- unname(c(col1, col2))
p <- ggplot(dat, aes(x = nam, y = val, fill= nam ))
geom_bar(stat = 'identity')
scale_fill_manual(values = colFinal, name = 'name')
theme_bw()
p$scales$scales[[1]]$breaks <- letters[1:6]
p$scales$scales[[1]]$labels <- c(letters[1:5], "Others")
p