使用单个直方图中的两个数据将图例添加到图层qplot

时间:2016-01-26 06:47:36

标签: r ggplot2 legend

我正在尝试将这两个样本添加到一个直方图中,其中一个层用于a,另一个层用于b。在图表之后,如何将图例添加到图表中?

    a <- rnorm(50,10,1)
    b <- rnorm(100,10,2)
    qplot(a,binwidth = 0.5,fill = "Red")+geom_histogram(b,fill="Blue",alpha = 0.2)

它提供了以下消息:错误:映射必须由aes()aes_()

创建

谢谢

1 个答案:

答案 0 :(得分:2)

鉴于

library(ggplot2)
set.seed(1)
a <- rnorm(50,10,1)
b <- rnorm(100,10,2)

你可以做到

qplot(a,binwidth = 0.5,fill = "Red") + 
  geom_histogram(aes(b), as.data.frame(b), fill="Blue",alpha = 0.2)

df <- stack(list(a=a, b=b))
ggplot(df, aes(x=values, fill=ind)) + geom_histogram(alpha=.5, binwidth = 0.5)

(后者被称为long-format,正如@Pascal所说。)