合并多个geom_rect()有什么问题?

时间:2014-12-26 03:14:40

标签: r ggplot2

我有一个简单的数据集,

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]) 

enter image description here

然而,将这三个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

enter image description here

2 个答案:

答案 0 :(得分:2)

另一个答案是好的。只是,如果你真的想坚持你的原始代码。这是一个基于原始版本稍作修改的解决方案。

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

enter image description here

答案 1 :(得分:1)

为了避免@MrFlick解释的警告,您可以例如单独定义data,如下所示:

g1 = ggplot(data = NULL)

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

你会得到你想要的情节。