在PowerPoint幻灯片中绘制具有给定大小的ggplot2图表 - R

3
我正在尝试使用officer包在PowerPoint幻灯片中绘制ggplot2图形。实际上我已经可以做到了(直接将ggplot2打印到ppt中),但是我需要增加ggplot2图形的大小(用于ppt幻灯片),我了解到ggplot2图形取决于窗口的大小(在RStudio中)或者您导出时设置的大小,因此我正在寻找一种方法:(1)以给定的大小导出ggplot2图形(例如:height=5, width=8),(2)从ppt代码中导入/读取。
library(officer)
library(devEMF)
library(magrittr)
library(ggplot2)

t <- "../example.pptx"
filename <- gg

read_pptx() %>% 
  add_slide(layout = "Title and Content", master = "Office Theme") %>% 
  ph_with_img(src = filename, width = 6, height = 4, type = "body") %>% 
  print(target = t)
gg 是 ggplot2 中的任何一个图表(实际上并不重要)。t 是输出文件的地址。 ph_with_img PowerPoint 文档和图形 注:如果有我不知道的包或命令,可以直接编辑 ggplot2 的大小,那么以上所有内容都是不必要的。

解决方案(1):使用例如 png()width = 8,height = 5 - erc
请查看我的答案,使用导出包中的graph2ppt命令,它允许您指定宽度和高度... - Tom Wenseleers
1
不需要外部保存ggplot对象或使用外部包,可以参见我下面的答案。 - JWilliman
3个回答

5

我刚刚基于officer创建了一个新的包export,它可以轻松地使用命令graph2ppt()来执行此操作,与上面其他答案中的位图不同,它可以很好地以矢量格式导出,例如:

install.packages("export")
library(export)
library(ggplot2)
qplot(Sepal.Length, Petal.Length, data = iris, color = Species, 
      size = Petal.Width, alpha = I(0.7))     
graph2ppt(file="plots.pptx", width=6, height=5) 

这种方法能否与标准的官方语言结合使用,例如 doc <- read_pptx(); doc <- ph_with(x = doc, value = my_ggplot, location = ph_location_fullsize() ) - 还是说它是一个完整的包装器,只将单个图形呈现为pptx页面? - geotheory
这只是一个包装器,内部使用 officer,因此我的唯一目的是能够轻松导出单个图形,尽管它也允许向现有文件添加额外的图形。 - Tom Wenseleers

3
以下是使用 officer 0.3.11 直接将 ggplot 对象创建并导出为矢量图到 PowerPoint 的方法。关键在于使用 ph_withlocation = ph_location。这样可以设置对象的位置和大小,但要保留 html 标签。

library(ggplot2)
library(dplyr, warn.conflicts = FALSE)
library(officer)
library(rvg)

t <- "example.pptx"

fig_gg <- ggplot(mtcars, aes(x=wt, y=mpg)) +
  geom_point()

fig_vg <- dml(ggobj = fig_gg)

read_pptx() %>% 
  add_slide(layout = "Title Only", master = "Office Theme") %>% 
  ph_with(fig_vg, location = ph_location(left = .5, top = 1.3, height = 5, width = 5)) %>% 
  print(t)

本文创建于2020年6月12日,使用了reprex软件包(v0.3.0)


除非我弄错了,这并不改变图表的大小(分辨率),而是规定其在页面上的边框。它不能控制文本和页边距的渲染大小。 - geotheory
@geotheory 在我的例子中,更改 widthheight 的规格确实会改变 PowerPoint 中图形的大小。矢量图像本身没有分辨率(与光栅/位图图像相比)。文本和边距的大小由 ggplot 调用内部控制,例如 fig_gg + theme(text = element_text(size=20)) - JWilliman
在ggplot中正确完成所有这些细节非常繁琐。您需要一种重新缩放最终图的方法。 - geotheory
抱歉,我并不想听起来批评。我只是讨厌要在主题上瞎折腾! - geotheory
1
好的,你可以使用 theme(base_size = 20) 参数来调整所有文本的相对大小。更多信息请参见 https://community.rstudio.com/t/ggplot-theme-with-larger-font-sizes/30084。 - JWilliman
显示剩余3条评论

3

我曾经成功地将ggplot2图表首先保存为.png文件,然后将该文件调用到ph_with_img中。这有点绕,但是它能够工作。你也可以将图表保存为?tempfile,然后使用?unlink删除,但我更喜欢拥有一个存放我的图表的文件夹。

ggplot() +
  (code for my ggplot)

ggsave("../thisplot.png", width = 6, height = 4)

read_pptx() %>% 
  add_slide(layout = "Title and Content", master = "Office Theme") %>% 
  ph_with_img(src = "../thisplot.png", width = 6, height = 4, type = "body") %>% 
  print(target = t)

1
这种解决方案的缺点是输出为位图而不是矢量图形......我在下面发布了另一个答案,保留矢量格式... - Tom Wenseleers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接