简体   繁体   中英

How to adjust legend for a colour-shape combiation in ggplot2?

I would like to rename the title and labels of this legend combining shape and colour elements.

data <- data.frame(x = rep(seq(from=10, to=100, by=10), each=2),
                   y = runif(20,0,1),
                   group = rep(0:1,20))

data %>% 
  ggplot(aes(x=x, y=y, col=factor(group), shape=factor(group))) +
  geom_point(size=3) + geom_line()

在此处输入图像描述

I have tried this post Combine legends for color and shape into a single legend

data %>% 
  ggplot(aes(x=x, y=y, col=factor(group), shape=factor(group))) +
  geom_point(size=3) + geom_line() +
  scale_colour_manual(name = "Group",
                    labels = c("A, B"),
                    values = c("blue", "red")) +   
  scale_shape_manual(name = "Group",
                     labels = c("A, B"),
                     values = c(0,1))

where I can combine shape and colour in principle, but I need to specify new colors. I would like to keep the defaults, just change the labels of the legend.

You can use scale_color_discrete and scale_shape_discrete . Just supply the same name and labels argument to each. There is no need to stipulate values .

You can see that this will retain the default shapes and colors:

data %>% 
  ggplot(aes(x, y, col = factor(group), shape = factor(group))) +
  geom_point(size = 3) + 
  geom_line() +
  scale_color_discrete(name = "Group", labels = c("A", "B")) +
  scale_shape_discrete(name = "Group", labels = c("A", "B"))

在此处输入图像描述

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