R graphics: Add labels to stacked bar chart

被刻印的时光 ゝ 提交于 2019-11-28 05:16:44

问题


I am looking for a way to add labels, i.e. absolute values, into a stacked bar chart using the basic plot functions of R. The labels should be inside the stacked bars.

Thank you!


回答1:


barplot will return the mid x position of the bars, so you could do

mydata <- matrix(c(10, 21, 22, 33, 45, 23, 22, 43, 33), nrow=3)

# b will contain the x midpoints of the bars
b <- barplot(mydata)

# This will write labels in the middle of the bars, horizontally and vertically
text(b, colMeans(mydata), c("Label1", "Label2", "Label3"))

# This will write labels in the middle of the middle block
text(b, mydata[1,]+mydata[2,]/2, c("LabelA", "LabelB", "LabelC"))

EDIT: re-reading your question, I think this is what you want (or maybe not, but I'll write it anyways :D)

# Find the top y position of each block 
ypos <- apply(mydata, 2, cumsum)
# Move it downwards half the size of each block
ypos <- ypos - mydata/2
ypos <- t(ypos)

text(b, ypos, mydata)



回答2:


How about the simple function text()?

You can simply add a string where ever you want, eg:

text (x = ..., y = ..., labels = c("foo bar 1000"))



回答3:


Maybe you can use or inspect the barp function of the plotrix package



来源:https://stackoverflow.com/questions/3626324/r-graphics-add-labels-to-stacked-bar-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!