自定义函数,ggplot和返回值 [英] Custom Function, ggplot and return values
本文介绍了自定义函数,ggplot和返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
但是,如果我运行该函数,则不会出现图或数据帧。
你知道这个问题吗?可以给我一个解决方案吗?
非常感谢!
Rainer
以下是一个虚拟函数,让自己明白:
dummyfunct <-function(){
df < - data.frame(time = factor(c(Lunch,Dinner)) c(午餐,晚餐)),
total_bill = c(14.89,17.23))
ggplot(data = df,aes(x = time,y = total_bill)) + geom_bar(aes(fill = time))
return(df)
}
或
dummyfunct< -function(){
df<< - data.frame(time =因子(c(午餐,晚餐),水平= c(午餐,晚餐)),
total_bill = c(14.89,17.23))
ggplot data = df,aes(x = time,y = total_bill))+ geom_bar(aes(fill = time))
}
解决方案
我会回答,但我知道这是一个重复的问题,它可能会被关闭:
威特h ggplot你需要明确地在函数内使用 print
,如下所示:
dummyfunct <-function(){
df < - data.frame(time = factor(c(Lunch,Dinner),levels = c(Lunch,Dinner)),
total_bill = c(14.89,17.23))
x < - ggplot(data = df,aes(x = time,y = total_bill))+ geom_bar(aes(fill = time))
print(x)
return(df)
}
dummyfunct()
Today I noticed something strange. I wrote a function which should return a dataframe and a plot, a plot produced with ggplot2.
But if I run the function, either the plot will not appear or the dataframe.
Do you know this problem and can give me a solution to it?
Thank you very much!
Rainer
Here is a dummy function to make myself clear:
dummyfunct<-function(){
df <- data.frame(time = factor(c("Lunch","Dinner"), levels=c("Lunch","Dinner")),
total_bill = c(14.89, 17.23))
ggplot(data=df, aes(x=time, y=total_bill)) + geom_bar(aes(fill=time))
return(df)
}
or
dummyfunct<-function(){
df <<- data.frame(time = factor(c("Lunch","Dinner"), levels=c("Lunch","Dinner")),
total_bill = c(14.89, 17.23))
ggplot(data=df, aes(x=time, y=total_bill)) + geom_bar(aes(fill=time))
}
解决方案
I'll answer but I know this is a repeated question and it may likely get closed:
With ggplot you need to explicitally use print
inside a function as in:
dummyfunct<-function(){
df <- data.frame(time = factor(c("Lunch","Dinner"), levels=c("Lunch","Dinner")),
total_bill = c(14.89, 17.23))
x <- ggplot(data=df, aes(x=time, y=total_bill)) + geom_bar(aes(fill=time))
print(x)
return(df)
}
dummyfunct()
这篇关于自定义函数,ggplot和返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文