2017-09-05 17 views
0

GGPLOT2我試圖從產生可變的參數號地塊。該代碼工作正常,並生成預期的情節。但是,標籤功能(fill = labels [i])不能按預期工作。我無法弄清楚我在這裏做錯了什麼。所有的行都有相同的標籤「C 3」,因此具有相同的顏色。不正確的標貼,同時增加stat_function地塊使用循環

library(ggplot2) 
F.Linear <- function(A, a, b, c) { 
    C <- (c - a*A)/b 
    C[C < 0] <- NA 
    return(C) 
} 

plot.linear.equations <- function(X, ...){ 
p <- ggplot(data.frame(x = X), aes(x = x)) 

    arguments <- list(...) 

    mycolors <- c("red", "blue", "green", "orange") 
    labels <- c("C 1", "C 2", "C 3", "C 4") 

    for(i in 1:length(arguments)){ 
    C <- unlist(arguments[i]) 
    p <- p + stat_function(fun=F.Linear, args = list(a=C[1], b=C[2], c=C[3]), geom="area", colour="black", alpha=0.2, aes(fill = labels[i])) 
    } 
    p <- p + scale_x_continuous(name = "A") + 
    scale_y_continuous(name = "C") + 
    scale_fill_manual("Constraints", values = c("red", "blue", "green", "orange")) 
return(p) 
} 

C1 <- c(12, 6, 20400) 
C2 <- c(9, 15, 25200) 
C3 <- c(6, 6, 12000) 


plot.linear.equations(c(0, 3000), C1, C2, C3) 

enter image description here

+2

的可能的複製[GGPLOT2:將在一個循環線和保持顏色映射(https://stackoverflow.com/questions/32698616/ggplot2-adding-lines-in-a-環和固色的映射) – aosmith

+0

據我所知,這個問題看起來差不多,但是,我不能使用的伎倆上的鏈接的問題(使用cbind添加變量數據)。仍在試圖弄清楚。 – max

+0

不,這是我的確切代碼。我沒有做X $ labels = labels [1]。在鏈接的例子,他們所使用的數據列,但我沒有在stat_function數據列。仍在試圖弄清楚。我知道,如果我把它作爲一個整體而不是循環寫出來,它就會起作用。但我想弄清楚爲什麼循環不起作用。 – max

回答

1

如重複所示,標籤移動到數據集繞過aes延遲評價的問題。

可以通過先使該函數中的數據集和循環爲數據集中的新變量中加入適當的labels值,它做到這一點。您可以使用此數據集的stat_functiondata說法。

plot.linear.equations <- function(X, ...){ 
    dat <- data.frame(x = X) 

    p <- ggplot(mapping = aes(x = X)) 

    arguments <- list(...) 

    mycolors <- c("red", "blue", "green", "orange") 
    labels <- c("C 1", "C 2", "C 3", "C 4") 

    for(i in 1:length(arguments)){ 
      dat$label <- labels[i] 
      C <- unlist(arguments[i]) 
      p <- p + stat_function(data = dat, fun=F.Linear, args = list(a=C[1], b=C[2], c=C[3]), geom="area", colour="black", alpha=0.2, aes(fill = label)) 
    } 

    p <- p + scale_x_continuous(name = "A") + 
      scale_y_continuous(name = "C") + 
      scale_fill_manual("Constraints", values = c("red", "blue", "green", "orange")) 
    return(p) 
} 

enter image description here

+0

太棒了!謝謝! – max