1

How to add a legend to this picture? I tried scale_color_manual() and legend(), but it didn’t work. I think there must be steps I don’t know. Is there any way?

library(ggplot2)

data<-data.frame(R=c(0.9649789,0.9700804,0.9632690,0.9523244,0.9339738),
             M=c(0.2465927,0.2263204,0.2520991,0.2982259,0.3614747),
             A=c(0.1427684,0.1428706,0.1642165,0.1937662,0.2353444),
             D=c(20,15,10,5,2))

ggplot(data,
       aes(x = D,y=R))+
geom_line(color="#6FB585")+
geom_point(size=3,color="#6FB585")+
scale_y_continuous(name = 'R',
                   sec.axis = sec_axis(~(.-0.875)/0.25, name = 'M and A'))+
geom_line(aes(y = M*0.25+0.875, x= D), color="#E8BF80") +
geom_point(aes(y=M*0.25+0.875, x=D),size=3,color="#E8BF80")+
geom_line(aes(y=A*0.25+0.875,x=D), color="#A8BF85")+
geom_point(aes(y=A*0.25+0.875 , x=D),size=3,color="#A8BF85")
吳海濱
  • 71
  • 5
  • 2
    Make your data tidy by adding an extra column within the data frame (`Model` say) to identify which line is which. Put `color=Model` inside your call to `ae()` and the legends will appear automatically. You'll need only one `geom_line` and one `geom_point`. `ggplot` is designed to work with [tidy](https://cran.r-project.org/web/packages/tidyr/vignettes/tidy-data.html) data. Your data is not tidy. Hence your pain. – Limey Nov 25 '22 at 08:57

1 Answers1

2

You can mutate M and A according to your scale-factor, make the DF long, define color name and ggplot will take care of the legend.

library(tidyverse)


data<-data.frame(R=c(0.9649789,0.9700804,0.9632690,0.9523244,0.9339738),
                 M=c(0.2465927,0.2263204,0.2520991,0.2982259,0.3614747),
                 A=c(0.1427684,0.1428706,0.1642165,0.1937662,0.2353444),
                 D=c(20,15,10,5,2))

data %>% 
  mutate(M = M*0.25+0.875,
         A = A*0.25+0.875) %>% 
  pivot_longer(cols = R:A) %>% 
  ggplot(aes(D,value, color = name)) +
  geom_line() +
  geom_point(size=3)+
  scale_y_continuous(name = 'R',
                     sec.axis = sec_axis(~(.-0.875)/0.25, name = 'M and A'))

MarBlo
  • 4,195
  • 1
  • 13
  • 27