创建一个堆积的条形图,其中包含以ggplot2打印的计数

时间:2015-02-12 13:51:17

标签: r ggplot2

所以我想创建一个堆积条形图,每个都打印频率计数 填充因子。

Showing data values on stacked bar chart in ggplot2

此问题将计数放在每个段的中心,但用户指定值。在这个例子中,我们不输入特定值,我正在寻找一个自动计算计数的r函数。

以以下数据为例。

set.seed(123)
a <- sample(1:4, 50, replace = TRUE)
b <- sample(1:10, 50, replace = TRUE)
data <- data.frame(a,b)
data$c <- cut(data$b, breaks = c(0,3,6,10), right = TRUE,
                         labels = c ("M", "N", "O"))
head(data)

ggplot(data, aes(x = a, fill = c)) + geom_bar(position="fill")

所以我想在1,2,3和4中为M,N和O值打印一个“n = ..”

所以最终结果看起来像

enter image description here

与此问题类似,但我们没有fr

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

obj <- ggplot_build(p)$data[[1]]

# some tricks for getting centered the y-positions:
library(dplyr)
y_cen <- obj[["y"]]
y_cen[is.na(y_cen)] <- 0
y_cen <- (y_cen - lag(y_cen))/2 + lag(y_cen)
y_cen[y_cen == 0 | y_cen == .5] <- NA

p + annotate("text", x = obj[["x"]], y = y_cen, label = paste("N = ", obj[["count"]]))

给出了:

enter image description here