15

In ggplot2, transparency that is defined in geom_XXX is reflected in the legend. For example:

df <- data.frame(x=runif(10000),  z=ifelse(runif(10000) > 0.5, 'a', 'b')); df$y <- runif(10000); df$y[df$z == 'b'] <- cos(df$x[df$z == 'b']*10)
ggplot(df) + geom_point(aes(x, y, color=z), alpha=0.1)

Gives the following result:

what we have

Since the points are very transparent, they are hardly seen on the legend. I would like to remove point transparency from the legend, so that the graph looks like this:

what I want

How is this possible?

Boris Gorelik
  • 29,945
  • 39
  • 128
  • 170

1 Answers1

39

You can use function guides() and override.aes= to set alpha value just for legend entries.

ggplot(df) + geom_point(aes(x, y, color=z), alpha=0.1)+
  guides(colour = guide_legend(override.aes = list(alpha=1)))
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • wasn't aware of this mechanism. Quick search for override.aes gave several more examples: http://stackoverflow.com/q/16356052/17523 and http://stackoverflow.com/q/5290003/17523 which is a duplicate of this question. – Boris Gorelik Nov 04 '13 at 09:55