Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with merging multiple geom_rect()?

Tags:

r

ggplot2

I have a simple data set, with

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

And I want to all multiple geom_rect() to the plot. Here is what I do, and it looks fine.

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, what putting those three geom_rect() calls into a loop, I get a different plot. It seems that the geom's are merged together. Can I someone tell 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

like image 736
baidao Avatar asked Nov 19 '25 03:11

baidao


1 Answers

The other answer is good. Just that if you really want to stick with your original code. Here is a solution with 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

like image 138
KFB Avatar answered Nov 21 '25 16:11

KFB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!