我在这里使用此功能:
library(ggplot2)
getp1 <- function(names, data, colors) {
num_lines <- length(names)
p1_colors <- colors
names(p1_colors) <- names
p1 <- ggplot(data.frame(x = c(0,720)), aes(x)) +
stat_function(fun=data[[1]], geom="line", aes(colour=names[1]), size=1) +
stat_function(fun=data[[2]], geom="line", aes(colour=names[2])) +
stat_function(fun=data[[3]], geom="line", aes(colour=names[3])) +
stat_function(fun=data[[4]], geom="line", aes(colour=names[4])) +
scale_x_continuous(name="") + scale_y_continuous(name="") +
scale_colour_manual(name = "", guide = FALSE, values = p1_colors)
return(p1)
}
现在,我从中获得了四条数据线。但我希望它能准确地绘制num_lines
行,所以我想我需要找到一些方法来复制&#34; stat_function()
位num_lines
次。知道我该怎么做吗?
答案 0 :(得分:0)
完全没有看到这个的目的,可能误解了这个问题。但我认为您可以使用lapply
来实现您想要的效果。
library(ggplot2)
# your version, changed so it works for me...
# (may already be something else than you expected?)
getp1_old <- function(names, data, colors) {
p1 <- ggplot(data.frame(x = c(0,720)), aes(x)) +
stat_function(fun=data[[1]], geom="line", colour=colors[1], size=1) +
stat_function(fun=data[[2]], geom="line", colour=colors[2]) +
stat_function(fun=data[[3]], geom="line", colour=colors[3]) +
stat_function(fun=data[[4]], geom="line", colour=colors[4]) +
scale_x_continuous(name="") + scale_y_continuous(name="") +
scale_colour_manual(guide = FALSE, values = colors)
return(p1)
}
# my version, with lapply
getp1_new <- function(names, data, colors) {
num_lines <- length(names)
stat_fct_combine <- lapply(1:num_lines, function(index){
stat_function(fun=data[[index]], geom="line", colour=colors[index])
})
p1 <- ggplot(data.frame(x = c(0,720)), aes(x)) +
stat_fct_combine +
scale_x_continuous(name="") +
scale_y_continuous(name="") +
scale_colour_manual(guide = FALSE, values = colors)
return(p1)
}
# reproducible example
nms <- paste0('nr', 1:6)
dta <- list(function(x) 1, function(x) 2, function(x) 3, function(x) 4,
function(x) 5, function(x) 6)
cols <- rep(c('red', 'green', 'black', 'blue'), length=6)
# example plots
getp1_old(nms, dta, cols)
getp1_new(nms[1:4], dta, cols)
getp1_new(nms, dta, cols)