ggplot2优雅的给线条添加置信区间

2022-09-21 15:43:17 浏览数 (2)

❝本节来介绍如何使用「geom_ribbon」给线条来添加置信区间并使用代码将其导出到PPT中,下面通过一个小例子来进行展示 ❞

安装并加载R包

代码语言:javascript复制
devtools::install_github("davidgohel/officer")
install.packages("flextable")

library(tidyverse)
library(officer)
library(flextable)
library(lubridate)

数据可视化

代码语言:javascript复制
plot <- read_tsv("data.xls") %>% ggplot(aes(x = date, y=moving_pck)) 
  geom_ribbon(aes(ymin=moving_pck -(moving_rmd/2),ymax=moving_pck  (moving_rmd/2)), color='steelblue4', alpha=0.5, fill='steelblue4', linetype='blank') 
  geom_ribbon(aes(ymin=moving_pck -(moving_rnw/2), ymax=moving_pck  (moving_rnw/2)), color='firebrick2', alpha=0.5, fill='firebrick2', linetype='blank') 
  geom_line(color='grey20') 
  theme_test() 
  theme(
    panel.background = element_rect(fill = "grey98"),
    plot.background = element_rect(fill = "grey98"),
    panel.grid.major.x =element_blank(),
    axis.line.x = element_line(color = "black"),
    axis.text = element_text(size=9, color="black"),
    axis.title.y =element_blank(),
    axis.title.x = element_blank(),
    axis.line.y = element_line(color = "black"),
    axis.ticks.x = element_blank()) 
  scale_x_date(breaks=scales::pretty_breaks(n=10)) 
  scale_y_continuous(breaks = scales::pretty_breaks(n=9)) 
  geom_rect(xmin =-Inf, ymax =Inf,xmax= as.Date("2011-9-01"),
            ymin = 540,alpha = 0.1, fill="white",color="black") 
  geom_rect(xmin= as.Date("2009-7-01"), ymax = 600, xmax = as.Date("2009-12-01"),
            ymin=580, color="steelblue4", fill = "steelblue4") 
  geom_text(x = as.Date("2010-2-05"), y=590, label="Markdown vignettes",
            size=3, hjust=0, vjust=0.5, color="steelblue4") 
  geom_rect(xmin= as.Date("2009-7-01"), ymax = 570, xmax = as.Date("2009-12-01"),
            ymin=550, color="#b96d76",fill="#b96d76") 
  geom_text(x = as.Date("2010-2-05"), y=560,label="Sweave vignettes",
            size=3, hjust=0, vjust=0.5, color="#b96d76")

将图片导入PPT

代码语言:javascript复制
ppt <- read_pptx() %>% add_slide() %>% 
  ph_with(.,value=plot,location = ph_location(left=.2,top = 1.5,right=0,
                                              width=9.5,height=5)) %>% 
  ph_with(.,value = format(Sys.Date()),location = ph_location_type(type = "dt"))

print(ppt,target = "20220807.pptx") 

❝本节介绍到此结束,其实小编主要想介绍的是如何使用「officer」包将图片导出PPT

0 人点赞