'R Plot not showing if inside function [duplicate]
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.
Solution 1:[1]
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
