Changing fonts in ggplot2

前端 未结 5 1353
盖世英雄少女心
盖世英雄少女心 2020-11-22 12:59

Once upon a time, I changed my ggplot2 font using using windowsFonts(Times=windowsFont(\"TT Times New Roman\")) to change it. Now I can\'t get it

5条回答
  •  难免孤独
    2020-11-22 13:28

    You just missed an initialization step I think.

    You can see what fonts you have available with the command windowsFonts(). For example mine looks like this when I started looking at this:

    > windowsFonts()
    $serif
    [1] "TT Times New Roman"
    
    $sans
    [1] "TT Arial"
    
    $mono
    [1] "TT Courier New"
    

    After intalling the package extraFont and running font_import like this (it took like 5 minutes):

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

    I had many more available - arguable too many, certainly too many to list here.

    Then I tried your 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)
    

    yielding this:

    Update:

    You can find the name of a font you need for the family parameter of element_text with the following code snippet:

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

    And then:

    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)
    

    yields:

提交回复
热议问题