Ziqin He
Ziqin He

Reputation: 145

About add legend in ggplot

Here is my code:

library(ggplot2)
empty_list <- vector(mode = "list", length = 2)
test1 <- data.frame(matrix(ncol = 2, nrow = 0))
x <- c("DU", "DUR")
colnames(test1)<-x
test1[1,1] = 2
test1[2,1] = 4
test1[1,2] = 6
test1[2,2] = 8

test2 <- data.frame(matrix(ncol = 2, nrow = 0))
colnames(test2)<-x
test2[1,1] = 3
test2[2,1] = 5
test2[1,2] = 7
test2[2,2] = 9
empty_list[[1]] <- test1
empty_list[[2]] <- test2


for  (i in 1 : length(empty_list)){
colnames(empty_list[[i]]) = c( paste("DU", i, sep = ""),  paste("DUR", i, sep = ""))}
full <- cbind(empty_list[[1]], empty_list[[2]])
x <- 1:nrow(full)
full <- cbind(x, full)
colnames(full)[1] <- "num"
full


ggplot(full) +
    geom_line(aes(x = num  ,y = DU1), method="lm", formula= (y ~ x), color=1)+
    geom_line(aes(x = num  ,y = DUR1), method="lm", formula= (y ~ x), color=1, linetype = 'dashed')+
    geom_line(aes(x = num  ,y = DU2), method="lm", formula= (y ~ x), color=2)+
    geom_line(aes(x = num  ,y = DUR2), method="lm", formula= (y ~ x), color=2, linetype = 'dashed')

I set up a dataset called full and it looks like this: enter image description here

And I want to plot the columns DU1, DU2, DUR1, DUR2 versus num, and here is what the plot looks like running the current code: enter image description here

And I want the lines of DU1 and DUR1 to be in the same color and DU2,DUR2 to be in the same color, so I set the color to be 1 and 2 respectively, and I want the DU1 and DU2 to be solid lines, DUR1 and DUR2 to be dashed lines, and I want to add legend to these lines, but since the setting, I cannot put the color or linetype setting in the aes(), and also cannot use scale_color_discrete to achieve it I guess, so how can I add the legends to the plot? Thank you for any help.

Upvotes: 0

Views: 39

Answers (1)

Duck
Duck

Reputation: 39595

With your full data, I would suggest next approach reshaping the data and then formating with scale_color_manual() and scale_linetype_manual(). You can directly reshape data with pivot_longer(). All functions can be found in ggplot2 and tidyverse packages:

library(tidyverse)
#Melt data and plot
full %>% pivot_longer(cols = -num) %>%
  ggplot(aes(x=num,y=value,group=name,color=name,linetype=name))+
  geom_line()+
  scale_color_manual(values = c(DU1='red',DUR1='red',DU2='blue',DUR2='blue'))+
  scale_linetype_manual(values = c(DU1='solid',DUR1='dashed',DU2='solid',DUR2='dashed'))

Output:

enter image description here

I have defined standard colors, but you can change them according to what you want.

Upvotes: 1

Related Questions