2013-10-29 143 views
1

假設我有一個柱狀圖像如何覆蓋條形圖

ggplot(mtcars, aes(factor(cyl)))+geom_bar() 

enter image description here

現在我想在覆蓋數的水平線= 5,4,6的各條線路上對於cyl分別爲4,6,8。每條線應該跨越它所覆蓋的條的寬度。我該如何做到這一點?

回答

3

冷杉,把你的計數數據在具有與mtcars相同的列名cyl的新數據框中。添加這些行

df2<-data.frame(cyl=c(4,6,8),counts=c(5,4,6)) 

的一種方法是使用geom_crossbar()並設置yyminymax和向的counts相同的值。

ggplot(mtcars, aes(factor(cyl)))+geom_bar()+ 
    geom_crossbar(data=df2,aes(x=factor(cyl), 
        y=counts,ymin=counts,ymax=counts),color="green") 

geom_errorbar()也可以達到同樣的效果。

ggplot(mtcars, aes(factor(cyl)))+geom_bar()+ 
    geom_errorbar(data=df2,aes(x=factor(cyl), 
        ymin=counts,ymax=counts),color="green") 

enter image description here