Search code examples
rggplot2legendlegend-properties

How do you create a legend entry for a single geom/color combination in ggplot2?


I want to include a legend in ggplot2 for a geom/color combination with only one value. For example:

library(tidyverse)
lala <- tibble(
  haha = runif(100),
  baba = runif(100) - 2 , 
  equis = 1:100,
  cow = factor(round(runif(100)))
)
  runner <- tibble(ecks = rnorm(100) * 100, why = rnorm(100))

  ggplot(data = lala ) + 
geom_ribbon(mapping = aes(x = equis, ymax = haha, ymin = baba, fill = cow)) + 
geom_point(data = runner, aes( x = ecks, y = why))

the ribbons get legends, but I want a second legend with a single entry for the black points. I know that this is a silly example but I have a more serious example I'm working on. Any way to do this without a caption or annotation? Thanks.


Solution

  • One way would be to use the shape argument in the aesthetics of geom_point(). Then if you need to rename it you can use the labs() function.

    ggplot(data = lala ) +
      geom_ribbon(mapping = aes(x = equis, ymax = haha,ymin = baba, fill = cow)) +
      geom_point(data = runner, aes(x = ecks, y = why, shape = "")) +
      labs(shape="name goes here")
    

    enter image description here