How to add legends to a geom_line() function in ggplot?

I´m trying to set legends to two lines in my graph in order to people recognize what represents each line, but I don’t know how

Here’s a code example

x <- c(2,4,6,8,10)
y <- (6:10)
z <- (1:5)
df <- data.frame(x,y,z)

ggplot(df) +
  geom_line(aes(x=z, y=x), color="black") + 
  geom_line(aes(x=z, y=y), color="red")

enter image description here

I would like to watch legends like the next graph in the part of "Periodo"

enter image description here

I DON’T want to categorized my data by another vector, as follows:

ggplot(df) +
  geom_line(aes(x=z, y=x, color="categoria")) 

>Solution :

You can stack all variables you want to display into a single column, and use their names as color labels.


df %>%
  pivot_longer(c(x, y), names_to = "catogory") %>%
  ggplot() +
  geom_line(aes(x = z, y = value, color = catogory))

enter image description here

Leave a Reply