Miha
Miha

Reputation: 2884

Barplot -adding percentages

So i have this numeric variables which reflect percentages

data1.pct<-19
data2.pct<-5
data3.pct<-76

class1.pct<-35
class2.pct<-18
class3.pct<-47

Now i am using this code to generate barplot

CairoPDF(paste('data1/', data, '_plot1.pdf', sep=''), family='sans', pointsize=9, width=6, height=3.25)
par(mar=(c(4, 4, 1, 13) + 0.1), mgp=c(3, 2, 0), xpd=TRUE)
barplot(cbind(
  c(data1.pct, data2.pct, data3.pct),
  c(class1.pct, class2.pct, class3.pct)), col=c("firebrick3", "dodgerblue3", "mistyrose1"), ylim=c(0,100), space=c(0,1)
)
legend("topright", inset=c(-0.55, 0), legend=c("not attend", "refused", "attend"), col=c("mistyrose1", "dodgerblue3", "firebrick3"), lty=1, lwd=2, bty='n')
dev.off()

and the result is enter image description here

I would like to add corresponding percentages inside barplot, that is numbers/percentages in my variables. So My output should be: enter image description here

I would like to use barplot funcion to do this and NOT ggplot2

I have tried adding percentages with

text(mydata, 0, round(data1.pct), 1),cex=1,pos=3) but this is not right.

Upvotes: 2

Views: 3300

Answers (1)

Rorschach
Rorschach

Reputation: 32436

To get the y-values for the text, you can use cumsum along with tail and head to get the midpoints of each bar section.

par(mar=(c(4, 4, 1, 13) + 0.1), mgp=c(3, 2, 0), xpd=TRUE)

## Make the matrix for barplot
mat <- cbind(c(data1.pct, data2.pct, data3.pct), c(class1.pct, class2.pct, class3.pct))

## Get the y-values for text
ys <- apply(mat, 2, function(x) c(x[1]/2, head(cumsum(x),-1) + tail(x,-1)/2))

## Make barplot, store x data
xs <- barplot(mat, col=c("firebrick3", "dodgerblue3", "mistyrose1"), ylim=c(0,100), space=c(0,1))

## Add text
text(rep(xs, each=nrow(ys)), c(ys), labels=c(mat))

legend("topright", inset=c(-0.55, 0), legend=c("not attend", "refused", "attend"), col=c("mistyrose1", "dodgerblue3", "firebrick3"), lty=1, lwd=2, bty='n')

enter image description here

Upvotes: 3

Related Questions