So a handful of posts already address how to remove unwanted legends in ggplot.
The wonderful answer posted to "Remove extra legends in ggplot2" suggests:
For any mapped variable you can supress the appearance of a legend by using
guide = 'none'
in the appropriatescale_
...
However, I'm having problems with unwanted legends being created by adding the group
aesthetic.
I tried the scale approach, but it doesn't seem to work with the group argument:
could not find function "scale_group"
A search here didn't provide any insight on the proper function call to modify group aesthetics either.
User @joran provided the following insight in the linked post above:
That's because the
group
aesthetic doesn't generate any scales or guides on its own. It's always sort of modifying something else. You'll never get a legend for thegroup
aesthetic.
Example
So I could just add show.legend = FALSE
to my function call containing group
to remove any legend for that function, but this doesn't work out if I want some other portion (i.e., aesthetic) of that call to be included in the legend.
#Set Up Example:
library(lme4)
library(ggplot2)
mod <- lmer(mpg ~ hp + (1 |cyl), data = mtcars)
pred <- predict(mod,re.form = NA)
pdat <- data.frame(mtcars[,c('hp','cyl')], mpg = pred, up = pred+1, low = pred-1)
Adding show.legend = F
to function calls work as expected:
gp <-
ggplot(data = mtcars, aes(x = hp, y = mpg, color = cyl, group = cyl), show.legend = F) +
geom_point(aes(group = cyl),show.legend = F) +
facet_wrap(~cyl) +
geom_line(data = pdat, aes(group = cyl),show.legend = F, color = 'orange')
But when I want to add a legend for a geom_ribbon
fill based on the same group
(and therefore cannot use the show.legend = F
argument), I get a legend for my group
again...
gp + geom_ribbon(data = pdat, aes(ymin = low, ymax = up, group = cyl, fill = 'mod'), alpha = 0.3) +
scale_fill_manual(values=c("orange"), name="model")
The outputs:
color
aesthetic (you can see it in the outline of the ribbons). If you only set that ingeom_point
, it will go away. – alistairecolor
in the mainggplot
function call, all subsequent function calls are "activating" (not sure the right word to use) thecolor
call (and thus creating a legend for it unless supressed usingshow.legend=F
)? Is that right? – theforestecologistmodel
legend withoutcyl
gradient scale? – Tunginherit.aes = FALSE
such asgeom_ribbon(data = pdat, aes(x = hp, ymin = low, ymax = up, group = cyl, fill = 'mod'), inherit.aes = FALSE, alpha = 0.3)
– Tung?geom_ribbon
here), it will tell you which aesthetics it understands. – alistaire