【问题标题】:Barplot -adding percentages条形图 - 添加百分比
【发布时间】:2016-05-31 00:47:08
【问题描述】:

所以我有这个反映百分比

的数值变量
data1.pct<-19
data2.pct<-5
data3.pct<-76

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

现在我正在使用此代码生成条形图

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

我尝试过添加百分比

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

【问题讨论】:

标签: r bar-chart


【解决方案1】:

要获取文本的 y 值,您可以使用 cumsum 以及 tailhead 来获取每个条形部分的中点。

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

【讨论】:

  • 谢谢你的作品。如果有百分比,例如 76.864,并且想在条形图中四舍五入到 1 位,我在哪里放 round()?
  • @Miha 在text 电话中,输入labels=round(c(mat), 1))
猜你喜欢
  • 2023-01-04
  • 2022-09-25
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 2021-09-12
相关资源
最近更新 更多