简体   繁体   中英

Change color shape and edit legend in R ggplot2 object

I am trying to modify a ggplot2 object where I took an object and used the scale_colour_manual and scale_shape_manual to change the colors and shapes. However, now I'd like to only show the top two items in the legend.

As you can see in the code, I changed the first and third shapes to match each other and now the third is redundant but I still want that underlying data within the plot. The desired result would be plot2 but without the third value within the legend but with the data left 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)))

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

Adding breaks = ... to scale_colour_manual and scale_shape_manual should do it

plot3 <- plot +
  scale_colour_manual(values = c('#999999', '#999999','#999999'), 
                      breaks = c('4', '6')) +   
  scale_shape_manual(values = c(0, 1, 0), 
                     breaks = c('4', '6'))

# https://github.com/thomasp85/patchwork
# install.packages("devtools", dependencies = TRUE)
# devtools::install_github("thomasp85/patchwork")
library(patchwork)
plot2 + plot3 +
  plot_layout(ncol = 2) 

Created on 2019-04-13 by the reprex package (v0.2.1.9000)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM