Search code examples
rggplot2colorsfacet-gridlegend-properties

Manually add a key and text label in the legend for data repeated in all facets


I'm trying to add a key and a text label for certain data that I want repeated in all facets. First, I followed the procedure read in this forum to repeat certain data in all facets without creating a new facet, then I choose its color in aes() and I set the scale_color_manual(), but even though the points are plotted, the color is not correct and neither it is showed in the legend.

Any advice?

Here the reproducible example (please, consider they are not the real data, there is a reason why I want separate facets):


example <- data.frame(group=c("A","A","A","B","B","B","C","C","C"),
           time=c(1,2,3,1,2,3,1,2,3),
           value=c(5,6,7,9,10,11,2,2,3))
example$group <- factor(example$group, levels=c("A","B","C"))


ggplot(data=example[example$group!="C",],
         aes(x=time, y=value))+
  geom_point(data=example[example$group!="C",],
         aes(color=group))+
  geom_point(data=select(example[example$group=="C",],
                         -group),
         aes(color="red"))+
  facet_grid(~group)+
  scale_color_manual(breaks=c("A","B","C"),
                     values=c("purple","green","red"))

What produced the following plot:

enter image description here

When I don't set the scale_color_manual, points of group "C" are represented in the legend, but not with the correct color.

enter image description here

I also tried using different data.frames but as I delete the variable group from the geom_point that I use to plot the "C" points, they are either non-colored and non-represented in the legend or at least non-colored. Any advice? Thanks in advance.


Solution

  • Instead of the color name map the name of the category aka "C" on the color aes:

    library(ggplot2)
    
    ggplot(
      data = example[example$group != "C", ],
      aes(x = time, y = value)
    ) +
      geom_point(
        data = example[example$group != "C", ],
        aes(color = group)
      ) +
      geom_point(
        data = dplyr::select(
          example[example$group == "C", ],
          -group
        ),
        aes(color = "C")
      ) +
      facet_grid(~group) +
      scale_color_manual(
        breaks = c("A", "B", "C"),
        values = c("purple", "green", "red")
      )