我在统计书中找到了一个情节,我想用基础包重现 .
情节看起来像这样:
到目前为止,我有情节,但我有问题为栏的每个部分添加居中标签 .
我的代码如下所示:
data <- sample( 5, 10 , replace = TRUE )
colors <- c('yellow','violet','green','pink','red')
relative.frequencies <- as.matrix( prop.table( table( data ) ) )
bc <- barplot( relative.frequencies, horiz = TRUE, axes = FALSE, col = colors )
2 回答
这是使用
mapply
的另一种解决方案:mapply
是sapply
的多变量版本 . 在这种情况下,它需要两个输入:cumsum(relative.frequencies)
和relative.frequencies
并使用这两个向量应用text()
函数 .x =
是标签的坐标,它将每个累积总和减去每个相应的relative.frequencies
的一半 . 然后将relative.frequencies
再次用作要绘制的标签 .invisible()
功能禁止将输出打印到控制台 .对于您给出的示例,我们可以( all readers can skip this part and jump to the next ):
适合所有读者
I will now construct a comprehensive example for you to digest the idea.
Step 1: generate a toy matrix of percentage for experiment
Step 2: understand a stacked bar-chart and get "mid-height" of each stacked bar
对于堆积条形图,条形的高度是
h
的每列的累积总和:我们现在转回
h / 2
以获得每个堆叠条的中间/中心:Step 3: producing a bar-chart with filled numbers
对于垂直条形图,上面的
H
给出了每个堆叠条形中心的y
坐标 .x
坐标由barplot
(无形)返回 . 请注意,使用text
时,我们需要x
的每个元素nrow(H)
次:对于水平条形图,上面的
H
给出了每个堆叠条的中心的x
坐标 .y
坐标由barplot
(无形)返回 . 请注意,使用text
时,我们需要y
的每个元素nrow(H)
次: