我會直接跳到一個例子,後記評論:傳遞數據和列名通過另一個功能ggplot
cont <- data.frame(value = c(1:20),variable = c(1:20,(1:20)^1.5,(1:20)^2),group=rep(c(1,2,3),each=20))
value variable group
1 1 1.000000 1
2 2 2.000000 1
3 3 3.000000 1
#... etc.
#ser is shorthand for "series".
plot_scat <- function(data,x,y,ser) {
ggplot(data,aes(x=x,y=y,color=factor(ser)))+geom_point()
}
plot_scat(cont,value,variable,group)
#This gives the error:
#Error in eval(expr,envir,enclose) : object 'x' not found
現在,我知道有GGPLOT2一個已知的bug,其中AES()將只在看全球環境而不是當地環境。根據建議:Use of ggplot() within another function in R,我嘗試了另一條路線。
plot_scat <- function(data,x,y,ser) {
#environment=environment() added
ggplot(data,aes(x=x,y=y,color=factor(ser)),environment=environment())+geom_point()
}
plot_scat(cont,value,variable,group)
#This gives the error:
#Error in eval(expr,envir,enclos) : object 'value' not found
#In addition: Warning message:
#In eval(expr,envir,enclos) : restarting interrupted promise evaluation
我不知道最後一行是什麼意思。如果我打電話: ggplot(cont,aes(x = value,y = variable,color = group))+ geom_point()
我得到您期望的圖。在命令行中,aes()正在尋找ggplot()中的變量名,但在函數調用中沒有這樣做。所以,我想改變我的電話:
plot_scat(cont,cont$value,cont$variable,cont$group)
這讓我我想要的東西。所以我增加了複雜性的下一層:
plot_scat <- function(data,x,y,ser) {
#added facet_grid
ggplot(data,aes(x=x,y=y,color=factor(ser)),environment=environment())+geom_point()+
facet_grid(.~ser)
}
plot_scat(cont,cont$value,cont$variable,cont$group)
#This gives the error:
#Error in layout_base(data, cols, drop = drop):
# At least one layer must contain all variables used for facetting
我對這個問題的想法是,SER實際上是續$組,這是罰款用於AES(),但傳遞給facet_grid的時候,現在是一列數據沒有關於價值和變量的信息。根據幫助頁面,facet_grid不採用「data =」參數,所以我不能使用facet_grid(data = data ,.〜ser)來解決這個問題。我不知道如何從這裏出發。
這是一個非常簡單的例子,但長期目標是讓我的辦公室裏有非識字人員的功能,並說「給它的數據框名稱,列名和列想要分裂,它會爲你做出漂亮的陰謀「。它也將變得更加複雜,帶有一個非常定製的主題,這與我遇到的問題無關。