Search code examples
rggplot2label

Add aesthetics to the text label in ggplot


I have below ggplot

library(ggplot2)

set.seed(1234)
ss <- sample(1:32, 15)
df <- mtcars[ss, ]

ggplot(df, aes(wt, mpg)) +
  geom_point(color = 'red') +
  geom_label(aes(x = 2, y = 15), label = 'My Text', size = 10, label.size = 2, label.padding = unit(0.95, "lines"), fill = 'red', alpha = 0.50, color = 'black', label.r = unit(0.45, "lines"))

WHile it is working fine, I want add a few more aesthetics as follow

  1. Want to add some transparency in the label background. I used alpha = 0.50, but it does not seem to be working
  2. Want to have different colour for the border
  3. Want to place the label at the top-left position of my graph with some top and left margin e.g. 5 unit.

Is there any way to achieve them? Any pointer will be very helpful


Solution

  • The issue with the transparency is that you add a label for each row in your data (In the upcoming version of ggplot2 you will get a message about that), i.e. 15 slightly transparent objects plotted of each other look as is there is no transparency applied. Hence, if you just want one label use annotate or use a one row data frame in geom_label/text. Concerning your third issue, if you want to place annotations in relative coordinates I would suggest to use annotation_custom, which however requires to pass your label as a grob. Unfortunately the labelGrob used for geom_label is not exported by ggplot2. Instead I switched to gridtext::richtext_grob (which is the grob powering the ggtext package). As an additional benefit this already adds more options for customization, e.g. you can set different colors for the outline and the text. Note that to apply the transparency to the fill color I used scales::alpha.

    library(ggplot2)
    
    set.seed(1234)
    ss <- sample(1:32, 15)
    df <- mtcars[ss, ]
    
    ggplot(df, aes(wt, mpg)) +
      geom_point(color = "red") +
      annotation_custom(
        gridtext::richtext_grob(
          text = "My Text",
          x = unit(0, "npc") + unit(5, "pt"),
          y = unit(1, "npc") - unit(5, "pt"),
          hjust = 0,
          vjust = 1,
          padding = unit(0.95, "lines"),
          r = unit(0.45, "lines"),
          gp = grid::gpar(
            col = "black"
          ),
          box_gp = grid::gpar(
            col = "blue",
            lwd = 2 * .pt,
            fill = scales::alpha("red", .5)
          )
        )
      )