Search code examples
rggplot2facet-wrap

Adding subscripts and symbols to facet_wrap in ggplot2


I am trying to create a 2x2 facet plot of some weather conditions over time, and am having trouble adding a degrees symbol and a superscript to some of the facet titles.

weatherPLOT = data.frame(weather = rep(c("Soil Temperature (C)", 
                                        "Snow Depth (m)", 
                                        "Air Temperature (C)", 
                                        "Discharge (m3/sec)"), each = 366),
                           day = 1:366,
                           mean = 3, # Obvious place holders,
                           Lo95 = 2, # Are actual numbers in real code
                           Hi95 = 4)

ggplot(aes(y = mean, x = day), data = weatherPLOT) + 
  geom_ribbon(aes(ymin = Lo95, ymax = Hi95), alpha = 0.25) +
  geom_path(size = 1) + 
  theme(axis.title.y = element_blank()) + xlab("Julian Day") +
  facet_wrap( ~ weather, nrow = 2, ncol = 2, scales = "free")

I know the trick is to use labeller inside of facet_wrap, but I can't to make it work - I'm just looking to add a degree symbol before the (C) and make the 3 in (m3/sec) superscripted.


Solution

  • The easiest way to do this to change the text values themselves to appropriate symbols and use the ggtext package for the formatting.

    \u00b0 is the Unicode value for the degree sign. <sup>3</sup> is the ggtext Markdown code for superscript 3. You specify that theme text should be markdown by using ggtext::element_markdown().

    library(ggplot2)
    weatherPLOT = data.frame(weather = rep(c("Soil Temperature (\u00b0C)", 
                                             "Snow Depth (m)", 
                                             "Air Temperature (\u00b0C)", 
                                             "Discharge (m<sup>3</sup>/sec)"), each = 366),
                             day = 1:366,
                             mean = 3, # Obvious place holders,
                             Lo95 = 2, # Are actual numbers in real code
                             Hi95 = 4)
    
    ggplot(aes(y = mean, x = day), data = weatherPLOT) + 
      geom_ribbon(aes(ymin = Lo95, ymax = Hi95), alpha = 0.25) +
      geom_path(size = 1) + 
      labs(y = "", x = "Julian Day") +
      theme(strip.text = ggtext::element_markdown()) +
      facet_wrap( ~ weather, nrow = 2, ncol = 2, scales = "free")
    

    Created on 2021-08-25 by the reprex package (v2.0.0)