关于在ggplot中添加图例

About add legend in ggplot

这是我的代码:

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')

我建立了一个名为 full 的数据集,它看起来像这样:

我想绘制列 DU1、DU2、DUR1、DUR2 与 num 的关系,这是绘图的样子 运行 当前代码:

而我希望DU1和DUR1的线条颜色相同,DU2,DUR2的线条颜色相同,所以我分别设置颜色为1和2,我想要DU1和DU2为实线,DUR1和DUR2为虚线,我想为这些线添加图例,但由于设置,我无法将colorlinetype设置放在aes(),而且我猜也不能使用 scale_color_discrete 来实现它,那么如何将图例添加到情节中呢? 感谢您的帮助。

对于您的 full 数据,我建议采用下一种方法重塑数据,然后使用 scale_color_manual()scale_linetype_manual() 进行格式化。您可以使用 pivot_longer() 直接重塑数据。所有函数都可以在 ggplot2tidyverse 包中找到:

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'))

输出:

我已经定义了标准颜色,但您可以根据需要更改它们。