1

I discovered that if ggplot is the last thing in a function, then calling the function will result in ggplot creating a plot as expected.

But if ggplot is not the last thing in a function -- say it is followed by an assignment (like x <- t) or a return statement (like return(x)) then ggplot will not create a plot.

What is the work around for this?

P.S. please throw in a comment explaining how to create an inline grey background used to indicate code :-)

  • 1
    surround your code with backticks (``) to create the `code` line – SymbolixAU Nov 30 '16 at 00:46
  • Use ` to surround the code. – Kota Mori Nov 30 '16 at 00:47
  • 1
    It's not quite clear what you mean by a *work around*. In R, the _last thing_ in a function is what is returned, unless you explicitly use `return(myObj)`. What do you want the function to return? – SymbolixAU Nov 30 '16 at 00:47
  • I think this is (a version of) FAQ 7.22, e.g. http://stackoverflow.com/questions/24314858/how-can-i-plot-multiple-residuals-plots-in-a-loop/24315262#24315262 ; put `print()` around your `ggplot` call ... – Ben Bolker Nov 30 '16 at 00:49

1 Answers1

6

Use plot for your ggplot object.

func1 <- function() {
  require(ggplot2)
  ggplot(mtcars, aes(mpg, wt)) + geom_point()
}

func1()  # this creates plot


func2 <- function() {
  require(ggplot2)
  ggplot(mtcars, aes(mpg, wt)) + geom_point()
  cat("hey\n")
}

func2()  # this does not create plot


func3 <- function() {
  require(ggplot2)
  plot(ggplot(mtcars, aes(mpg, wt)) + geom_point())
  cat("hey\n")
}

func3()  # use plot to make sure your plot is displayed

By the way, func1 creates plot not because ggplot is the last thing to do in the function. It creates plot because the function returns the ggplot object and the code func1() invokes the print method of the object. To see this, If you do a <- func1(), then the plot is not created, but stored in the a variable.

Note: You can use print insted. print and plot are equivalent for the ggplot object.

Kota Mori
  • 6,510
  • 1
  • 21
  • 25