是否有更好的解决方法将透明的 ggplots 从 Rstudio 导出到 PowerPoint?

Is there a better workaround for exporting transparent ggplots from Rstudio to PowerPoint?

所以我需要将我在 R/Rstudio 中制作的绘图复制并粘贴到 PowerPoint(不幸的是,我的政府客户要求所有内容都在 PowerPoint 中,否则只需将我的图形放入 Rmarkdown 中即可轻松解决这个问题文件)。这并不是什么大问题,直到最近我发现透明对象无法复制并粘贴到 PowerPoint 中,至少在我一直使用的方法中是这样(导出 > 复制为图元文件 > 复制图 > 粘贴) .相反,透明物体所在的位置现在什么都没有了。我读了一些书,发现这与我的 "graphics engine" 不支持透明对象有关,而 "cairo" 引擎可以,但我不明白这意味着什么,或者如果它是我可以更改的选项在 Rstudio 或 PowerPoint 中。

下面是一些示例代码:

iris %>%
mutate(small_petal = if_else(Petal.Width > 1.5, "big", "small")) %>%
ggplot(aes(x = Sepal.Length, y = Sepal.Width, color = Species, alpha = small_petal)) +
geom_point()

我尝试了一种非常奢侈的解决方法来获得我想要的颜色。我制作了不透明的自定义 RGB 值以模仿我想要的透明度。然后,我使用带有四个 if_elsemutate 将它们附加到 data.frame(每个 alpha 颜色组合一种颜色)。然后我使用 scale_fill_identity 来应用我的自定义颜色,但它随后会生成一个包含我不想要的元素的图例。我需要使用以下方法使图例至少包含我想要的一些元素:

scale_fill_identity(guide = "legend",
                    labels = c("DUMMY LABEL",
                               "DUMMY LABEL",
                               "Small Petal",
                               "Big Petal"),
                    breaks = unique(iris$custom_colors))

然后我删除了 PowerPoint 中不需要的图例对象。非常感谢任何帮助。

您是否尝试过从 RMarkdown 直接渲染到 PowerPoint?添加了该功能 pretty recently 您必须安装 RMarkdown 和 RStudio 的开发版本才能获得它。前面的说明 link,但是 tldr;如下:

  1. 最新降价:devtools::install_github("rstudio/rmarkdown")
  2. 安装最新的 RStudio 预览版:https://www.rstudio.com/products/rstudio/download/preview/

当我在 Mac 上尝试时,我认为输出看起来很不错:

我的 RMarkdown 测试如下:

---
title: "testing ppt"
author: "JD Long"
date: "8/3/2018"
output: powerpoint_presentation
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

## Test chunk

```{r iris, echo = TRUE}
library(tidyverse)
iris %>%
  mutate(small_petal = if_else(Petal.Width > 1.5, "big", "small")) %>%
  ggplot(aes(x = Sepal.Length, y = Sepal.Width, color = Species, alpha = small_petal)) +
  geom_point()
```

像@JD Long 提到的那样直接渲染可能是可行的方法,但作为替代方案,开罗可能会奏效:

p = iris %>%
  mutate(small_petal = if_else(Petal.Width > 1.5, "big", "small")) %>%
  ggplot(aes(x = Sepal.Length, y = Sepal.Width, color = Species, alpha = small_petal)) +
  geom_point() +
  theme_bw()   

ggsave(p, filename = "a.png", type = "cairo")

我还添加了theme_bw(),透明度在白色背景上看起来更好

如果您想将 R 图表导出到 Powerpoint,您还可以使用刚刚在 CRAN 上发布的 officer 之上构建的包装程序包 export,请参阅 https://cran.r-project.org/web/packages/export/index.html 和演示 https://github.com/tomwenseleers/export

典型语法非常简单,输出为原生 Powerpoint 矢量格式,完全支持半透明:

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="ggplot2_plot.pptx", width=6, height=5) 

您还可以使用它导出到 Word、Excel、Latex 或 HTML,您还可以使用它导出各种 R 统计对象的统计输出。