2014-09-29 16 views
0

的說法,我在這裏該功能的工作:ggplot期權數量的功能

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線,所以我想我需要找到一些方法來「複製」stat_function()num_lines次。任何想法我可以做到這一點?

+0

請舉一個'data'的例子。 – Roland 2014-09-29 12:16:18

回答

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)