Search code examples
rggplot2knitrtikztikzdevice

ggplot2: Degree Celsius Symbol in labeller with dev="tikz" option in knitr


I want to put degree Celsius symbol in ggplot2 labeller. MWE is given below with its output:

library(ggplot2)
ggplot(data=mtcars, mapping = aes(x=drat, y=mpg)) + geom_point() +
  facet_wrap(facets = ~cyl, labeller = as_labeller(c(`4` = "4 °C",`6` = "6 °C", `8` = "8 °C")))

enter image description here

However the same strategy does not work when dev="tikz" option is used in knitr.


Solution

  • It looks like one option when working with a tikz device is to write math in native latex. \circ is the degree symbol, so one of your labels could be "$4^\\circ{C}$".

    The following knits to a PDF with dev = "tikz" and shows the degree symbol:

    ggplot(data=mtcars, mapping = aes(x=drat, y=mpg)) + geom_point() +
      facet_wrap(facets = ~cyl, 
             labeller = as_labeller(function(string) paste0("$", string, "^\\circ{C}$")))
    

    To add more spacing between the number and degree symbol you can include \\: or \\; in the label.

    labeller = as_labeller(function(string) paste0("$", string, "\\;^\\circ{C}$"))