Search code examples
rggplot2geom-text

displaying single value from a different dataframe in ggplot


I'm trying to display a single value in my ggplot, but from a different data frame than the rest of the plot data. Basically, I just want to insert "d = [value from second dataframe]" in a corner of the graph. All of the advice points to using geom_text(), but I can't seem to get the syntax right. Here's the data reprex.

library(tidyverse)

df <- data.frame(junior = c(4,3,2,2,4,3,2), 
                 senior = c(2,6,3,5,2,6,3))
longdf <- df %>%
  pivot_longer(cols = everything(), names_to = 'class', values_to = 'rating')

df2 <- data.frame(p = .002, d = 0.64)

... and here is the plot code. I'm not sure what exactly would go in geom_text(), or if it's even possible to import a single data point from another dataframe. I also need to reference the data point vs. just pasting in the text "d = 0.64".

ggplot(data = longdf, aes(x = class, y = rating)) +
  geom_boxplot() +
  geom_text(data = df2, label = d)

Thanks for any help.


Solution

  • You need to wrap label = d in aes(), and specify x and y positions:

    library(ggplot2)
    
    ggplot(data = longdf, aes(x = class, y = rating)) +
      geom_boxplot() +
      geom_text(data = df2, aes(x = 2.4, y = 2, label = paste("d =", d)))
    

    Note that you don’t have to put the label values in a dataframe. You can also use annotate():

    ggplot(data = longdf, aes(x = class, y = rating)) +
      geom_boxplot() +
      annotate(geom = "text", x = 2.4, y = 2, label = "d = 0.64")