将 ggplot 与图形函数一起使用

Using ggplot with figure functions

我正在尝试了解 图形函数 我使用基于 ggplot 的绘图从 Nice R Code blog 到 运行。

让我快速回顾一下他们的想法:基本上,这只是一种在打印到文件时提高可读性和结构的方法。不必打开绘图设备、生成绘图然后使用 dev.off() 关闭设备,建议的方法是通过定义一个生成图形的函数和另一个将其写入文件的函数来分离这两个任务.

to.dev <- function(expr, dev, filename, ..., verbose=TRUE) { 
  if (verbose) {
    cat(sprintf("Creating %s\n", filename))
  }

  dev(filename, ...)
  on.exit(dev.off())
  eval.parent(substitute(expr))
} 

to.png <- function(expr, filename, ..., verbose=TRUE) {
  to.dev(expr, png, filename)
}

fig.progressive <- function(with.trend=FALSE) {
  set.seed(10)
  x <- runif(100)
  y <- rnorm(100, x)
  par(mar=c(4.1, 4.1, .5, .5))
  plot(y ~ x, las=1)
  if ( with.trend ) {
    fit <- lm(y ~ x)
    abline(fit, col="red")
    legend("topleft", c("Data", "Trend"),
           pch=c(1, NA), lty=c(NA, 1), col=c("black", "red"), bty="n")
  }
}

最后只需要写一行就可以输出图了:

to.png(fig.progressive(TRUE), "figs/base.png", width = 6, height = 4)

这就像一个魅力,如果你必须为很多人物做这些事情,那就太棒了。但是,它不适用于 ggplot。当尝试这样的事情时:

fig.progressive.ggplot <- function(with.trend=FALSE) {
  set.seed(10)
  df.x <- runif(100)
  df.y <- rnorm(100, df.x)
  df <- data.frame(df.x, df.y)
  plot <- ggplot(data = df, aes(x = df.x, y = df.y)) + geom_point()
  if ( with.trend ) {
    plot <- plot + geom_smooth()
  }
  plot
}

然后使用

将其写入设备
to.png(fig.progressive(TRUE), "figs/ggplot.png", width = 6, height = 4)

没有任何反应。代码是 运行,但没有 figs/ggplot.png 文件。

我了解到其他用户在全局环境以外的环境中遇到 ggplot 问题,我认为这可能与我的问题有关。但是我想不通,问题到底是什么。

如果能解决此问题,我将不胜感激and/or 关于如何在输出多个图形时编写干净、可读的代码的其他建议。

保存 ggplot 图形的正确方法是使用 ggsave。参见 http://docs.ggplot2.org/current/ggsave.html

如果您不想使用 ggsave,只需将 plot 更改为 print(plot) 即可。参见 http://www.cookbook-r.com/Graphs/Output_to_a_file/

即:

fig.progressive.ggplot <- function(with.trend=FALSE) {
  set.seed(10)
  df.x <- runif(100)
  df.y <- rnorm(100, df.x)
  df <- data.frame(df.x, df.y)
  plot <- ggplot(data = df, aes(x = df.x, y = df.y)) + geom_point()
  if ( with.trend ) {
    plot <- plot + geom_smooth()
  }
  print(plot)
}