如何在堆叠条形图中的条形图上添加比率

时间:2014-05-07 14:54:16

标签: r plot bar-chart

我想在条形图上方添加堆积条形图的值计数之间的比率,我该怎么办? 这是示例数据框:

dat <- read.table(text = " TargetVar  Var1    Var2       Var3
 0        0        0         7
 0        0        1         1
 0        1        0         3
 0        1        1         7
 1        0        0         5
 1        0        1         1
 1        1        0         0
 1        1        1         6
 0        0        0         8
 0        0        1         5
 1        1        1         4
 0        0        1         2
 1        0        0         9
 1        1        1         2  ", header = TRUE)

我写了以下代码:

counts <- table(dat$TargetVar, dat$Var3)
barplot(counts, main="Is churn",
        xlab="Var1", col=c("darkblue","red"),
        legend = rownames(counts))

并获得此图表,但如何在条形图上方添加比率?

bar chart

1 个答案:

答案 0 :(得分:2)

这应该有效:

barX <- barplot(counts, main="Is churn",
        xlab="Var1", col=c("darkblue","red"),
        legend = rownames(counts))

ratios <- apply(counts, 2, paste, collapse = "/")
text(cex=.9, x=barX, y=apply(counts, 2, sum) + .05, ratios, xpd=TRUE) 

enter image description here

编辑根据您的要求:

ratios <- paste(apply(counts, 2, paste, collapse = "/"), " = ",
    apply(counts, 2, function(x) x[1]/x[2]), "%")