Search code examples
rggplot2geom-text

How to create geom_text and geom_point with matching manual color scales?


I'd like to create a plot where my labels (derived from geom_text) match a manual color scale I'm using for my points. Here's an example using the Iris data set. When I enter the following code I get this error:

library(tidyverse)

labels <- tibble(
           Species = c("setosa", "veriscolor", "virginica"),
           Sepal.Length = c(4.3, 5.5, 7), 
           Sepal.Width = c(3.5, 2.3, 3.7))

ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(color = Species)) +
  geom_text(data = labels, 
            aes(x = Sepal.Length, 
                y = Sepal.Width, label = Species, color = Species),
            inherit.aes = F) +
  scale_color_manual(values = c("gray", "purple", "orange")    

Error: Insufficient values in manual scale. 4 needed but only 3 provided.

I've seen that this has something to do with unused factor levels but I can't seem to apply their solutions here.


Solution

  • The error is not in ggplot, but in your labels data frame:

    labels <-
      data.frame(
        Species = levels(iris$Species),
        Sepal.Length = c(4.3, 5.5, 7), 
        Sepal.Width = c(3.5, 2.3, 3.7) )
    

    You can also specify color in the global aes to simplify your code. And following Gregor comment, you don't need to specify x and y in geom_text, since it's also in the global aesthetics.

    ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
      geom_point() +
      geom_text(data = labels, aes(label = Species)) +
      scale_color_manual(values = c("gray", "purple", "orange"))
    

    enter image description here