Graphic Theme for AI/PPT

用ggplot2绘图,调整图片主题是一项大工程。代码绘图不如可视化绘图(如GraphPad Prism)直观,可以自制一些常用theme,提高可复用性。

例如,将图片中所有的线条元素(如坐标轴、折线等)设置为0.5 pt,坐标轴tick设置为0.3 mm,坐标轴标签设置为6 pt,坐标轴标题设置为7 pt,删去图片标题和图例,封装为如下函数。

my_theme <- function() {
  linewidth_pt <- 0.235  # ≈ 0.5 pt ≈ 0.1764 mm, 1 pt = 1/72 inch ≈ 25.4/72 mm
  tick_length_mm <- grid::unit(0.3, "mm")
  
  ggprism::theme_prism(base_size = 6) +
    ggplot2::theme(
      axis.title = ggplot2::element_text(size = 7),
      axis.text = ggplot2::element_text(size = 6),
      legend.position = "none",
      plot.title = ggplot2::element_blank(),
      axis.line = ggplot2::element_line(linewidth = linewidth_pt),
      axis.ticks = ggplot2::element_line(linewidth = linewidth_pt),
      axis.ticks.length = tick_length_mm
    )
}

在实际应用中,图片排版常用170mm宽画布,如果每行排4个panel,那么每个panel宽度在40mm左右。如果保持坐标轴长宽比为4:3(非整个panel的长宽比),则单个panel可以设置为42.5 mm宽,35 mm高的pdf文件,dpi为300。

my_save <- function(plot = NULL,
                    filename,
                    width_grid = 1,
                    height_grid = 1,
                    dpi = 300) {
  base_width_mm <- 42.5
  base_height_mm <- 35
  
  if (is.null(plot)) {
    plot <- ggplot2::last_plot()
  }
  
  ggplot2::ggsave(
    filename = filename,
    plot = plot,
    width = width_grid * base_width_mm,
    height = height_grid * base_height_mm,
    units = "mm",
    dpi = dpi
  )
}

实际使用中,绘制好图片之后,先用my_theme更改图片主题,再用my_save保存为pdf。

p <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot()

p + my_theme()

my_save(filename = '_.pdf')