The pdf
and postscript
graphic devices in R have special functions that handle the translation of an R graphics font family name to a PostScript or PDF file. In this recipe, we will see how to choose the fonts for these vector formats.
We will only use the base graphics functions for this recipe. So, just open up the R prompt and type in the following code. You might wish to save the code as an R script for later use.
Let's create a PDF of an rnorm()
graph with the title and axis annotations in the Avant Garde font:
pdf("fonts.pdf",family="AvantGarde") plot(rnorm(100),main="Random Normal Distribution") dev.off()
To save the same graph as a postscript file, we use the following code:
postscript("fonts.ps",family="AvantGarde") plot(rnorm(100),main="Random Normal Distribution") dev.off()
As shown in the examples, the font family for a PDF or PostScript output is set exactly the same way as in the previous recipe, by using the family
argument. In the examples, we passed the family
argument to the pdf()
and postscript()
functions as they open the relevant graphics devices.
Note that we used a font family that was not available in the basic R graphics device. We can also use the default values sans
, serif
, and mono
, which are mapped to Helvetica, Times New Roman, and Courier New, respectively. The pdf
and postscript
devices have inbuilt mappings to a lot of font families. To see all the available fonts, we can use the pdfFonts()
command. Running pdfFonts()
at the R prompt lists all the names of the font families and related attributes (metrics, encoding, and class). To list just the names of all font families, we can run the following line of code:
names(pdfFonts())
This line of code gives the following output at the R prompt:
[1] "serif" "sans" "mono" [4] "AvantGarde" "Bookman" "Courier" [7] "Helvetica" "Helvetica-Narrow" "NewCenturySchoolbook" [10] "Palatino" "Times" "URWGothic" [13] "URWBookman" "NimbusMon" "NimbusSan" [16] "URWHelvetica" "NimbusSanCond" "CenturySch" [19] "URWPalladio" "NimbusRom" "URWTimes" [22] "Japan1" "Japan1HeiMin" "Japan1GothicBBB" [25] "Japan1Ryumin" "Korea1" "Korea1deb" [28] "CNS1" "GB1"
We can check the default mapping to sans by running pdfFonts()$sans
at the R prompt.
The postscript
device has two extra fonts: Computer Modern and Computer Modern Italic (you can check this by running names(postscriptFonts())
at the R prompt). Just like the commands for specific operating systems, we can use pdfFonts()
and postscriptFonts()
to add new font mappings for the pdf
and postscript
devices, respectively. Refer to the help section to see some examples of such mappings (?postscriptFonts()
and ?pdfFonts()
).