Home > Software design >  Labeling a ggplot with a mix of variables and expressions
Labeling a ggplot with a mix of variables and expressions

Time:10-27

I'm trying to make a labeled scatterplot in ggplot and the specifics of the labels are causing me fits. Basically, among other things, I want to annotate my facet_wrapped 2-panel ggplot with the R^2 and Mean Bias. Notably, I want to label the mean bias with the appropriate units.

A simple version of my data might look as follows:

library(tidyverse)

Demo_Df <- tibble(Modeled = rnorm(50,0,1), Observed = rnorm(50, 0.5, 1),
                  Scheme = c(rep("Scheme1", 25), rep("Scheme2", 25)))

Demo_Annotation <- tibble(r.squared = c(0.589, 0.573), Mean_Bias = c(-2.038, -1.049), Scheme = c("Scheme1", "Scheme2"))

Demo_Scatter <- Demo_Df %>%
  ggplot(aes(x = Observed, y = Modeled, color = Scheme))  
  geom_point(size = 1.5)  
  facet_wrap(~Scheme)  
  theme_tufte()  
  xlab(expression(paste("Observed Aerosol (", mu, "g m" ^ "-3", ")"), sep = ""))  
  ylab(expression(paste("Modeled Aerosol (", mu, "g m" ^ "-3", ")"), sep = ""))  
  ylim(-3, 4)  
  theme(legend.position = "none")

Demo_Labeled <- Demo_Scatter  
  geom_text(data = Demo_Annotation, aes(-2, 3,
            label = paste(
              "R2 = ", sprintf("%.2f", signif(r.squared, 3)), "\n",
              "Mean Bias = ", sprintf("%.2f", signif(Mean_Bias, 3))
              )),
            size = 5, hjust = 0, color = "black")

This produces almost the right figure, but I would like the R2 to have a superscript 2 and I need to add micrograms per cubic meter (ug/m3) to the end of the "Mean Bias = " label, as it is on the x and y-axes.

To date, I've completely failed at this. I cannot find a solution that supports multiple lines, facet_wrap, variable inputs, AND expressions. There has to be a way to do this. Please help me, tidyverse gods!

CodePudding user response:

One option to achieve your desired result is to add you multiple lines via multiple geom_text layers. To parse the labels as math notation add parse=TRUE to geom_text. Finally I added the labels to you annotations df where I made use of ?plotmath for the math notation.

library(tidyverse)
library(ggthemes)

Demo_Annotation <- Demo_Annotation %>% 
  mutate(r.squared = paste0("R^{2} == ", sprintf("%.2f", signif(r.squared, 3))),
         Mean_Bias = paste0("Mean~Bias == ", sprintf("%.2f", signif(Mean_Bias, 3)), "~mu*g~m^{-3}"))

Demo_Scatter  
    geom_text(data = Demo_Annotation, aes(x = -2, y = 4, label = r.squared),
            size = 5, hjust = 0, color = "black", parse = TRUE, family = "serif")  
    geom_text(data = Demo_Annotation, aes(x = -2, y = 3.5, label = Mean_Bias),
            size = 5, hjust = 0, color = "black", parse = TRUE, family = "serif")

DATA

set.seed(42)

Demo_Df <- tibble(Modeled = rnorm(50,0,1), Observed = rnorm(50, 0.5, 1),
                  Scheme = c(rep("Scheme1", 25), rep("Scheme2", 25)))
  • Related