What's wrong with combining multiple geom_rect ()?

I have a simple dataset, with

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

      

And I want all to geom_rect()

appear somewhat in the plot. Here's what I do and everything looks good.

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

However, which puts these three geom_rect()

in a loop, I end up with a different plot. The geometry seems to be fused together. Can I tell someone to me what's wrong with the loop code?

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

+3


source to share


2 answers


Another answer is good. Simple if you really want to stick with your source code. Here is a solution, with a slight modification based on your original.

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

+2


source


To avoid the caveat described in @MrFlick, you can define data

separately for example, like:

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

      



and you will get the plot you want.

+1


source







All Articles