ClementWalter
ClementWalter

Reputation: 5272

Link colour with integer ggplot2

I am new with ggplo2 and I don't manage to reproduce something I was using with native plot function : basically I add points to a plot iteratively and I want the new points to be added with a colour changing also iteratively.

MWE:

pts = data.frame(x = rnorm(10), y = rnorm(10))
plot(pts, pch = 19)
for(i in 2:5) {
   pts = data.frame(x = rnorm(10), y = rnorm(10))
   points(pts, col = i, pch = 19)
}

which gives: enter image description here

while with ggplot2 I have:

pts = data.frame(x = rnorm(10), y = rnorm(10))
p <- ggplot(pts, aes(x,y)) + geom_point()
print(p)
for(i in 2:5) {
   pts = data.frame(x = rnorm(10), y = rnorm(10))
   p <- p + geom_point(data = pts, aes(colour = i))
   print(p)
}

enter image description here which does not give the same thing. I have thought using scale_colour_hue(5) instead of aes(colour=i) to specify I want 5 different distinguishable colours, but I got an error :

Error: Continuous value supplied to discrete scale

thanks !

Upvotes: 2

Views: 2164

Answers (1)

Heroka
Heroka

Reputation: 13139

Due to the iterative nature of your case, this might be a solution. I have added the iteration to the data, to have all information for a certain point contained in the relevant dataset. Then I used factor(i) to color it. You were on the right way with aes(color=i), but as i equals 5 at the end of the iteration all dots get colored as 5 (with the exception of the first iteration, as they have no color-mapping.

Edit: created a column 'iteration' with factor levels 1 to the number of iterations in each dataset and forced all levels to display in the scale parameter.

set.seed(124)
n_iterations <- 5
pts = data.frame(x = rnorm(10), 
                 y = rnorm(10),
                 iteration=factor(1,levels=1:n_iterations)
)
p <- ggplot(pts, aes(x,y, color=iteration)) + geom_point()+
  scale_colour_discrete(drop=FALSE) + #forces all levels to display
  ylim(c(-2.5,2.5)) #keeps plot limits constant

for(i in 2:5) {
  pts = data.frame(x = rnorm(10), 
                   y = rnorm(10), 
                   iteration=factor(i,levels=1:n_iterations))
  p <- p + geom_point(data = pts)
  print(p)
}

enter image description here

Iterated images: enter image description here

Upvotes: 4

Related Questions