在R的直方图中绘制条形图

问题描述 投票:1回答:1

我正在尝试用堆积的条形图叠加直方图,但是当条形图从零开始绘制时,它总是向右移动。请参阅以下示例,以了解我要执行的操作(如果不使用ggplot,则应该添加)。

set.seed(1)

dat <- rnorm(1000, sd = 10)
h <- hist(dat)
cnt <- h$counts
breaks <- h$breaks

mat <- matrix(NA, nrow = 3, ncol = length(cnt))
for(i in 1:length(cnt)){
  sample <- sample(1:3, size = cnt[i], replace = TRUE)
  for(j in 1:3){
    mat[j, i] <- sum(sample == j)
  }
}

barplot(mat, add = TRUE, width = unique(diff(breaks)), space = 0, 
        col = c("blue", "green", "orange"))

此代码的输出如下:

enter image description here

我尝试在矩阵垫中使用列名指定位置,但无济于事。在要创建直方图的绘图中,将完全覆盖绘图,因为它应该与小节完全位于同一位置。首先将其绘制的原因是我希望直方图可以给我轴。非常感谢您对此有任何想法。

r plot
1个回答
0
投票

您可以对数据进行位置移位,以使最小值为0加上barplot的条宽,看来是5

h <- hist(dat, plot=FALSE)  ## first `hist` call
# [...]

hist(dat - min(dat) + 5)  ## second `hist` call
barplot(mat, add = TRUE, width = unique(diff(breaks)), space = 0, 
        col = c("blue", "green", "orange"))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.