Search code examples
rggplot2transparency

geom_label unable to handle text transparency


I want to plot data using geom_label to plot some text inside rectangles. I can't find how to add transparency (alpha) to my text. In fact, transparency seems to apply only to the filling color:

ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars), alpha=cyl))+ geom_label(fill="blue")
ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars), alpha=cyl)) + geom_text()

When I use geom_text instead, the alpha parameters works as expected:

enter image description here Do you know a way to make the text inside the label also transparent when using geom_label? Thanks,


Solution

  • By using this brutal trick you can make it work. Just move label inside geom_text, and make an empty long string for geom_label, this is hardly a "reproducible" solution though.

    library(ggplot2)
    ggplot(mtcars, aes(wt, mpg, alpha=cyl)) + 
      geom_label(label="                               ", fill="blue") + 
      geom_text(aes(label = rownames(mtcars)))
    

    enter image description here

    Edit by @agenis: we could first compute the length of blank spaces for each label so we adapt the box to the text

    ggplot(mtcars %>% mutate(blank_label = strrep(" ", nchar(rownames(.))*2)), aes(wt, mpg, alpha=cyl)) + 
      geom_label(aes(label=blank_label), fill="blue") + 
      geom_text(aes(label = rownames(mtcars)))
    

    (the *2 is because I coulnd't get a font with fixed-width characters")