0

I am trying to create a legend in ggplot. If I use different variables from the same file, I add colour = "xx" in aes and it works. but what about if it is the same variable but different datasets?

In the example below, I plot Value ~ Year from two different datasets. How can I create a legend that says df1 with a red line, and df2 with a blue line?

A <- c(2001, 2002, 2003, 2004, 2005)
B <- c(3, 5, 2, 7, 5)
C <- c(2, 7, 4, 3, 5)


df1 <- data.frame(A, B)
df2 <- data.frame(A, C)

colnames(df1) <- c("Year","Value")
colnames(df2) <- c("Year","Value")


(test <- ggplot(df1, aes(Value, Year)) + geom_path(size = 1, colour='red') + 
geom_path(data=df2, colour='blue') + ylab("Year")+ scale_x_continuous(position = "top") +  scale_y_reverse(expand = c(0, 0)))

2 Answers 2

0

We could create a single dataset with bind_rows and specify .id to create a grouping column, which can be passed in aes as 'colour`

library(ggplot2)
library(dplyr)
bind_rows(lst(df1, df2), .id = 'grp') %>% 
    ggplot(aes(Value, Year, colour = grp)) +
      geom_path(size = 1) + 
      ylab("Year")+ 
      scale_x_continuous(position = "top") +  
      scale_y_reverse(expand = c(0, 0))

-output enter image description here

0

Here is simple solution, but not a great one with you have more data.frames

Libraries

library(tidyverse)

Code

ggplot(df1, aes(Value, Year)) +
  geom_path(size = 1,aes(colour='df1')) +
  geom_path(data = df2,size = 1,aes(colour='df2')) +
  ylab("Year")+
  scale_x_continuous(position = "top") +
  scale_y_reverse(expand = c(0, 0))+
  scale_colour_manual(values = c("df1" = "red", "df2" = "blue"))

Output

enter image description here

2
  • Would scale_colour_labs change the name? id like to change df1 in the legend to a different name. I can do this the long way by changing the file name! but is there a shortcut?
    – L55
    Commented Sep 9, 2021 at 4:42
  • 1
    Yes @L55, you can set them, e.g., scale_colour_manual(values = c("df1" = "red", "df2" = "blue"),labels = c("a","b")) Commented Sep 9, 2021 at 4:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.