我有一个简单的数据集

tmp
#  xmin xmax ymin ymax
#     0    1    0   11
#     0    1   11   18
#     0    1   18   32

我想将所有多个geom_rect()都绘制到情节中。这是我的工作,看起来不错。
cols = c('red', 'blue', 'yellow')
x = seq(0, 1, 0.05)

ggplot(data = NULL, aes(x = 1, y = 32)) +
  geom_rect(data = NULL, aes(xmin=x, xmax = x + 0.05, ymin=0, ymax=11, fill = x), color = cols[1] ) +
  geom_rect(data = NULL, aes(xmin=x, xmax = x + 0.05, ymin=11, ymax=18, fill = x), color = cols[2])  +
  geom_rect(data = NULL, aes(xmin=x, xmax = x + 0.05, ymin=18, ymax=32, fill = x), color = cols[3])

但是,将这三个geom_rect()调用放入循环的原因是,我得到了另一幅图。看来,geom已合并在一起。我可以告诉我循环代码怎么了吗?
g1 = ggplot(data = NULL, aes(x = 1, y = 32))

for (i in 1:3) {
  yl = tmp[i, ]$ymin
  yu = tmp[i, ]$ymax
  g1 = g1 + geom_rect(data = NULL, aes(xmin=x, xmax = x + 0.05, ymin=yl, ymax=yu, fill = x), color = cols[i])
}
g1

最佳答案

另一个答案是好的。只是如果您真的想坚持使用原始代码。这是一个根据您的原始内容稍作修改的解决方案。

g1 = ggplot(data = NULL, aes(x = 1, y = 32))
for (i in 1:3) {
  yl = tmp[i, 3] ## no need to use $, just column index is fine
  yu = tmp[i, 4] ## no need to use $, just column index is fine
  ## ggplot2 works with data frame. So you convert yl, yu into data frame.
  ## then it knows from where to pull the data.
  g1 = g1 + geom_rect(data=data.frame(yl,yu), aes(xmin=x, xmax=x+0.05, ymin=yl, ymax=yu, fill=x), color=cols[i])
}
g1

08-24 14:35