2015-11-06 215 views
-1
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是一个数据集仅包含两列登录这是一个长数的表号,状态,这是一个因素包含3个级别-C,L,T 我试图用它来绘制重叠的直方图,但它只返回一个。由于GGPLOT2多直方图图表描绘仅单个直方图

the graph it produced

回答

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

+0

,对不起,你能告诉我如何为这个 –

+0

嗯添加一个图例,看看现在。不那么容易。 –

2

您想在状态

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

我想您的建议我生成的数据。看起来错了。像三色旗。 –

+0

有趣的是,如果我在日志编号中使用反引号代替单引号,那么您的解决方案就有点类似了。所以'Log Number'(带有backtics)而不是''Log Number''。不是什么OP想要的,但更接近。 WTH会这样吗? –