如何在Rstudio中清除绘图查看器?

时间:2020-10-25 20:27:49

标签: r rstudio

我将对象保存到列表中,并且每次加载这些对象时都想清除图窗格和查看器窗格。在浏览完列表中该元素中的图表后,我基本上希望后退按钮变灰。

这是我的代码

gg <- ggplot(iris, aes(width, length)) + geom_point
l <- list()
l[["element"]] <- gg

我想要它,以便当我运行l $ element时,就像我第一次在rstudio中单击绘图和查看器选项卡上的扫帚一样。

2 个答案:

答案 0 :(得分:1)

只要将ggplot存储在自定义S3类中即可,您可以执行此操作,该类的默认打印方法调用dev.off然后绘制随附的ggplot:

gg_wipe <- function(x) structure(list(plot = x), class = "gg_wipe")

print.gg_wipe <- function(x) {dev.off(); print(x$plot)}

gg <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point()
l <- list() 
l[["element"]] <- gg_wipe(gg)

l[["element"]]

答案 1 :(得分:1)

或者可以像提供Allan一样包装图(这是个好主意),而不是提供一个辅助函数,然后提供不同的获取方法。因此,这直接调用了辅助函数

l <- list(
   apple=ggplot(data.frame(x=1:3, y=1:3)) + geom_point(aes(x,y)),
   banana=ggplot(data.frame(x=1:3, y=3:1)) + geom_point(aes(x,y))
)
clear_and_print <- function(x, ele) {
   graphics.off(); invisible(print(x[[deparse(substitute(ele))]]))
}
clear_and_print(l, apple)

您可以定义一些新的运算符,但是它们必须在语法上有效。您不能拥有^^^的伯尔%^%

`%^%` <- clear_and_print
l %^% apple
l %^% banana

或者您可以为容器创建一个特殊的类

`$.plot_clear` <- function(x, ele) {
  graphics.off(); x[[ele]]
}
class(l) <- "plot_clear"
l$apple
l$banana