rggplot2officer

Axis labels of ggplot are cut when saved in officer as docx


See below the code. I have a limited area in my document and need to cut the width. Scaling works just fine for all elements (chart, titles, texts etc.). But when I add a few custom labels, they are cut automatically by ggsave. The scaling argument is set to 1 by default.

my_doc <- officer::read_docx()

# Dummy data
data <- data.frame(
  day = as.Date("2017-06-14") - 0:364,
  value = runif(365) + seq(-140, 224)^2 / 10000)

p <- ggplot(data, aes(x=day, y=value)) +
  geom_line() + 
  xlab("") + 
  scale_x_date(
    date_labels = "%b %Y") + 
  scale_y_continuous(
    position = "right") + 
  theme(axis.text.x=element_text(angle=30, hjust=1,vjust= 1,
                                 color = 'black'))
p

my_doc <- body_add_gg(my_doc, value = p, width = 2.3, height = 2.8, res = 1200)

my_doc %>% print(target = "doc.docx")

As result

enter image description here

I tried to adjust margins, and paddings. No success.


Solution

  • I think setting plot.margin will work:

    library(ggplot2)
    library(officer)
    
    p <- ggplot(data, aes(x=day, y=value)) +
      geom_line() + 
      xlab("") + 
      scale_x_date(
        date_labels = "%b %Y") + 
      scale_y_continuous(
        position = "right") +
      theme(axis.text.x=element_text(angle=30, hjust=1,vjust= 1,
                                     color = 'black'),
            plot.margin = unit(c(0, 0, 0, 1), "cm")) ## add this in theme
    
    my_doc <- body_add_gg(my_doc, value = p, width = 2.3, height = 2.8, res = 1200)
    
    my_doc %>% print(target = "doc.docx")
    

    word_screenshot

    Or using the scale parameter to make the scale smaller if you don't might the sizes of the plot elements:

    p <- ggplot(data, aes(x=day, y=value)) +
      geom_line() + 
      xlab("") + 
      scale_x_date(
        date_labels = "%b %Y") + 
      scale_y_continuous(
        position = "right") +
      theme(axis.text.x=element_text(angle=30, hjust=1,vjust= 1,
                                     color = 'black'))
    
    my_doc <- body_add_gg(my_doc, value = p, width = 2.3, height = 2.8, res = 1200, scale = 0.5) # scale here
    
    my_doc %>% print(target = "doc.docx")
    

    word_screenshot2