我有一个用于绘制3个geom_line
的for循环,如何添加标签/图例,使它们不会全部成为3条难以区分的黑线?
methods.list <- list(rwf,snaive,meanf)
cv.list <- lapply(methods.list, function(method) {
taylor%>% tsCV(forecastfunction = method, h=48)
})
gg <- ggplot(NULL, aes(x))
for (i in seq(1,3)){
gg <- gg + geom_line(aes_string( y=sqrt(colMeans(cv.list[[i]]^2, na.rm=TRUE))))
}
gg + guides(colour=guide_legend(title="Forecast"))
如果我不使用循环,则可以使用aes
而不是那个可怕的aes_string
,然后一切正常,但是我必须编写相同的代码3次并用此替换循环:
gg <- gg + geom_line(aes(y=sqrt(colMeans(cv.list[[1]]^2, na.rm=TRUE)), colour=names(cv.list)[1]))
gg <- gg + geom_line(aes(y=sqrt(colMeans(cv.list[[2]]^2, na.rm=TRUE)), colour=names(cv.list)[2]))
gg <- gg + geom_line(aes(y=sqrt(colMeans(cv.list[[3]]^2, na.rm=TRUE)), colour=names(cv.list)[3]))
,然后有很好的自动颜色和图例。我想念什么?为什么R这么不友好?
答案 0 :(得分:0)
该示例不可复制,(没有数据!),但看来您在列表cv.list
中包含一些数据,其中包含多个data.frame,并且您想针对每个数据绘制一些摘要统计信息存储在x
中的常见变量。
最简单的方法就是创建一个data.frame
并使用data.frame进行绘制。
#Create 3 data.frames with data (forecast?)
df <- lapply(1:3, function(group){
summ_stat <- sqrt(colMeans(cv.list[[i]]^2, na.rm=TRUE))
group <- group
data.frame(summ_stat, group, x = x)
})
#bind the data.frames into a single data.frame
df <- do.call(rbind, df)
#Create the plot
ggplot(data = df, aes(x = x, y = summ_stat, colour = group)) +
geom_line() +
labs(colour = "Forecast")
请注意labs
参数中标签的更改。这将更改colour
的一部分aes
的标签。