Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

library(tidyverse)

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

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading