Domanda

I would like to add the ratio between the value counts of a stacked bar plot above the bars, how can I do it? here is the example data frame:

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)

I wrote the following code:

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

and got this chart, but how can I add the ratio above the bars?

bar chart

È stato utile?

Soluzione

This should work:

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

EDIT Per your request:

ratios <- paste(apply(counts, 2, paste, collapse = "/"), " = ",
    apply(counts, 2, function(x) x[1]/x[2]), "%")
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top