【问题标题】:Using ggplot with figure functions使用带有图形功能的 ggplot
【发布时间】:2015-05-18 05:49:30
【问题描述】:

我正在尝试了解 图形函数我从 Nice R Code blog 获得的想法,以运行基于 ggplot 的绘图。

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

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 的问题,并认为这可能与我的问题有关。但我无法弄清楚问题到底是什么。

我将不胜感激此问题的解决方案和/或有关如何在输出多个数字时编写干净、易读的代码的其他建议。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    保存 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)
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-22
      • 2022-09-30
      • 2020-10-06
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      相关资源
      最近更新 更多