【发布时间】:2015-02-25 15:50:40
【问题描述】:
在我的研究中,我使用 R 生成各种图表。我看到大多数图表都带有各种大小的 Sans Serif 字体。
如何将图表中的所有文本(x 标签、y 标签、标题、图例等)更改为统一字体,例如Times New Roman,12pt,粗体?
【问题讨论】:
-
您使用的是基础绘图还是像 ggplot2 这样的专用绘图包?
在我的研究中,我使用 R 生成各种图表。我看到大多数图表都带有各种大小的 Sans Serif 字体。
如何将图表中的所有文本(x 标签、y 标签、标题、图例等)更改为统一字体,例如Times New Roman,12pt,粗体?
【问题讨论】:
您可以使用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
注意:使用extrafont 包,您还可以将这些字体嵌入到PDF 和EPS 文件中(在R 中绘制并导出为PDF/EPS)。您也可以直接创建数学符号(参见下图中的数学方程式),通常使用 TeX 创建。更多信息here 和here。另请查看github project page。
【讨论】:
您可以使用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')
)
此外,您可以使用降价来补充您的情节文本。我体验过ggtext 比extrafont 更简单、更安全。
【讨论】: