0

If I run the following code, everything works as expected and the plot shows on the right panel in RStudio:

plot(x=iris$Sepal.Width, y=iris$Sepal.Length)

However, if instead I call the plot from my own custom function, it no longer shows the plot. Why?

a <- function() {
  plot(x=iris$Sepal.Width, y=iris$Sepal.Length)
}

a

EDIT: As per the comments, I forgot to call a as a(). However, I have another scenario in which, once again, the plot is not being created, and I do not know why, this time with ggplot:

a <- function() {
  ggplot(iris, aes(x=Sepal.Width, y=Sepal.Length)) +
    geom_point()
  
  return(1)
}

b <- a()

If I return a value from the function, the plot is not created.

Tiago Silva
  • 455
  • 5
  • 20
  • 1
    Are you actually calling the function with `a()` rather than just `a`? – MrFlick Mar 29 '22 at 17:35
  • Thank you for the help, it now works. However, I added another scenario in my edit that still does not work – Tiago Silva Mar 29 '22 at 17:46
  • 1
    Well, now that's a different question. The `ggplot` function doesn't actually draw a plot. It returns an option that draw a plot when that object is printed. If you return the object from the function, R will normally print that for you. But if you don't return the value, you'll need to explicitly `print()` the result yourself – MrFlick Mar 29 '22 at 17:48

1 Answers1

3

Answer pre-edit:

That is not a function call (if we're talking R), that is an implicit print of a. Try a() instead of simply a.

Answer post-edit:

As @MrFlick mentioned in his comment, the result of ggplot should be printed, either implicitly (by evaluating its output at the console), or explicitly. The second example avoids the evaluation of the ggplot result at console (by returning 1 instead), so the only option left is explicit printing:

library("ggplot2")

a <- function() {
    print(
        ggplot(iris, aes(x=Sepal.Width, y=Sepal.Length))
      + geom_point()
    )
    return(1)
}

b <- a()
user51187286016
  • 256
  • 1
  • 5
  • Yeah, you are completely correct. Check my edit for another scenario with ggplot that still does not work as expected – Tiago Silva Mar 29 '22 at 17:48