在R中更改图表字体

54

在我的研究中,我使用 R 生成各种图形。我发现大多数图形都采用不同大小的 Sans Serif 字体。

我该如何将图形中所有文本(x 标签、y 标签、标题、图例等)更改为统一的字体,例如 Times New Roman,12pt,加粗?


1
你是使用基本绘图还是像ggplot2这样的专业绘图包? - Serban Tanasa
4个回答

54
你可以使用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创建。 更多信息在这里在这里。 还要查看GitHub项目页面

图片描述

还可以查看此答案,其中描述了如何使用extrafont包创建xkcd样式的图形。

图片描述


23

您可以使用 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

输入图像描述


此解决方案仅适用于Times New Roman字体。我试图使用此解决方案将字体更改为非Times New Roman字体,但无论我输入什么,字体都永远不会变化。如果一个人想要使用除Times New Roman以外的字体,该怎么办? - Jennifer B.
windowsFonts(A = windowsFont("Helvetica")) plot(forecast(fit, 5), xlab ="年份", ylab ="乘客数", main ="嘉年华邮轮:乘客数量(以千为单位)", col.main ="darkgreen", xlim = c(2005, 2025), ylim = c(7000, 16000), family="A", las="0") - Jennifer B.

20
这是一个使用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",...),...)

我认为这个解决方案更好!谢谢 - j_3265

7

2020年更新 现在可以通过使用ggtext软件包来解决此问题,例如:

install.packages(ggtext)

plot <- plot + theme(
  legend.text = ggtext::element_markdown(family = 'Times', face='bold')
)

此外,您可以使用Markdown来补充您的图表文本。我的经验是使用ggtextextrafont更简单且更安全。


这似乎对整个情节来说不起作用,即text = ggtext::element_markdown(family = 'Times')会产生错误信息!主题元素text具有没有默认值的“NULL”属性:fill、box.colour、linetype、linewidth、halign、valign、padding、r、align_widths、align_heights和rotate_margins - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接