【问题标题】:Changing fonts in ggplot2更改 ggplot2 中的字体
【发布时间】:2015-12-30 04:02:42
【问题描述】:

曾几何时,我使用windowsFonts(Times=windowsFont("TT Times New Roman")) 更改了我的ggplot2 字体。现在,我无法摆脱它。

在尝试在ggplot2 theme() 中设置family="" 时,我似乎无法生成字体更改,因为我用不同的字体系列编译下面的MWE。

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
        ggtitle("Fuel Efficiency of 32 Cars") +
        xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
        theme(text=element_text(size=16, 
#       family="Comic Sans MS"))
#       family="CM Roman"))
#       family="TT Times New Roman"))
#       family="Sans"))
        family="Serif"))


print(a)
print("Graph should have refreshed")

R 返回警告font family not found in Windows font database,但我正在关注一个教程(如果我能再次找到它,我将在此处更新链接)说这是正常的,不是问题。此外,不知何故,这在某一时刻起作用,因为我的图表曾经使用过一些 arial 或 helvitica 字体。我认为即使在最初的迁移期间,这也一直是一个当前的警告。

更新

当我运行 windowsFonts() 时,我的输出是

$serif [1] "TT Times New Roman"

$sans [1] "TT Arial"

$mono [1] "TT Courier New"

但是,这是在我运行font_import() 之后,所以我只能得出结论,我的字体没有保存在正确的位置。运行font_import() 请求的代码实际上加载了库:

LocalLibraryLocation <- paste0("C:\\Users\\",Sys.getenv("USERNAME"),"\\Documents","\\R\\win-library\\3.2");
    .libPaths(c(LocalLibraryLocation, .libPaths()))

【问题讨论】:

标签: r ggplot2 fonts extrafont showtext


【解决方案1】:

我认为你只是错过了一个初始化步骤。

您可以使用命令windowsFonts() 查看可用的字体。例如,当我开始看这个时,我的看起来是这样的:

> windowsFonts()
$serif
[1] "TT Times New Roman"

$sans
[1] "TT Arial"

$mono
[1] "TT Courier New"

在安装包 extraFont 并像这样运行font_import 之后(大约需要 5 分钟):

library(extrafont)
font_import()
loadfonts(device = "win")

我还有更多可用的 - 有争议的太多了,当然太多了,无法在此处列出。

然后我尝试了您的代码:

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text=element_text(size=16,  family="Comic Sans MS"))
print(a)

产生这个:

更新:

element_textfamily参数可以找到你需要的字体名称,代码如下:sn-p:

> names(wf[wf=="TT Times New Roman"])
[1] "serif"

然后:

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text=element_text(size=16,  family="serif"))
print(a)

收益:

