R语言学习笔记 -- ggplot2 绘图指定字体大小与线宽

期刊投稿时一般对 figure 的字体大小 (font size) 和线宽 (line width) 有特定的要求,e.g., "Size any text in your figure to at least 6–8 points", "graph lines at least 0.25 points wide"。这里的 point(pt)翻译为点,也音译磅因、磅,是印刷所使用的长度单位。1 点的标准并不统一,当代最通行的是广泛应用于桌面排版软件的 DTP 点,1 inch = 72.27 point = 25.4 mm (维基百科)。
然而,ggplot2 中的 pt unit 与 exact pt 是不同的,需要换算。在 ggplot2 中有专门针对 fontsize 的 graphical unitsggplot2::.pt,它被定义为 72.27/25.4 = 2.845276,详见 geom-.r 第165行。
ggplot2::.pt
[1] 2.845276
对于线宽则又是另一种换算,1 inch = 72.27 point = 96 pixel。原文表述为 you need to multiply the resulting value by 72.27/96 to convert from R pixels to points。然而我无法理解这样做的原因。Anyway,达到目的就行。
ggplot2::.pt*72.27/96
[1] 2.141959
下面示例生成基本字体大小20磅,基本线宽3磅的图形。另有代码对应在图中生成10磅的文字以及宽度4磅的线段。
library(ggplot2); 
str(iris)      
lwd_pt <- .pt*72.27/96
theme_set(theme_bw(base_size = 20, base_line_size = 3/lwd_pt, base_rect_size = 3/lwd_pt))
                
ggplot(iris, aes(Species, Sepal.Length, fill = Species)) +
  geom_boxplot() +
  geom_hline(aes(yintercept = 4), color = "blue", size = 4/lwd_pt) +
  geom_text(x = 1, y = 7, label = "fontsize = 10",  size = 10/.pt) +
  labs(title = "data = iris") 
# ggsave(filename = "./pt.pdf",  width = 6, height = 4)
# 保存为pdf后可在 Adobe illustrator 中确定与设定的尺寸一致。
仔细检查会发现字体大小中坐标轴标题和 legend title 是20磅,图片标题是24磅,坐标轴刻度及 legend text 是16磅;主网格线线宽是3磅,而次网格线线宽是1.5磅。这是因为 ggplot2 默认主题的设置函数theme_bw()的预设代码所致。如需更改,修改自定义theme相应rel即可。
function (base_size = 12, base_family = "")
      {
          theme(axis.text   = element_text(size = rel(0.8)), 
                strip.text  = element_text(size = rel(0.8)),
                legend.text = element_text(size = rel(0.8)),
                plot.title  = element_text(size = rel(1.2)),
                panel.grid.minor = element_line(size = rel(0.5)))
      }
# 此处仅显示部分源代码

你可能感兴趣的:(R语言学习笔记 -- ggplot2 绘图指定字体大小与线宽)