Оставляя базу R как запрошенный OP, мы можем легко автоматизировать внутреннее позиционирование метки (т.е. x
координаты) в пределах небольшой функции.
xFun <- function(x) x/2 + c(0, cumsum(x)[-length(x)])
Теперь, хорошо знать, что barplot
невидимо бросает y
координаты, мы можем поймать их по присваиванию (здесь byc <- barplot(.)
).
В конце концов, просто соберите координаты и метки во фрейме данных labs
и выполните цикл по вызовам text
в sapply
. (Используйте col="white"
или col=0
для белых меток, как требуется в другом вопросе .)
# barplot
colors <- c("gold", "orange", "red")
par(mar=c(2, 19, 4, 2) + 0.1) # expand margins
byc <- barplot(as.matrix(stemdata), horiz=TRUE, col=colors, main="N=29", # assign `byc`
border=FALSE, las=1, xaxt='n')
# labels
labs <- data.frame(x=as.vector(sapply(stemdata, xFun)), # apply `xFun` here
y=rep(byc, each=nrow(stemdata)), # use `byc` here
labels=as.vector(apply(stemdata, 1:2, paste0, "%")),
stringsAsFactors=FALSE)
invisible(sapply(seq(nrow(labs)), function(x) # `invisible` prevents unneeded console output
text(x=labs[x, 1:2], labels=labs[x, 3], cex=.9, font=2, col=0)))
# legend (set `xpd=TRUE` to plot beyond margins!)
legend(-55, 8.5, legend=c("Medium","High", "Very High"), col=colors, pch=15, xpd=TRUE)
par(mar=c(5, 4, 4, 2) + 0.1) # finally better reset par to default
Результат
![enter image description here](https://i.stack.imgur.com/vy0Cp.png)
Данные
stemdata <- structure(list(`Food, travel, accommodations, and procedures` = c(7,
17, 76), `Travel itinerary and dates` = c(14, 10, 76), `Location of the STEM Tour stops` = c(14,
17, 69), `Interactions with presenters/guides` = c(4, 10, 86),
`Duration of each STEM Tour stop` = c(7, 17, 76), `Overall quality of the STEM Tour` = c(4,
10, 86)), class = "data.frame", row.names = c(NA, -3L))