Question: how to add lines to a plot gradually (ggplot2) ?
0
gravatar for Amirosein
3.7 years ago by
Amirosein70
UBC, Vancouver, CA.
Amirosein70 wrote:

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:

enter image description here

now i want to write a same thing but with ggplot2

thanks all

plot ggplot2 R line • 8.3k views
ADD COMMENTlink modified 3.7 years ago by Roman Luštrik100 • written 3.7 years ago by Amirosein70
1

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 forloop but adding on top of existing plot, mygg <- mygg + geom_line(data ... aes(....)))

ADD REPLYlink written 3.7 years ago by zx87549.6k
1

Curse you, I was typing my answer. :)

ADD REPLYlink written 3.7 years ago by Roman Luštrik100

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

ADD REPLYlink written 3.7 years ago by zx87549.6k
4
gravatar for Roman Luštrik
3.7 years ago by
Ljubljana, Slovenia
Roman Luštrik100 wrote:

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.

ADD COMMENTlink written 3.7 years ago by Roman Luštrik100

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()

ADD REPLYlink written 3.7 years ago by Amirosein70
3

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

ADD REPLYlink written 3.7 years ago by John12k
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 963 users visited in the last hour