简体   繁体   中英

Add legend for alpha when using identity scale

I'm building up a somewhat complex plot and want to specify the alpha for each point manually. I can do this with scale_alpha_identity , so far so good. But now I want to add a legend for my alpha scale. Adding a guide to scale_alpha_identity doesn't seem to work - I just get an error, even when I try adding breaks and labels as the documentation suggests: http://ggplot2.tidyverse.org/reference/scale_identity.html .

Minimal example: this produces the plot I'd like, but without a legend.

ggplot(data = iris) + 
  geom_point(aes(x = Sepal.Length, y = Sepal.Width, 
                 alpha = Petal.Length / max(Petal.Length))) + 
  scale_alpha_identity()

Based on the documentation, I thought this would work but it doesn't:

ggplot(data = iris) + 
  geom_point(aes(x = Sepal.Length, y = Sepal.Width, 
                 alpha = Petal.Length / max(Petal.Length))) + 
  scale_alpha_identity(breaks = c(0, 1), labels = c(0, 1), guide = 'legend')

I've also tried many other variations: passing 'colorbar' or 'legend' directly to the guide argument with and without the breaks and labels, passing guide_legend or guide_colorbar instead of strings - no luck, just different error messages. Adding a fake scale as suggested in Is there a way to add a legend for ggplot's alpha? doesn't work for me because it overrides my identity scale.

If you set the limits in scale_alpha_identity you can add a legend via guides .

ggplot(data = iris) + 
    geom_point(aes(x = Sepal.Length, y = Sepal.Width, 
                   alpha = Petal.Length / max(Petal.Length))) + 
    scale_alpha_identity(limits = c(.2, 1)) +
    guides(alpha = guide_legend() )

According to https://github.com/tidyverse/ggplot2/issues/2112 , a possible workaround is to use size identity function...

ggplot(data = iris) + 
  geom_point(aes(x = Sepal.Length, y = Sepal.Width, 
                 alpha = Petal.Length / max(Petal.Length))) + 
  scale_size_identity(guide = 'legend')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM