Modification des polices de caractères dans ggplot2

il était une fois, j'ai changé mon ggplot2 font en utilisant windowsFonts(Times=windowsFont("TT Times New Roman")) pour le changer. Maintenant, je ne peux pas le faire hors de ce.

En essayant de définir family=""ggplot2 theme() je n'arrive pas à générer un changement dans les polices que je compile les MWE ci-dessous avec les différentes familles de polices de caractères.

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 renvoie un avertissement font family not found in Windows font database, mais il y avait un tutoriel que je suivais (si je peux le retrouver je mettrai à jour le lien ici) qui disait que c'était normal et pas un problème. Aussi, d'une certaine façon cela a fonctionné à un point parce que mon graphe une fois utilisé une police de type arial ou helvitica. Je pense que cela a toujours été un avertissement présent, même pendant la période de migration initiale.

UPDATE

quand je lance windowsFonts() ma sortie est

$ serif [1]"TT Times New Roman"

$ sans [1]"TT Arial"

$mono [1]"TT Courier New"

Mais, c'est après que j'ai couru font_import() pour que je puisse seulement conclure que mes polices ne sont pas sauvegardées au bon endroit. Le code qui a couru le font_import() request charge en fait les bibliothèques avec:

LocalLibraryLocation <- paste0("C:Users",Sys.getenv("USERNAME"),"Documents","Rwin-library3.2");
    .libPaths(c(LocalLibraryLocation, .libPaths()))
25
demandé sur Tung 2015-12-30 07:02:42

2 réponses

vous venez de rater une étape d'initialisation je pense.

vous pouvez voir quelles polices vous avez disponibles avec la commande windowsFonts(). Par exemple le mien ressemble à ça quand j'ai commencé à regarder ceci:

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

$sans
[1] "TT Arial"

$mono
[1] "TT Courier New"

après l'introduction du paquet extraFont et l'exécution font_import comme ceci (il a fallu que 5 minutes):

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

j'en avais beaucoup d'autres disponibles - discutables trop nombreux, certainement trop nombreux à énumérer ici.

puis j'ai essayé votre code:

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)

rendement:

enter image description here

mise à Jour:

Vous pouvez trouver le nom d'une police dont vous avez besoin pour l' family paramètre element_text avec le code suivant:

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

puis:

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)

les rendements: enter image description here

49
répondu Mike Wise 2015-12-30 15:32:07

une Autre option est d'utiliser showtext paquet qui supporte plus de types de polices (TrueType, OpenType, Type 1, web fonts, etc.) et plus de dispositifs graphiques, et évite d'utiliser des logiciels externes tels que Ghostscript.

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

importer quelques polices Google

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

chargez la police du chemin de recherche actuel dans 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() 

parcelle: besoin d'ouvrir Windows graphics device comme showtext ne fonctionne pas bien avec RStudio intégré périphérique graphique

# https://github.com/yixuan/showtext/issues/7
# https://journal.r-project.org/archive/2015-1/qiu.pdf
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) 
4
répondu Tung 2018-09-24 04:14:06