R图形:为堆积条形图添加标签

3
我正在寻找一种使用R的基本绘图功能在堆叠条形图中添加标签(即绝对值)的方法。这些标签应该位于堆叠的条形内部。
谢谢!
3个回答

8
`barplot`会返回条形图的中心x位置,所以你可以这样做:
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"))

“编辑:重新阅读您的问题,我认为这就是您想要的(或者可能不是,但我还是写下了: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)

嗨Nico,哇,这个竖直条形图的效果非常完美。非常感谢你。我很高兴解决方案并不神秘。我也尝试将您的代码应用于竖直条形图。只需交换b和ypos即可。非常非常感谢! - Jens

1

关于简单函数 text() 怎么样?

你可以在任何你想要的地方简单地添加一个字符串,例如:

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

文本也是我的首选,但我该如何告诉R它应该将数据集中的值放置在堆栈的中心位置? - Jens

0
也许你可以使用或检查 plotrix 包的 barp 函数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接