I'm trying to draw a series of boxes in ggplot2 using a loop. Below, I have included a toy example.
# Load necessary library
library(ggplot2)
# Height of rectangle
box.size <- 0.5
# Colours for rectangles
my.cols <- c("red", "blue", "purple", "yellow", "green")
# Initialise plot & set limits
p <- ggplot() + xlim(0, 1) + ylim(0, 2.5)
# Loop through and draw boxes
for(i in 1:5){
# Draw boxes
p <- p + geom_rect(aes(xmin = 0, xmax = 1, ymin = (i - 1) * box.size, ymax = i * box.size),
fill = my.cols[i])
# Check that the loop is working
print(i)
}
# Plot graph
print(p)
This code only plots the final rectangle, but I can't figure out what I am doing wrong. The loop is running correctly because I included a print statement to check. Can someone point out my error and offer a solution, please?

ggplotis designed for plotting data. I'd recommend you construct a data frame (in a similar loop, if you want) and then plot that. As-is, you're trying to use a screwdriver as a hammer.ggplotis strongly designed around the data frame. You almost certainly shouldn't be usingaes()without a data frame, but even without that your code doesn't work. And theforloop has nothing to do with it - if you write out the first couple iterations by hand, the first layer works as expected and the second doesn't.