Fonts

    Solution

    Update: Also see the package for much better support of fonts for PDF and Windows bitmap output.

    Font support in R is generally not very good. It varies between systems, and between output formats.

    With or annotate in ggplot2, you can set a number of properties of the text. geom_text is used to add text from the data frame, and annotate is used to add a single text element.

    Note that size is in mm, not points.

    When controlling elements such as the title, legend, axis labels, and so on, you use element_text, which has the same parameters, except that size is points (not mm), and instead of fontface, it uses face. The default value of depends on the element; for example, titles are larger than tick labels.

    1. p + geom_point() +
    2. ggtitle("This is a Title") +
    3. theme(plot.title=element_text(family="Times", face="bold", size=20))

    You can use this code to generate a graphical table of fonts. Fonts have short names and canonical family names. You can use either one when specifying the family.

    To view it on screen:

    1. pf

    Notice that on the system that generated this picture, most of the fonts (at the top) don’t really work. Only the basic fonts (at the bottom) work.

    plot of chunk unnamed-chunk-7


    And PDF output (the image below has been converted from PDF to PNG):

    1. print(pf)
    2. dev.off()

    The PDF device has better font support than the PNG device. All the fonts work (though they’re not necessarily pretty):