在R中的pdf()函数中指定字体后,更改字体类型(例如,粗体)

时间:2019-06-18 15:55:57

标签: r fonts

问题陈述

我正在处理乳胶文档,并使用R的pdf()函数创建绘图。为了匹配文档的字体,我在pdf函数中指定了字体系列:pdf(family = "LM Roman 12")。但是,在图形(森林图)中,我使用par(font = ..)更改为粗体字体以突出显示标题。不幸的是,由于我已经在pdf()中指定了字体系列,因此该功能不再起作用。

示例代码

### Required packages
library(metafor)
library(extrafont)


### My dataset reproduced with: dput()
data.rct.forest <- structure(list(study = c("Fellmeth et al. (2015)", "Gaffney, Ttofi et al. (2019)", 
"Jiménez-Barbero et al. (2016)", "Gaffney, Farrington et al. (2019)", 
"Moy & Hazen (2018)", "Park-Higgerson et al. (2008)"), rct_es = c(1.227, 
1.235, 1.243, 1.333, 0.947, 1.037), rct_es_low = c(0.948, 1.124, 
1.115, 1.087, 0.881, 0.696), rct_es_up = c(1.586, 1.389, 1.361, 
1.669, 1.018, 1.545), quality_score = c(4, 2, 4, 3, 4, 3), group_intervention = c("3_psychosocial: sexual violence", 
"2_psychosocial: bullying", "2_psychosocial: bullying", "2_psychosocial: bullying", 
"1_psychosocial: general violence", "1_psychosocial: general violence"
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-6L), .Names = c("study", "rct_es", "rct_es_low", "rct_es_up", 
"quality_score", "group_intervention"))


### Plotting the forest plot
pdf("plot_forest_rct.pdf", height = 5, width = 8, family = "LM Roman 12")

par(font = 1, cex = 1.1)
forest(x = log(data.rct.forest$rct_es), 
       ci.lb = log(data.rct.forest$rct_es_low), 
       ci.ub = log(data.rct.forest$rct_es_up),
       slab = data.rct.forest$study, xlim = c(-4, 2.5), 
       psize = rep(1, 6), atransf = exp,
       refline = 0, alim = c(log(0.5), log(3)), at = c(log(0.5), log(1), log(2), log(3)),
       row = c(0, 3:5, 8:9), ylim = c(0, 13),
       cex = 1, efac = 0.75, xlab = "Odds ratio (log scale)")

### add text for subgroups
par(font = 4, cex = 1.1) # <--- ADDED TEXT SHOULD BE BOLD
text(-4, c(1, 6, 10), pos = 4, c("Psychosocial interventions: sexual violence",
                                 "Psychosocial interventions: bullying",
                                 "Psychosocial interventions: general violence"))

### add text to header
par(font = 4, cex = 1) # <--- ADDED TEXT SHOULD BE BOLD
text(-4, 12, pos = 4, "Author (year)")
text(2.5, 12, pos = 2, "Odds ratio [95% CI]")

dev.off()

这就是我得到的:

actual state

这是它的外观(字体系列除外):

target state

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

我对字体系列有一些问题,但是将fontcex放在text调用中似乎可以正常工作:

text(-4, c(1, 6, 10), pos = 4, c("Psychosocial interventions: sexual violence",
                                 "Psychosocial interventions: bullying",
                                 "Psychosocial interventions: general violence"), font=4, cex=1.1)
text(-4, 12, pos = 4, "Author (year)", font=4, cex=1.1)
text(2.5, 12, pos = 2, "Odds ratio [95% CI]", font=4, cex=1.1)

这是使用字体家族“ sans”的结果:

enter image description here