topepo
topepo

Reputation: 14316

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

Upvotes: 1

Views: 207

Answers (1)

tonytonov
tonytonov

Reputation: 25608

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"))

enter image description here

Upvotes: 1

Related Questions