在office中保存为docx时,ggplot的轴标签被剪切

问题描述 投票:0回答:1

请参阅下面的代码。 我的文档中的区域有限,需要剪切宽度。 缩放适用于所有元素(图表、标题、文本等)。 但是当我添加一些自定义标签时,它们会被 ggsave 自动剪切。 缩放参数默认设置为 1。

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")

结果

我尝试调整边距和填充。没有成功。

r ggplot2 officer
1个回答
0
投票

我认为设置

plot.margin
会起作用:

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")

© www.soinside.com 2019 - 2024. All rights reserved.