2016-05-23 67 views
2

使用包裝與運算符「+」我開始與問題:有沒有一種方法創建一個函數,說ggColors,從包裝ggplot2包裝等幾個功能?該函數加起來應該使用運營商+(而不是%>%運營商)在這個例子中ggplot對象:總結幾個GGPLOT2功能和R中

p <- ggplot(mtcars, aes(hp,disp, color = as.factor(cyl))) + geom_point() 
p + ggColors() 

ggColors應該是這樣的:

ggColors <- function(values = NULL, name = NULL, cold.colors = TRUE) { 
    # Some conditions: 
    if (is.null(values)){ 
     if (cold.colors) { 
      values <- c("darkblue","blue", "green") 
     } else { 
      values <- c("red","orange", "yellow") 
     } 
    }  
    # Modified default values of `ggplot2` functions: 
    scale_color_manual(name = name, values = values) + 
    scale_fill_manual (name = name, values = values) 
} 

的問題是,scale_color_manualscale_fill_manual不加起來,因爲它們不會導致功能ggColors內部的ggplot對象。

回答

3

ggColors應該返回一個圖元素列表。然後所有返回列表的元素可以添加使用+劇情:

ggColors <- function(values = NULL, name = NULL, cold.colors = TRUE) { 
    # Some conditions: 
    if (is.null(values)){ 
     if (cold.colors) { 
     values <- c("darkblue","blue", "green") 
     } else { 
     values <- c("red","orange", "yellow") 
     } 
    }  
    # Modified default values of `ggplot2` functions: 
    return(list(scale_color_manual(name = name, values = values), 
       scale_fill_manual (name = name, values = values))) 
    } 

然後,

p + ggColors()