2013-04-15 35 views
2

我正在使用ggplot2,我需要在同一個直方圖上顯示兩組數據,並且需要區分它們。目前,我只是將每個系列的顏色設置爲50%不透明度,以便我可以看到隱藏在彼此背後的酒吧,但這非常不理想,看起來非常難看,而且很難讀取。覆蓋在同一條形圖/直方圖上的兩個數據系列

R有沒有一種方法可以智能地疊加小節,這樣我就可以使用完全不透明的小節,並且永遠不會看到一個隱藏的小節?這裏是我的代碼的時刻:

library(ggplot2) 
dat <- data.frame(a=sample(10, size=100, replace=T), 
        b=sample(10, size=100, replace=T)) 
ggplot(dat, aes(x=a), fill=rgb(1,0,0,0.5)) + geom_histogram() 
          + geom_histogram(aes(x=b), fill=rgb(0,0,1,0.5)) 

code output for 50% opaque bars

任何指針都大加讚賞。

回答

6

以長格式工作,然後使用position_dodge躲避重疊的垃圾箱。如果你希望他們還是重疊的,那麼你可以設置alpha以及

library(reshape2) 
ldat <- melt(dat) 


# slight overlap 
ggplot(ldat, aes(x=value, colour = variable, fill = variable)) + 
    geom_histogram(position = position_dodge(width = 0.5), binwidth = 1, alpha =0.5) 

enter image description here

# or the default value 
ggplot(ldat, aes(x=value, colour = variable, fill = variable)) + 
    geom_histogram(position = 'dodge', binwidth = 1) 

enter image description here

或者你可以使用小面,這將意味着你的問題消失了,因爲你不再有任何溢出

ggplot(ldat, aes(x=value)) + 
    geom_histogram(binwidth=1,fill = 'grey', colour = 'black') + 
    facet_grid(~variable) 

enter image description here

+0

謝謝!我想我必須和position_dodge一起去。這仍然不像出版質量圖表,但現在沒問題。乾杯! – Durand