【问题标题】:R ggplot2: Blank page before plot with pdf() and ggplot_gtable() / ggplot_build()R ggplot2:使用 pdf() 和 ggplot_gtable() / ggplot_build() 绘图前的空白页
【发布时间】:2017-09-22 05:25:49
【问题描述】:

我需要修改一个绘图的一些注释,所以我必须保存 ggplot2 绘图并做

ggplot_build(plot.obj)

然后用它绘制

plot(ggplot_gtable(ggplot_build(plot.obj)))

问题是,当我将它保存在这样的 pdf 中时

pdf(file="test.pdf")
  plot(ggplot_gtable(ggplot_build(plot.obj)))
dev.off()

生成的 pdf 在绘图页之前有一个空白页...我怎样才能避免这种情况?

检查这个 MWE

data(iris)
library(ggplot2)
box <- ggplot(data=iris, aes(x=Species, y=Sepal.Length)) +
    geom_boxplot(aes(fill=Species)) +
    ylab("Sepal Length") + ggtitle("Iris Boxplot") +
    stat_summary(fun.y=mean, geom="point", shape=5, size=4) 
box2 <- ggplot_build(box)
#I do stuff here
pdf(file="test.pdf")
  plot(ggplot_gtable(box2))
dev.off()

问题是如何在没有空白页的情况下使用 ggplot_gtable 制作 pdf?

【问题讨论】:

    标签: r pdf ggplot2


    【解决方案1】:

    这个论点onefile=FALSE 解决了这个问题!

    data(iris)
    library(ggplot2)
    box <- ggplot(data=iris, aes(x=Species, y=Sepal.Length)) +
      geom_boxplot(aes(fill=Species)) +
      ylab("Sepal Length") + ggtitle("Iris Boxplot") +
      stat_summary(fun.y=mean, geom="point", shape=5, size=4) 
    box2 <- ggplot_build(box)
    #I do stuff here
    pdf.options(reset = TRUE, onefile = FALSE)
    pdf(file="test.pdf")
    my_plot <- plot(ggplot_gtable(box2))
    #ggsave("test1.png", plot = my_plot,dev = 'png')
    print(my_plot)
    dev.off()
    

    【讨论】:

    • 嘿,这仅适用于单页 pdf,多页需要一些 hack!
    【解决方案2】:

    简单地做:

    plot(ggplot_gtable(box2))
    ggsave(filename = "my_plot.pdf")
    

    【讨论】:

      猜你喜欢
      • 2013-08-26
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      • 2023-03-24
      • 1970-01-01
      • 2021-08-20
      相关资源
      最近更新 更多