user3878084 user3878084 - 8 days ago 6
R Question

R if ggplot not last in function, it won't plot

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 :-)

Answer

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.