关于在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",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),color=1,linetype = 'dashed')+
    geom_line(aes(x = num,y = DU2),color=2)+
    geom_line(aes(x = num,y = DUR2),color=2,linetype = 'dashed')

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

enter image description here

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

enter image description here

我希望DU1和DUR1的行具有相同的颜色,而DU2,DUR2的行具有相同的颜色,因此我分别将颜色设置为1和2,并且我希望DU1和DU2分别为实线,DUR1和DUR2为虚线,我想在这些行中添加图例,但是由于该设置,我无法将colorlinetype设置放入aes()中,而且我猜也不能使用scale_color_discrete来实现它,那么如何向图中添加图例? 谢谢您的帮助。

解决方法

对于您的describe(ResponseCamelCaseInterceptor.name,() => { const createService = createServiceFactory(ResponseCamelCaseInterceptor); test('some description',() => { const { service } = createService(); const fakeHttpRequest = new HttpRequest('POST','https://...',{ custom_key: '1' }); service.intercept(fakeHttpRequest,'what should I put here for HttpHandler?').subscribe(() => { // expect(httpResponse.body).toStrictEqual({ customKey: '1' }); }); }); }); 数据,我建议采用以下方法重塑数据,然后使用fullscale_color_manual()进行格式化。您可以使用scale_linetype_manual()直接重塑数据。所有功能都可以在pivot_longer()ggplot2软件包中找到:

tidyverse

输出:

enter image description here

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