我想在条形上方添加堆叠条形图的值计数之间的比率,我该怎么做?这是示例数据帧:
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))
并获得此图表,但是如何在柱形上方添加比率?
这应该工作:
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)
编辑根据您的要求:
ratios <- paste(apply(counts, 2, paste, collapse = "/"), " = ",
apply(counts, 2, function(x) x[1]/x[2]), "%")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句