0

I am a new R user and I am trying to add a legend to my lines plot. This is the command line that I used to make the plot and the relative plot.

ggplot(crab_tag$daylog, aes(Date))+ geom_line(aes(y=-Max.Depth), color="blue")+ geom_line(aes(y=-Min.Depth),color="violet")+ labs(x="Date",y="Depth(m)")+ theme(legend.position = c(0,1),legend.justification = c(0,1)) +scale_color_manual(values = c("blue","violet"))

Anyone can help me to see my error? Thanks!

1 Answers1

0

Based on this thread https://community.rstudio.com/t/adding-manual-legend-to-ggplot2/41651/2 I found the following: The issue here is that you have to link the colour to the legend (and also have to call the legend). Here is a solution:

library(tidyverse)`
library(learningr)`

ggplot(crab_tag$daylog, aes(Date)) + 
  geom_line(aes(y=-Max.Depth, colour = "Max.Depth")) + 
  geom_line(aes(y=-Min.Depth, colour = "Min.Depth"))+ 
  labs(x="Date",y="Depth(m)", colour = "legend")+ 
  theme(legend.position = c(0,1),legend.justification = c(0,1)) +
  scale_color_manual(values = c("Max.Depth"="blue","Min.Depth"="violet"))

You see, the main changes is to call colour within the aes() function and there define the variable name you want to use in the legend, the label of the colour legend in labs, and the named vector for values in scale_colour_manual()

Owe Jessen
  • 247
  • 1
  • 2
  • 11
  • Thank you Owe for your suggestions and advice. I managed to add the legend and to understand what I was doing wrong. I appreciate it! – mariapambr May 20 '20 at 00:37