Search code examples
rggplot2officer

ph_with_vg and ggplot on R


I am able to create my desired chart using ggplot using the following code:

    ggplot(data, aes(x=as.Date(data$Date, "%d/%m/%Y"), y=items)) + geom_col(fill="#00cccc")

However, when i use it with my full code, i get an error that reads "StartTag:invalid element name [68]"

    my_pres<-
      # Load template
      read_pptx("C:/Users/USERNAME/Desktop/template.pptx") %>%
      # 02 - SLIDE
      add_slide(layout="Title with Subtitle and Content", master="MySlides2016") %>%
      # 02 - Title
      ph_with_text(type = "title", str = "Items by Day") %>%
      # 02 - Chart
      ph_with_vg_at(code = ggplot(data, aes(x=as.Date(data$Date, "%d/%m/%Y"), y=items)) + geom_col(fill="#00cccc"),left = 1, top = 2, width = 6, height = 4)

Solution

  • If you read the documentation available here, it says that you have to use print(your_ggplot_object) in function ph_with_vg_at, so you can do :

    library("officer")
    library("rvg")
    library("magrittr")
    library("ggplot2")
    
    gg <- ggplot(mtcars, aes(x = mpg , y = wt, colour = qsec)) + geom_point() + theme_minimal()
    
    my_pres<-
      # Load template
      read_pptx() %>%
      # 02 - SLIDE
      add_slide(layout = "Title and Content", master = "Office Theme") %>%
      # 02 - Title
      ph_with_text(type = "title", str = "Items by Day") %>%
      # 02 - Chart
      ph_with_vg_at(code = print(gg),left = 1, top = 2, width = 6, height = 4)
    
    # Save
    tmp <- tempfile(fileext = ".pptx")
    print(my_pres, target = tmp)
    
    # Open
    browseURL(tmp)