1

I would like to produce a completely customized legend for a ggplot. For complicated reasons that are beyond a MWE, I do not want to specify color within my various aes arguments.

Here's an example of what I want to work:

p = ggplot() + 
  # First plot some data from one set
  geom_point(aes(x = rnorm(10), y = rnorm(10)), col = "blue") +
  # Then plot some data from another set
  geom_point(aes(x = rnorm(10) + 1, y = rnorm(10) + 1), col = "orange") + 
  # Just to make the plot mildly cleaner
  labs(x = "X", y = "Y") +
  # Now want to manually come up with my own legend
  # However ggplot seems to ignore this
  scale_colour_manual(name = "Group", 
                    values = c("Group 1" = "blue", "Group 2" = "orange"))
# Printing the plot
p

But the resulting plot ignores my scale_colour_manual call as we can see below:

enter image description here

How can I independently force a custom legend?

Cliff AB
  • 1,160
  • 8
  • 15
  • `scale_color_manual` will apply to the variable passed in `color` argument in the `aes`. Are you sure you absolutely do not want a `color` argument in `aes` ? – dc37 Apr 21 '20 at 17:53
  • 3
    Pretty sure you can't in ggplot, unless you want to go the route of `cowplot::get_legend`. But even if you don't want to map a variable in `aes`, you can still just announce a label directly in `aes`, like in the accepted answer here: https://stackoverflow.com/questions/3777174/plotting-two-variables-as-lines-using-ggplot2-on-the-same-graph – Axeman Apr 21 '20 at 17:59
  • @dc37: I'm pretty sure of it. In my actual application, the issue is that I have lots of functions that are adding lots of things that are being added to the plots (represented in my mwe with the two different `geom_point` calls, but in reality much more). Trying to get that work didn't seem to go anywhere, but more generally it'd actually be simpler in the code just to force the legend than to build the multiple custom `aes`'s. – Cliff AB Apr 21 '20 at 18:01
  • @dc37: actually, it's worth noting that I'm not doing multiple `geom_point` calls, but rather multiple `stat_contour` calls. This means I can't roll everything up into a single `geom_point` call with a variable for color. Unfortunately, adding that to MWE would add 20 lines of code or so. – Cliff AB Apr 21 '20 at 18:05
  • @Axeman: as I noted in my question, I do **not** want to go the `aes` route. Demonstrating the issue unfortunately would greatly expand the MWE, so I'd rather cut to the point and ask about how to create a custom legend. – Cliff AB Apr 21 '20 at 18:44
  • 1
    You'll need `aes` somewhere. You can trick ggplot by adding another layer of fake points, e.g.: `p + geom_point(aes(x = 1, y = 1, color = Group), alpha = 0, data = data.frame(Group = paste("Group", 1:2)))`. – Axeman Apr 21 '20 at 19:07

0 Answers0