ggplot2多直方图仅绘制单个直方图

时间:2015-11-06 21:20:54

标签: r ggplot2

ggplot(d,aes(x= `Log Number`)) + 
    geom_histogram(data=subset(d,state == 'c'),fill = "red", alpha = 0.2) +
    geom_histogram(data=subset(d,state == 'l'),fill = "blue", alpha = 0.2) +
    geom_histogram(data=subset(d,state == 't'),fill = "green", alpha = 0.2)

d是一个数据集,只包含两列log号,这是一个很长的数字列表,state是一个因子包含3个level-c,l,t  我试图用它来绘制一个重叠的直方图,但它只返回一个。感谢

the graph it produced

2 个答案:

答案 0 :(得分:2)

您希望按状态填写

ggplot(d, aes(x = `Log Number`, fill = state)) + geom_histogram()

答案 1 :(得分:0)

嗯,我不知道,我认为你的数据是错误的。为我工作:

lon <- log( rnorm(1000,exp(6) ))
state <- sample(c("c","l","t"),1000,replace=T)
d <- data.frame(lon,state)
names(d) <- c("Log Number","state")
head(d)

产生以下数据:

  Log Number state
1   5.999955     t
2   5.997907     c
3   6.002452     l
4   5.994471     l
5   5.997306     l
6   6.000798     t

然后是情节:

ggplot(d,aes(x= `Log Number`)) + 
  geom_histogram(data=subset(d,state == 'c'),fill = "red", alpha = 0.2) +
  geom_histogram(data=subset(d,state == 'l'),fill = "blue", alpha = 0.2) +
  geom_histogram(data=subset(d,state == 't'),fill = "green", alpha = 0.2)

看起来像这样: enter image description here

相关问题