use*_*084 1 r function ggplot2
我发现如果 ggplot是函数中的最后一件事,那么调用该函数将导致 ggplot 按预期创建绘图。
但是,如果 ggplot 不是函数中的最后一件事——假设它后面跟着一个赋值(如 x <- t)或一个 return 语句(如 return(x)),那么 ggplot 将不会创建绘图。
有什么解决办法吗?
PS请添加评论,解释如何创建用于指示代码的内联灰色背景:-)
用于plot您的ggplot对象。
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
Run Code Online (Sandbox Code Playgroud)
顺便说一句,func1创建绘图并不是因为ggplot这是函数中要做的最后一件事。它创建绘图,因为函数返回ggplot对象并且代码func1()调用print对象的方法。要看到这一点,如果您这样做a <- func1(),则不会创建绘图,而是将其存储在a变量中。
注意:您可以使用printinsted。 print和plot对于对象来说是等价的ggplot。