注释条形上方的值(ggplot刻面)

时间:2012-03-22 01:25:24

标签: r ggplot2

我最喜欢的基本图形技巧之一是Bill Dunlap的拾音器。能够在条形图中将数值(或任何值)放在条形图上方(我不会使用它,但偶尔使用它但是喜欢它。)

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)

这对我来说似乎很难,但也许它比我想象的要容易。提前感谢您考虑这个问题。

1 个答案:

答案 0 :(得分:24)

我是否认为你只想要每个非零条的计数(即高度)?如果是这样,您可以通过

实现这一目标
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..

引用它的原因
相关问题