在我的研究中,我使用 R 生成各种图形。我发现大多数图形都采用不同大小的 Sans Serif 字体。
我该如何将图形中所有文本(x 标签、y 标签、标题、图例等)更改为统一的字体,例如 Times New Roman,12pt,加粗?
install.packages("extrafont")
library(extrafont)
font_import()
loadfonts(device="win") #Register fonts for Windows bitmap output
fonts() #vector of font family names
## [1] "Andale Mono" "AppleMyungjo"
## [3] "Arial Black" "Arial"
## [5] "Arial Narrow" "Arial Rounded MT Bold"
library(ggplot2)
data(mtcars)
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme_bw() +
theme(text=element_text(family="Times New Roman", face="bold", size=12)) #Times New Roman, 12pt, Bold
#example taken from the Github project page
注意:使用extrafont
包,您还可以嵌入PDF和EPS文件中的这些字体(在R中制作图形并导出为PDF / EPS)。 您还可以直接创建数学符号(请参见下面绘图中的数学方程),通常使用TeX创建。 更多信息在这里和在这里。 还要查看GitHub项目页面。
还可以查看此答案,其中描述了如何使用extrafont
包创建xkcd样式的图形。
您可以使用 windowsFonts()
命令和 plot
中的 family
选项在 Windows 中更改字体为 Times New Roman:
x = seq(1,10,1)
y = 1.5*x
windowsFonts(A = windowsFont("Times New Roman"))
plot(x, y,
family="A",
main = "title",
font=2)
粗体文本 来自于 font=2
。至于大小,参见 ?cex()
。另外,请参见这里:http://www.statmethods.net/advgraphs/parameters.html
WindowsFonts(...)
的ggplot
解决方案。windowsFonts(Times=windowsFont("Times New Roman"))
library(ggplot2)
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme_bw() +
theme(text=element_text(family="Times", face="bold", size=12)) #Times New Roman, 12pt, Bold
正如您所见,这段文字确实是使用的 Times New Roman 字体。
主要的想法是,无论您在 R 中内部给字体起什么名称,只要在您的计算机上安装了该字体,它就会被正确地呈现出来。因此,如果您的同事或合作者在其计算机上没有安装该字体,则可能需要选择另一种字体。
windowsFonts(name=windowsFont("system name"))
你应该使用引用字体的方式
theme(text=element_text(family="name",...),...)
2020年更新
现在可以通过使用ggtext
软件包来解决此问题,例如:
install.packages(ggtext)
plot <- plot + theme(
legend.text = ggtext::element_markdown(family = 'Times', face='bold')
)
此外,您可以使用Markdown来补充您的图表文本。我的经验是使用ggtext
比extrafont
更简单且更安全。
text = ggtext::element_markdown(family = 'Times')
会产生错误信息!主题元素
text具有没有默认值的“NULL”属性:fill、box.colour、linetype、linewidth、halign、valign、padding、r、align_widths、align_heights和rotate_margins
。 - undefined