0

I am trying to "hide" a value from the legend of a ggplot2 object. For example in the following example, I would try to hide the third value in the legend while keeping the actual data within the plot. Desired output would be the same plot but without the 8 cycle listed in the legend but with the data still within the plot.

ggplot(mtcars, aes(x=wt, y=mpg, group=as.factor(cyl))) +
  geom_point(aes(shape=as.factor(cyl), color=as.factor(cyl)))

I'm also trying to change the colors and shapes so that every other shape repeats and the colors are only black and white as follows

plot <- ggplot(mtcars, aes(x=wt, y=mpg, group=as.factor(cyl))) +
        geom_point(aes(shape=as.factor(cyl), color=as.factor(cyl)))

plot2 <- plot +
         scale_colour_manual(values = c('#999999', '#999999','#999999')) +   
         scale_shape_manual(values = c(0, 1, 0))

plot2

However when I then try to only keep the first two values within the legend it seems to overwrite the previous changes. For example:

plot2 +
scale_color_discrete(breaks=c(4, 6)) +
scale_shape_discrete(breaks=c(4, 6))    
Kreitz Gigs
  • 369
  • 1
  • 9
  • 2
    [Please provide](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) some or all of `df`. It looks like it's derived from `mtcars`, except `cyl` is a factor? It's also not very clear what your desired output is. – neilfws Apr 12 '19 at 05:18
  • Oops sorry about that, I just updated it. – Kreitz Gigs Apr 12 '19 at 05:31
  • https://stackoverflow.com/questions/15704934/remove-certain-legend-variables-and-legend-values-from-ggplot2 – Jon Spring Apr 12 '19 at 06:44

1 Answers1

2
ggplot(mtcars, aes(x=wt, y=mpg, color=as.factor(cyl))) +
  geom_point(aes(shape=as.factor(cyl))) +
  scale_color_discrete(breaks=c(4, 6)) +
  scale_shape_discrete(breaks=c(4, 6))
Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • Hey Jon, thanks for your help. If you don't mind taking a look at my edits I'm trying to figure out how to change the figure to black and white and change the shapes to alternate between two different shapes. – Kreitz Gigs Apr 13 '19 at 05:57
  • Not sure I follow, but you can only use one `scale_*` for each aesthetic. Perhaps `plot2 <- plot + scale_colour_manual(values = c('#999999', '#999999','#999999')) + scale_shape_manual(values = c(0, 1, 0))`? – Jon Spring Apr 13 '19 at 06:47
  • Yeah so that works for what I want but then when I try to drop the 3rd variable from the legend it messes up the previous changes made with the scale_colour_manual() and scale_shape_manual() functions. – Kreitz Gigs Apr 13 '19 at 17:46