【问题标题】:How to prevent plot axis labels from being cropped by pdf exporter如何防止绘图轴标签被pdf导出器裁剪
【发布时间】:2019-01-21 17:24:36
【问题描述】:

我正在尝试生成一个图表,其中包含相对较长的 x 轴刻度字符串。为了使它们更具可读性,刻度线被放置在对角线上。当我将绘图导出为 pdf 时出现问题。最左边的 x 轴刻度在生成的 pdf 中被部分裁剪掉:

如何防止这种情况发生?

代码如下:

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

【问题讨论】:

  • + coor_flip()?
  • 也许可以调整theme(plot.margin = unit(...))

标签: r pdf ggplot2


【解决方案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"))

而且可能还有更多选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 2014-05-13
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多