-1

I am trying to add a legend to my plot using my own data.

rich_ph <- ggplot(CR_ph) + 
  geom_jitter(aes(ph,all.fungi), colour="pink") +   
  geom_smooth(aes(ph,all.fungi), color="pink", method=lm, se=FALSE) +
  geom_jitter(aes(ph,Animal.parasite), colour="blue") + 
  geom_smooth(aes(ph,Animal.parasite), color="blue", method=lm, se=FALSE) +
  geom_jitter(aes(ph,Plant.Pathogen), colour="green") + 
  geom_smooth(aes(ph,Plant.Pathogen),color= "green", method=lm, se=FALSE) 

I will post here a reproducible example (present on an old post) that I followed to build my plot:

ggplot(mtcars) + 
  geom_jitter(aes(disp,mpg), colour="blue") + 
  geom_smooth(aes(disp,mpg), method=lm, se=FALSE) +
  geom_jitter(aes(hp,mpg), colour="green") + 
  geom_smooth(aes(hp,mpg), method=lm, se=FALSE) +
  geom_jitter(aes(qsec,mpg), colour="red") + 
  geom_smooth(aes(qsec,mpg), method=lm, se=FALSE) +
  labs(x = "Percentage cover (%)", y = "Number of individuals (N)")

I have tried by using

 scale_color_manual(labels = c("disp", "hp", "qsec"), values = c("blue","green", "red"))

as shown in other posts, but the problem for me is that nothing is shown on the plot. I have also tried:

rich_ph + scale_colour_manual(name="Functional groups", labels = c("All fungi", "Animal parasite", "Plant pathogen"), values=c("pink", "blue", "green")enter code here

I would like to get the color points as well as the regression line, but with the script I use, I don't get any output. thanks a lot for any help!

i.b
  • 167
  • 11

1 Answers1

0

The recommended ggplot2 way is to make the data long before plotting. Here I use the tidyverse for data transformation and gather to make the data long. Following this will plot an appropriate legend automatically.

library(tidyverse)
mtcars %>% 
  as.tibble() %>% 
  select(mpg, disp, hp, qsec) %>% 
  gather(key, value, -mpg) %>% 
  ggplot(aes(y=mpg, x=value, color=key)) +
    geom_point() +
    geom_smooth(method=lm, se=FALSE)

enter image description here

Adding scale_color_manual(values = c("blue", "green", "red")) will change the color as desired.

Roman
  • 17,008
  • 3
  • 36
  • 49
  • Now, it worked perfectly! thanks a lot, it is, indeed, the solution I was looking for! – i.b Feb 26 '18 at 14:42