2015-11-06 162 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會這樣嗎? –