Asked  6 Months ago    Answers:  5   Viewed   80 times

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 off of this.

In trying to set family="" in ggplot2 theme() I can't seem to generate a change in fonts as I compile the MWE below with different font families.

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 is returning a warning font family not found in Windows font database, but there was a tutorial I was following (if I can find it again I will update the link here) that said this was normal and not a problem. Also, somehow this worked at one point because my graph once used some arial or helvitica type font. I think this has always been a present warning even during the initial times migration.

UPDATE

when I run windowsFonts() my output is

$serif [1] "TT Times New Roman"

$sans [1] "TT Arial"

$mono [1] "TT Courier New"

But, this is after I ran font_import() so I can only conclude that my fonts are not being saved in the right place. The code that ran the font_import() request actually loads the libraries with:

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

 Answers

91

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:

enter image description here

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: enter image description here

Tuesday, June 1, 2021
 
Zulakis
answered 6 Months ago
61

You can use the extrafont package.

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

enter image description here

Note: Using the extrafont package, you can also embed these fonts in PDF and EPS files (make plots in R and export to PDF/EPS). You can also directly create math symbols (see math equation in plot below), usually created using TeX. More information here and here. Also look at the github project page.

enter image description here

Also look at this answer which describes creating xkcd style graphs using the extrafont package.

enter image description here

Thursday, June 10, 2021
 
Jesse
answered 6 Months ago
74

With gtable version 0.2.0 (ggplot2 v 2.1.0) installed, Kohske's original solution (see the comments) can be made to work.

# Some toy data
df <- expand.grid(x = factor(seq(1:5)), y = factor(seq(1:5)), KEEP.OUT.ATTRS = FALSE)
df$Count = seq(1:25)

# Load packages
library(ggplot2)
library(grid)

# A plot
p = ggplot(data = df, aes( x = x, y = y, label = Count, size = Count)) + 
    geom_text() +
    scale_size(range = c(2, 10))
p

grid.ls(grid.force()) 
grid.gedit("key-[-0-9]-1-1", label = "N")

Or, to work on a grob object:

# Get the ggplot grob
gp = ggplotGrob(p)
grid.ls(grid.force(gp)) 

# Edit the grob
gp = editGrob(grid.force(gp), gPath("key-[1-9]-1-1"), grep = TRUE, global = TRUE,  
         label = "N")

# Draw it
grid.newpage()
grid.draw(gp)

Another option

Modify the geom

# Some toy data
df <- expand.grid(x = factor(seq(1:5)), y = factor(seq(1:5)), KEEP.OUT.ATTRS = FALSE)
df$Count = seq(1:25)

# Load packages
library(ggplot2)
library(grid)

# A plot
p = ggplot(data = df, aes( x = x, y = y, label = Count, size = Count)) + 
    geom_text() +
    scale_size(range = c(2, 10))
p

GeomText$draw_key <- function (data, params, size) { 
   pointsGrob(0.5, 0.5, pch = "N", 
   gp = gpar(col = alpha(data$colour, data$alpha), 
   fontsize = data$size * .pt)) }

p
Saturday, July 3, 2021
 
aWebDeveloper
answered 5 Months ago
10

First you get the font you want and install it on your system. Nothing to do with R. Test if the font works by checking in any regular program like MS Word or something.

Then open R, load extrafont package and import the font that you installed. I think it only works with .ttf fonts for now.

library(extrafont)
font_import(pattern="Roboto")

If this works, then this step will add those fonts to the extrafontdb. You will see something like this...

> font_import(pattern="Roboto",prompt=FALSE)
Scanning ttf files in C:windowsFonts ...
Extracting .afm files from .ttf files...
C:WindowsFontsRoboto-Black.ttf => C:/R/R-3.5.1/library/extrafontdb/metrics/Roboto-Black
C:WindowsFontsRoboto-BlackItalic.ttf => C:/R/R-3.5.1/library/extrafontdb/metrics/Roboto-BlackItalic
...
C:WindowsFontsRobotoCondensed-Regular.ttf => C:/R/R-3.5.1/library/extrafontdb/metrics/RobotoCondensed-Regular
Found FontName for 30 fonts.
Scanning afm files in C:/R/R-3.5.1/library/extrafontdb/metrics
Writing font table in C:/R/R-3.5.1/library/extrafontdb/fontmap/fonttable.csv
Writing Fontmap to C:/R/R-3.5.1/library/extrafontdb/fontmap/Fontmap...

This is a one time thing. Once imported, it is available within R from then on. All you have to do is run below.

library(extrafont)
# for windows
windowsFonts(sans="Roboto")
loadfonts(device="win")
loadfonts(device="postscript")

Now the defaults should have changed.

plot(x=1:5,y=1:5)

enter image description here

ggplot has base_family which needs to be changed and family argument for text geoms.

library(ggplot2)
p <- ggplot(data.frame(x=1:5,y=1:5),aes(x,y))+
  geom_point()+
  geom_text(aes(label=y),nudge_x=0.5,family="Roboto")+
  theme_bw(base_family="Roboto")
p

Exporting raster images should work too.

ggsave("plot.png",p)

enter image description here

PDFs are a pain. They have an extra family argument. There is also something about embedding and stuff. See link below.

ggsave("plot.pdf",p,family="Roboto")

All the info you need is here.

Wednesday, August 4, 2021
 
iteong
answered 4 Months ago
44

Try the pdf() function with an argument, colormodel = "cmyk"?

require("ggplot2")
pdf("test_cmyk.pdf", colormodel = "cmyk")
ggplot(mtcars, aes(wt, mpg)) + geom_point(size = 3, alpha = 0.2) +
  opts(title = "cmyk, alpha = 0.2")
dev.off()
embedFonts("test_cmyk.pdf")

It seems to be slightly better than colormodel = "rgb" in my environment (Win XP, Adobe Acrobat 9 Pro).

enter image description here

Sunday, October 10, 2021
 
Mr.D
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share