Search code examples
rggplot2plotlyggplotly

Alternative for geom_label in ggplotly


I would like to use the "fill" function of geom_label in a ggplotly graph. Unfortunately, ggplotly does not support geom_label. Instead I am working with geom_text but you cannot use "fill" here. Is there an alternative of how to get a background around your text without geom_label as in the picture below?

enter image description here


Solution

  • Well, this mimics the aesthetic of geom_label:

    #First compute sizes
    width <- strwidth(rownames(mtcars),units = "figure")
    height <- strheight(rownames(mtcars),units = "figure")
    xrange <- diff(range(mtcars$wt))
    yrange <- diff(range(mtcars$mpg))
    
    #New dataset
    data <- data.frame(x = mtcars$wt,
                       y = mtcars$mpg,
                       label = rownames(mtcars),
                       xmin = mtcars$wt - width*xrange,
                       xmax = mtcars$wt + width*xrange,
                       ymin = mtcars$mpg - height*yrange,
                       ymax = mtcars$mpg + height*yrange)
    
    gg <- ggplot(data, aes(x, y, label = label)) + 
      geom_rect(fill = "white",aes(xmin = xmin,xmax = xmax,ymin = ymin,ymax = ymax)) +
      geom_text() 
    
    ggplotly(gg)
    

    plot with car names and white rectangles

    But it's not great. If you zoom in the rectangles will not resize as the text does, so consider whether you can live with that. Hope it helps!