13

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))
}
1
  • try: x <- ggplot(data=df, aes(x=time, y=total_bill)) + geom_bar(aes(fill=time)) and then print(x) This is a common challenge to people using ggplot in a function. Commented Aug 3, 2012 at 16:08

1 Answer 1

20

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()
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! I did already know that, but haven't thought about it! Think before you post! ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.