【讨论】:

  • 感谢您的帮助,已经完成了一半。我现在可以在mono||sans(到目前为止看起来没有什么不同)和serif``, but not the actually name like "TT Times New Roman", but additionally, I not sure that my loadFonts` 之间切换成功。当我打电话给fonts() 时,我有一个近 300 种字体的列表,但我猜它们没有安装到本地环境中,因此 Windows 设备可以访问它们。我不确定这是否有意义,但我尝试使用可能有帮助的 sn-ps 提供对我最初问题的更新。再次感谢!
  • 感谢名称 sn-p 更新,它看起来很有帮助,如果家庭是我的安装识别的唯一字符串,您的漫画 sans 示例如何产生正确的外观。
  • 运气。在该字体(以及许多其他字体)中,姓氏与姓氏值相同。所以wf[which(wf=="Comic Sans MS")] 产生$``Comic Sans MS`` [1] "Comic Sans MS"
  • 谢谢,您知道是否可以从特定位置直接或加载字体? IE。即使是安装加载字体或指定字体?重复摘要显示调用时,我没有获得额外的窗口可见字体...
  • 由于没有管理员访问权限,这是否有可能无法在工作笔记本电脑上运行?我正在运行上述过程,但它对我不起作用......我上一份工作有一台 MacBook,这从来都不是问题,它只是在 Mac 上工作......想法?
【解决方案2】:

另一种选择是使用showtext 包,它支持更多类型的字体(TrueType、OpenType、Type 1、Web 字体等)和更多图形设备,避免使用 Ghostscript 等外部软件。

# install.packages('showtext', dependencies = TRUE)
library(showtext)

导入一些 Google 字体

# https://fonts.google.com/featured/Superfamilies
font_add_google("Montserrat", "Montserrat")
font_add_google("Roboto", "Roboto")

从当前搜索路径加载字体到showtext

# Check the current search path for fonts
font_paths()    
#> [1] "C:\\Windows\\Fonts"

# List available font files in the search path
font_files()    
#>   [1] "AcadEref.ttf"                                
#>   [2] "AGENCYB.TTF"                           
#> [428] "pala.ttf"                                    
#> [429] "palab.ttf"                                   
#> [430] "palabi.ttf"                                  
#> [431] "palai.ttf"

# syntax: font_add(family = "<family_name>", regular = "/path/to/font/file")
font_add("Palatino", "pala.ttf")

font_families()
#> [1] "sans"         "serif"        "mono"         "wqy-microhei"
#> [5] "Montserrat"   "Roboto"       "Palatino"

## automatically use showtext for new devices
showtext_auto() 

剧情:需要打开 Windows 图形设备,因为showtext 不能很好地与 RStudio 内置图形设备配合使用

# https://github.com/yixuan/showtext/issues/7
# https://journal.r-project.org/archive/2015-1/qiu.pdf
# `x11()` on Linux, or `quartz()` on Mac OS
windows()

myFont1 <- "Montserrat"
myFont2 <- "Roboto"
myFont3 <- "Palatino"

library(ggplot2)

a <- ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text = element_text(size = 16, family = myFont1)) +
  annotate("text", 4, 30, label = 'Palatino Linotype',
           family = myFont3, size = 10) +
  annotate("text", 1, 11, label = 'Roboto', hjust = 0,
           family = myFont2, size = 10) 

## On-screen device
print(a) 

## Save to PNG 
ggsave("plot_showtext.png", plot = a, 
       type = 'cairo',
       width = 6, height = 6, dpi = 150)  

## Save to PDF
ggsave("plot_showtext.pdf", plot = a, 
       device = cairo_pdf,
       width = 6, height = 6, dpi = 150)  

## turn showtext off if no longer needed
showtext_auto(FALSE) 

编辑:在 RStudio 中使用 showtext 的另一种解决方法。在 R 会话开始时运行以下代码 (source)

trace(grDevices::png, exit = quote({
    showtext::showtext_begin()
}), print = FALSE)

编辑 2Starting from version 0.9, showtext can work well with the RStudio graphics device (RStudioGD). Simply call showtext_auto() in the RStudio session and then the plots will be displayed correctly.

【讨论】:

  • 谢谢,我期待尝试一下!
  • 谢谢你一千次......这个包让你非常容易 a) 通过 font_families() 验证你有哪些字体系列可用于 ggplot - b) 通过 font_files( ) - c) 通过 font_add(family, font_file_name) 将字体文件添加为字体系列。太棒了!!!
  • @AgileBean:很高兴我能帮上忙 :)
  • 重要:您必须先从xquartz.org 安装XQuartz 包,否则在尝试加载库时会收到无法描述的错误。
  • 这个解决方案对我不起作用。我仍然在窗口和 Rstudio 的绘图窗口中获得默认字体。
【解决方案3】:

如果您不想安装任何新东西,一个简单的答案

更改绘图中的所有字体plot + theme(text=element_text(family="mono")) 其中mono 是您选择的字体。

默认字体选项列表:

  • 单声道
  • 没有
  • 衬线
  • 快递
  • Helvetica
  • 时代
  • 前卫
  • 图书管理员
  • Helvetica-窄
  • 新世纪教科书
  • 帕拉蒂诺
  • URWGothic
  • URWBookman
  • NimbusMon
  • URWHelvetica
  • NimbusSan
  • NimbusSanCond
  • 世纪学院
  • URWPalladio
  • URWTimes
  • NimbusRom

R 没有很好的字体覆盖率,正如Mike Wise 指出的那样,R 对常见字体使用不同的名称。

This page 详细检查默认字体。

【讨论】:

  • 出于某种原因,如果family="mono"sans 这对我有用。但是,不适用于HelveticaHelvetica-Narrow。在这里,我收到了经典警告grid.Call.graphics(C_text, as.graphicsAnnot(x$label), ... : font family not found in Windows font database。我还没有添加任何其他库,例如library(extrafont) loadfonts(device = "win")。这会是个问题吗?谢谢!
【解决方案4】:

聚会迟到了,但对于希望在 shinyapps.io 上的 shiny 应用程序中为 ggplots 添加自定义字体的人来说,这可能会感兴趣。

你可以:

  1. 将自定义字体放在www 目录中:例如IndieFlower.ttf 来自here
  2. 按照here 的步骤进行操作

这导致app.R 文件中的以下上部:

dir.create('~/.fonts')
file.copy("www/IndieFlower.ttf", "~/.fonts")
system('fc-cache -f ~/.fonts')

可以在here找到完整的示例应用程序。

【讨论】:

    【解决方案5】:

    全局更改 ggplot2 绘图的字体。

    theme_set(theme_gray(base_size = 20, base_family = 'Font Name' ))
    

    【讨论】:

      猜你喜欢
      • 2016-04-10
      • 2011-05-04
      • 2013-12-28
      • 2012-08-10
      • 2019-06-05
      • 2021-03-19
      • 2017-05-23
      • 2012-10-29
      • 2019-05-02
      相关资源
      最近更新 更多