如何防止绘图轴标签被pdf导出器裁剪

时间:2019-01-21 17:24:37

标签: r pdf ggplot2

我正在尝试生成一个图,该图的x轴刻度线字符串相对较长。为了使它们更具可读性,已将对角线定位在对角线上。当我将图导出为pdf时会出现问题。最左侧的x轴刻度在生成的pdf中被部分裁剪:

enter image description here

如何防止这种情况发生?

以下代码:

require(ggplot2)

# dataframe
df <- structure(list(month = structure(1:12, .Label = c("Jan 2018 to Dec 2018", 
    "Dec 2017 to Nov 2018", "Nov 2017 to Oct 2018", "Oct 2017 to Sep 2018", 
    "Sep 2017 to Aug 2018", "Aug 2017 to Jul 2018", "Jul 2017 to Jun 2018", 
    "Jun 2017 to May 2018", "May 2017 to Apr 2018", "Apr 2017 to Mar 2018", 
    "Mar 2017 to Feb 2018", "Feb 2017 to Jan 2018"), class = "factor"), 
    foo = c(8351999.07887727, 6755934.13878232, 6707439.054735, 
    5640531.60604089, 4059014.68824595, 7394651.70307085, 9225768.22340488, 
    828450.454864651, 6874948.06712493, 2928892.67439023, 3922518.1308575, 
    5243671.78557441)), row.names = c(NA, -12L), class = "data.frame")

# plot
plot.1 <- ggplot(data = df, aes(x = month, y = foo)) +
  geom_bar(stat = 'identity', fill = 'darkorchid4', width = 0.45) +
  theme_minimal() +
  labs(title = "", x = "", y = "Amount of foo") +
  scale_y_continuous(
    label = scales::unit_format(unit = "M", scale = 1e-6, sep = "")) +
  theme(axis.text.x = element_text(angle = 45, vjust = 1.2, hjust = 1, 
                                   size = 14),
        axis.text.y = element_text(size = 14),
        axis.title.y = element_text(size = 14))

# export to pdf
pdf(file = 'foo_plot.pdf', width = 10, height = 8)
print(plot.1)
dev.off()

1 个答案:

答案 0 :(得分:1)

选项1:

plot.1 + scale_x_discrete(expand = c(0, 1))

选项2:

plot.1 + theme(plot.margin = margin(t = 0, r = 0, b = 0, l = 20, unit = "pt"))

可能还有更多选择。