条形图添加百分比 [英] Barplot -adding percentages

查看:623
本文介绍了条形图添加百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个数字变量,它们反映了百分比

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

现在我正在使用此代码来生成barplot

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()

,结果是

我想在条形图中添加相应的百分比,即变量中的数字/百分比.所以我的输出应该是:

我想使用barplot函数来完成此操作,并且 ggplot2

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

我尝试用来添加百分比

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

推荐答案

要获取文本的y值,可以使用cumsum以及tailhead来获取每个条形区域的中点

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')

这篇关于条形图添加百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