how to add lines to a plot gradually (ggplot2) ?
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:

enter image description here

now i want to write a same thing but with ggplot2

thanks all

ggplot2 R plot line • 10k views
ADD COMMENT
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(....)))

ADD REPLY
1
Entering edit mode

Curse you, I was typing my answer. :)

ADD REPLY
0
Entering edit mode

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

ADD REPLY
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.

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

ADD REPLY
3
Entering edit mode

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

ADD REPLY

Login before adding your answer.

Traffic: 2512 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6