Why does ggplot not plot when storing to variable?

rjs*_*jss 1 plot r ggplot2 read-eval-print-loop

I thought this was obvious, but recently I was using the package openair and noticed that when I run the following:

library(openair)
myplot <- windRose(mydata)
Run Code Online (Sandbox Code Playgroud)

the plot myplot is still plotted in the viewer. After looking at the windRose function it is obvious the plot function is being called.

However, why does myggplot <- ggplot(mtcars, aes(cyl, mpg)) + geom_point() not have the same outcome of plotting to the viewer. I am guessing the difference is in how these functions are programmed but I cannot easily identify how ggplot handles the plotting part.

mer*_*erv 5

这不是 ggplot 特定的行为,而是一个更通用的原则:R REPL 一般不会打印赋值语句,而对于表达式,它根据对象类型调用print()或对结果值进行处理(请参阅R 的自动打印部分)内部细节)。例如,1show()

> 1 + 1       # expression
[1] 2
> x <- 1 + 1  # assignment
>
Run Code Online (Sandbox Code Playgroud)

对于 ggplot 对象,调用print该对象会触发渲染。因此,如果您不分配,它就会被渲染。例如,

> ggplot(mtcars, aes(hp, mpg)) + geom_point()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

> g <- ggplot(mtcars, aes(hp, mpg)) + geom_point()
>
Run Code Online (Sandbox Code Playgroud)

plot另一方面,该函数包含渲染作为其一部分,这就是为什么您调用的另一个函数尽管进行了赋值仍会被渲染。

请注意,可以使用该invisible函数临时设置R_VisibleFALSE,这会关闭打印表达式的默认行为,但仍会将计算结果推送到.Last.value

> invisible(1 + 1)
> .Last.value
[1] 2
Run Code Online (Sandbox Code Playgroud)

但是,由于plot()调用图形设备的渲染作为其代码的一部分,invisible()因此不会阻止其渲染。

> invisible(plot(mtcars$hp, mtcars$mpg))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


[1]图片来源@Gregor