R语言输出ppt可编辑的图片

ggplot2程序包的加持下,R语言可以做出非常漂亮的统计图出来。然而大家是否会有这样的体会,为了做出理想的图片,需要不停的调整作图的参数,包括颜色,字体大小,字体格式,注释的位置,非常麻烦。尤其是与别人进行科研合作,图片的绘制需要不停地进行沟通,甚至需要动用PS,GIMP等工具。

大家有没有想过可以像下面的动图展示的那样,可以对图片的任意元素进行修改呢???

本文给大家介绍一种解决方案,可以将R语言绘制的图片以元数据(点,线,面,颜色,形状等等)的方式保存到PPT文件中,在PPT中进行修改。

image

软件包

  • officer程序包:一个从R端访问和编辑word和PPT文件的程序包。
  • rvg程序包:一个为PPT和Excel生成矢量图的程序包。

两款程序包,均可以从CRAN进行安装,安装命名如下:

install.packages(c('officier', 'rvg'))

实现方法

  1. R图格式转换
    通过rvg中的dml函数进行转换,可以将R生成两类图,Graphics和ggplot图,转换成PPT可以直接导入的格式。
  • Graphics图: 首先找一段生成决策曲线的代码
data(dcaData)
set.seed(123)
baseline.model <- decision_curve(Cancer~Age + Female + Smokes,
                                data = dcaData,
                                thresholds = seq(0, .4, by = .005),
                                bootstraps = 10)
full.model <- decision_curve(Cancer~Age + Female + Smokes + Marker1 + Marker2,
                            data = dcaData,
                            thresholds = seq(0, .4, by = .005),
                            bootstraps = 10)

plot_decision_curve( list(baseline.model, full.model),
                    curve.names = c("Baseline model", "Full model"),
                    col = c("blue", "red"),
                    lty = c(1,2),
                    lwd = c(3,2, 2, 1),
                    legend.position = "bottomright")

最后的代码段是作图的命令,我们只需要将最后一段进行如下操作,即将其赋值给dml函数的code参数。

p.dca <- dml(code = {
  plot_decision_curve( list(baseline.model, full.model),
                    curve.names = c("Baseline model", "Full model"),
                    col = c("blue", "red"),
                    lty = c(1,2),
                    lwd = c(3,2, 2, 1),
                    legend.position = "bottomright")
})

  • ggplot图:同样找一段生成频数分布对比柱状图的代码:
ggbarstats(
  data = mtcars,
  x = vs,
  y = cyl
)

对该作图代码做如下修改,将它赋值给dml函数中的ggobj参数:

p.bar <- dml(ggobj = {
  ggbarstats(
  data = mtcars,
  x = vs,
  y = cyl
)
})

  1. 导入PPT
    使用officier包将前面生成p.dcap.bar输出到PPT中。会用到以下函数:
  2. 打开PPT--read_pptx
  3. 添加页面--add_slide
  4. 导入图片--ph_with
  5. 保存PPT--print
    具体操作如下:
pptx <- read_pptx()
pptx <- add_slide(pptx)
ph_with(pptx, value = p.dca, 
        location = ph_location_type(type = 'body'))

pptx <- add_slide(pptx)
ph_with(pptx, value = p.bar, 
        location = ph_location_fullsize())

print(pptx, 'output.pptx')

作者:小蜜蜂Stats
链接:https://www.jianshu.com/p/8f2d4a92214c

你可能感兴趣的:(R语言输出ppt可编辑的图片)