我在一本统计书中找到了一个图,我想用基础包来重现它。
情节如下:
到目前为止,我已经有了情节,但我在向栏的每个部分添加居中标签时遇到问题。
我的代码如下所示:
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 )
Run Code Online (Sandbox Code Playgroud)
对于您给出的示例,我们可以这样做(所有读者都可以跳过这一部分并跳到下一部分):
set.seed(0) ## `set.seed` for reproducibility
dat <- sample( 5, 10 , replace = TRUE )
colors <- c('yellow','violet','green','pink')
h <- as.matrix( prop.table( table( dat ) ) )
## compute x-location of the centre of each bar
H <- apply(h, 2L, cumsum) - h / 2
## add text to barplot
bc <- barplot(h, horiz = TRUE, axes = FALSE, col = colors )
text(H, bc, labels = paste0(100 * h, "%"))
Run Code Online (Sandbox Code Playgroud)
我现在将构建一个综合示例供您消化这个想法。
步骤1:生成一个用于实验的百分比玩具矩阵
## a function to generate `n * p` matrix `h`, with `h > 0` and `colSums(h) = 1`
sim <- function (n, p) {
set.seed(0)
## a positive random matrix of 4 rows and 3 columns
h <- matrix(runif(n * p), nrow = n)
## rescale columns of `h` so that `colSums(h)` is 1
h <- h / rep(colSums(h), each = n)
## For neatness we round `h` up to 2 decimals
h <- round(h, 2L)
## but then `colSums(h)` is not 1 again
## no worry, we simply reset the last row:
h[n, ] <- 1 - colSums(h[-n, ])
## now return this good toy matrix
h
}
h <- sim(4, 3)
# [,1] [,2] [,3]
#[1,] 0.43 0.31 0.42
#[2,] 0.13 0.07 0.40
#[3,] 0.18 0.30 0.04
#[4,] 0.26 0.32 0.14
Run Code Online (Sandbox Code Playgroud)
第 2 步:了解堆积条形图并获取每个堆积条形的“中间高度”
对于堆积条形图,条形的高度是 的每列的累积和h:
H <- apply(h, 2L, cumsum)
# [,1] [,2] [,3]
#[1,] 0.43 0.31 0.42
#[2,] 0.56 0.38 0.82
#[3,] 0.74 0.68 0.86
#[4,] 1.00 1.00 1.00
Run Code Online (Sandbox Code Playgroud)
现在我们向后移动h / 2以获得每个堆叠条形的中间/中心:
H <- H - h / 2
# [,1] [,2] [,3]
#[1,] 0.215 0.155 0.21
#[2,] 0.495 0.345 0.62
#[3,] 0.650 0.530 0.84
#[4,] 0.870 0.840 0.93
Run Code Online (Sandbox Code Playgroud)
第 3 步:生成填充数字的条形图
对于垂直条形图,H上面给出了y每个堆叠条形的中心坐标。坐标x由(不可见)返回barplot。请注意,在使用 时,我们需要复制每个x元素的次数:nrow(H)text
x <- barplot(h, col = 1 + 1:nrow(h), yaxt = "n")
text(rep(x, each = nrow(H)), H, labels = paste0(100 * h, "%"))
Run Code Online (Sandbox Code Playgroud)
对于水平条形图,H上面给出了x每个堆叠条形的中心坐标。坐标y由(不可见)返回barplot。请注意,在使用 时,我们需要复制每个y元素的次数:nrow(H)text
y <- barplot(h, col = 1 + 1:nrow(h), xaxt = "n", horiz = TRUE)
text(H, rep(y, each = nrow(H)), labels = paste0(100 * h, "%"))
Run Code Online (Sandbox Code Playgroud)