1
0
Entering edit mode
5.0 years ago
Amirosein ▴ 70

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:

now i want to write a same thing but with ggplot2

thanks all

ggplot2 R plot line • 10k views
1
Entering edit mode

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

1
Entering edit mode

Curse you, I was typing my answer. :)

0
Entering edit mode

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

4
Entering edit mode
5.0 years ago

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.

0
Entering edit mode

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

3
Entering edit mode

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