This is a test version of Biostars. For the public version, visit https://www.biostars.org.
how to add lines to a plot gradually (ggplot2) ?

Hi

I have and algorithm which found some new 2D lines in each iteration, I want to add this lines to ggplot frequently, I searched for it but I can't find a good example,

I write it using normal plot and that's it:

plot(c(0 , Len1), c(0, Len2), type= "n",xlim=c(0,Len1),  ylim=c(0,Len2))
for(j in 1:maxa){
  for (k in 1:8) {
    if( someCondition  ){
        lines(x = c(br[j,1],br[j+k,1]) , y=c(br[j,3],br[j+k,3]),col="blue") 
    }
  }
}

and this is my current result:

image: plot

Now I want to write a same thing but with ggplot2

Thanks all

line ggplot2 r plot

Do you mean to animate it? If so see gganimate and tweenr packages.

We can use the same logic to add lines in a loop, something like: mygg <- ggplot(data... aes(....)) + geom_line(), then do the same inside for loop but adding on top of existing plot, mygg <- mygg + geom_line(data ... aes(....))

Curse you, I was typing my answer. :)

1 answer

If you are working in a loop, store your ggplot in an object and then add a geom_line. Here's a small example.

library(ggplot2)
xy <- data.frame(on_x = 1:10, on_y = rnorm(10))

p <- ggplot(xy, aes(x = on_x, y = on_y)) +
  theme_bw() +
  geom_line()

for (i in 1:10) {
  temp <- data.frame(on_x = 1:10, on_y = rnorm(10))
  p <- p + geom_line(data = temp, aes(x = on_x, y = on_y))
}

p

The result can be viewed here.

sorry but Wrong! as you can see in my example, i want multiple distinct lines... i found my answer myself, i have to group lines and then use group parameter in geom_line()

Please be nice - it's nice to be nice - plus you're more likely to get help in the future :)

Log in to answer this question.