我想显示值不叠加的多个组的直方图。我是这样做的:
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
会产生相同的结果。
谢谢,
最高
答案 0 :(得分:1)
只有使用fill
将aes
映射到变量时,系统才会自动生成图例,如下所示:
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"))