Search code examples
rggplot2labeldata-visualizationfacet

Add additional labels from a DataFrame to a facet_grid with existing label


I have a set data that I need to add to levels of labels. One on a single chart within the facet grid, and one from a small dataframe with entries for for each chart.

In the example below you'll see that I can add to a single chart no problem but when I try to add from the df I get the error - Error in FUN(X[[i]], ...) : object 'wt' not found

Preparation:

library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_line()
p <- p + facet_grid(. ~ cyl)

ann_text <- data.frame(mpg = 30,wt = 5,lab = "Text",
                       cyl = factor(8,levels = c("4","6","8")))

dfl <- data.frame(name = c('Jim',"Bob", "Sue"), r = c(-0.2, 0.5, -0.4))

Single Label:

p + geom_text(data = ann_text,label = "Text") 

Multiple Labels:

p + geom_text(data = ann_text,label = "Text") + 
  geom_text(data = dfl, mpg = 30,wt = 5, aes(label = r))

The method I'm using is trying to recreate other examples I've found here on SO and elsewhere but I seem to be missing something.


Solution

  • It's not working in your second code because in the second geom_text, your mpg and wt in not in aes(). Also, these two variables are absent in your dfl.

    If you wish to have better control of the labelling of your r variable, you can create extra columns in dfl specifying the x and y location of the label, and use these variables in geom_text(aes()).

    Note that I have modified the y position in the second geom_text to avoid overlapping "0,2" with "Text".

    library(ggplot2)
    p <- ggplot(mtcars, aes(mpg, wt)) + geom_line()
    p <- p + facet_grid(. ~ cyl)
    
    ann_text <- data.frame(mpg = 30,wt = 5,lab = "Text",
                           cyl = factor(8,levels = c("4","6","8")))
    
    dfl <- data.frame(name = c('Jim',"Bob", "Sue"), r = c(-0.2, 0.5, -0.4))
    
    p + geom_text(data = ann_text,label = "Text") + 
      geom_text(data = dfl, aes(30, 4, label = r), check_overlap = T)
    

    Created on 2022-05-06 by the reprex package (v2.0.1)