Search code examples
rggplot2ggrepel

Label color the same as bubble fill using ggrepel


I have a bubble chart and I'm using ggrepel to avoid overlapping labels.

Reproducible example:

library(randomcoloR)
n <- nrow(iris)
palette <- unname(distinctColorPalette(n))


(p <- iris %>% 
  ggplot(aes(x=Sepal.Length,
             y=Sepal.Width,
             label = Species,
             color = palette)) +
  geom_point(alpha = 0.7, show.legend = FALSE) +
  scale_color_manual(values=palette)
)


(r <-
    p + geom_point(
      aes(size = Petal.Length*Petal.Width),
      pch = 21,
      show.legend = FALSE,
      fill = palette
    ) +
    scale_size_continuous(range = c(2, 30)) +
    geom_text_repel(segment.color = "orange",
                    nudge_y = 0.05,
                    angle        = 0,
                    vjust        = -5,
                    segment.size = 0.2) +
    theme(legend.position = "none")
)

The issue is I want the label the same color the bubble but I'm getting the color of the circle border instead.

enter image description here


Solution

  • Your color and fill should be inside aesthetics aes(), then ggrepel will recognise them. I mean ggrepel use that one which specified in aes I've rewrite your code a bit:

    library(randomcoloR)
    library(ggrepel)
    n <- nrow(iris)
    palette <- unname(distinctColorPalette(n))
    
    
    iris %>% 
        ggplot(aes(x=Sepal.Length,
                   y=Sepal.Width)) +
        geom_point(
          aes(size = Petal.Length*Petal.Width,
              fill = palette,
              color = palette),
          alpha = .7,
          pch = 21,
          show.legend = FALSE) +
        scale_size_continuous(range = c(2, 30)) +
        geom_text_repel(aes(label = Species,
                            color = palette),
                        segment.color = "orange",
                        nudge_y = 0.05,
                        angle        = 0,
                        vjust        = -5,
                        segment.size = 0.2) +
        theme(legend.position = "none")
    

    enter image description here