2012-03-22 62 views
21

基本圖形中我最喜歡的技巧之一是Bill Dunlap的拾取。能夠在條形圖上放置數值(或任何值)在條形圖上(我不使用它,但偶爾會喜歡它)。在條形圖上註釋值(ggplot分面)

mtcars2 <- mtcars[order(-mtcars$mpg), ] 
par(cex.lab=1, cex.axis=.6, 
    mar=c(6.5, 3, 2, 2) + 0.1, xpd=NA) #shrink axis text and increas bot. mar. 

barX <- barplot(mtcars2$mpg,xlab="Cars", main="MPG of Cars", 
    ylab="", names=rownames(mtcars2), mgp=c(5,1,0), 
    ylim=c(0, 35), las=2, col=mtcars2$cyl) 

mtext(side=2, text="MPG", cex=1, padj=-2.5) 
text(cex=.5, x=barX, y=mtcars2$mpg+par("cxy")[2]/2, mtcars2$hp, xpd=TRUE) 

它給你:

enter image description here

我希望能夠做同樣標註在ggplot方位條曲線。很明顯,這些值也必須與你刻畫的相同的兩個變量相同,以便你可以用ftable獲得它們。我想採取下面的ftable結果(對於非零值)並將它們放在它們各自的小節上方。

library(ggplot2) 
mtcars2 <- data.frame(id=1:nrow(mtcars), mtcars[, c(2, 8:11)]) 
mtcars2[, -1] <- lapply(mtcars2[, -1], as.factor) 

with(mtcars2, ftable(cyl, gear, am)) 

ggplot(mtcars2, aes(x=cyl)) + geom_bar() + 
    facet_grid(gear~am) 

這對我來說似乎很難,但也許它會比我想象的更容易。預先感謝您考慮這個問題。

+0

這是相關的嗎? http://stackoverflow.com/a/9185168/1036500 – Ben 2012-03-22 01:45:34

+0

@ben我認爲你的解決方案,但我不能連接到'facet_grid' – 2012-03-22 01:58:21

+0

有趣的是,這種標籤是由一些人認爲,使顯示更混亂,應該避免:http://stackoverflow.com/q/6644997/1036500和http://stackoverflow.com/a/9318468/1036500 – Ben 2012-03-22 02:28:58

回答

23

我認爲你只是想要每個非零棒的數量(即高度)嗎?如果是這樣,就可以實現與

ggplot(mtcars2, aes(x=cyl)) + 
    geom_bar() + 
    facet_grid(gear~am) + 
    stat_bin(geom="text", aes(label=..count.., vjust=-1)) 

將會產生此圖(您可能需要做一些調整,以獲取最高的標籤顯示): enter image description here

count是在數據幀的新變量由stat_bin()創建,這就是爲什麼你必須參考它..count..