简体   繁体   中英

showing scale_fill_manual from scratch

I want to show histograms of multiple groups where the values do not stack. I do this by:

dat <- data.frame(x = seq(-3, 3, length = 20))
dat$y <- dnorm(dat$x)
dat$z <- dnorm(dat$x, mean = 2)

p <- ggplot(dat, aes(x = x)) + 
  geom_bar(aes(y = y), stat = "identity", alpha = .5, fill = "red") +
  geom_bar(aes(y = z), stat = "identity", alpha = .5, fill = "blue")  

I'd like to have a fill legend that shows the groupings. I'm not sure why this does not produce any legend (or error):

p + scale_fill_manual(values = c(x = "red", z = "blue"), 
                      limits = c("mean 0", "mean 2")) + 
    guides(fill=guide_legend(title.position="top"))

Using unnamed values produces the same result.

Thanks,

Max

The legend is automatically generated only if you map fill to variable using aes , like so:

library(reshape2)
ggplot(melt(dat, "x"), aes(x = x)) + 
  geom_bar(aes(y = value, fill = variable), 
           stat = "identity", position = "identity", alpha = .5) +
  scale_fill_manual(values = c(y = "red", z = "blue"), 
                        labels = c("mean 0", "mean 2"))

在此处输入图片说明

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