2015-04-04 105 views
1

我想顯示值不堆疊的多個組的直方圖。我這樣做:從頭開始顯示scale_fill_manual

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

我想要一個填充圖例顯示分組。我不知道爲什麼,這不會產生任何圖例(或錯誤):

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

使用無名values產生相同的結果。

感謝,

最大

回答

1

傳說,如果你使用aes映射fill變量是自動生成唯一的,就像這樣:

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

+0

感謝。這是一個很好的解決方案。 – topepo 2015-04-05 16:45:20