在我的研究中,我使用R生成各种图形.我看到大多数图形都提供了各种大小的Sans Serif类型字体.
如何将图形中的所有文本(x标签,y标签,标题,图例等)更改为统一字体,例如Times New Roman,12pt,Bold?
Ujj*_*wal 33
您可以使用extrafont包.
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
Run Code Online (Sandbox Code Playgroud)

注意:使用该extrafont包,您还可以将这些字体嵌入PDF和EPS文件中(在R中绘制图并导出为PDF/EPS).您也可以直接创建数学符号(请参见下图中的数学公式),通常使用TeX创建.更多信息在这里和这里.另请参阅github项目页面.

另请参阅此答案,该答案描述了使用该包创建xkcd样式图extrafont.

Dev*_*von 14
您可以使用以下windowsFonts()命令和family选项将Windows中的字体更改为Times New Roman plot:
x = seq(1,10,1)
y = 1.5*x
windowsFonts(A = windowsFont("Times New Roman"))
plot(x, y,
family="A",
main = "title",
font=2)
Run Code Online (Sandbox Code Playgroud)
大胆的文字来自font=2.至于大小,请参阅?cex().另请参见此处:http://www.statmethods.net/advgraphs/parameters.html

这是一个ggplot使用的解决方案WindowsFonts(...)
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
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,文本真的是Times New Roman.
主要的想法是,无论你使用什么名称在R内部给出字体
windowsFonts(name=windowsFont("system name"))
Run Code Online (Sandbox Code Playgroud)
你应该用来引用字体
theme(text=element_text(family="name",...),...)
Run Code Online (Sandbox Code Playgroud)
更新 2020
现在可以通过使用该包来解决这个问题ggtext,例如:
install.packages(ggtext)
plot <- plot + theme(
legend.text = ggtext::element_markdown(family = 'Times', face='bold')
)
Run Code Online (Sandbox Code Playgroud)
此外,您可以使用 Markdown 来补充您的情节文本。我经历了ggtext比 更简单、更安全的情况extrafont。