0

I want to use push!() in a for loop to continue two separate plotting lines. Consider the following example:

using Plots; gr()

f = x->x*x
g = x->f(x)+.2*randn()
p = plot(-1:.1:0, f, ylim=(-1,2), c=:blue)
s = scatter!(-1:.1:0, g, c=:red)

anim = Animation()
for i=1:10
    x = i/10
    push!(p, x, f(x))
    push!(s, x, g(x)) # without this, f gets continued as expected
    frame(anim)
end
gif(anim, "test.gif", fps=2)

Why does push!(p, ...) and push!(s,...) both continue the blue line? How to append scattered data to s instead?

adding data to wrong line

I know that the second plot at this link achieves a similar result by plotting and pushing both lines at once, but that solution is not always practical, especially in more complicated plots.

mattu
  • 944
  • 11
  • 24

1 Answers1

6

In your code, p and s are the same objects.
It means that p == s will return true.

The data will be stored in p.series_list.
You can get your y-axis data in p.series_list[1][:y] for line plot, p.series_list[2][:y] for scatter plot.

Now just slightly modify the original code!
First, remove s and use p only.
Second, in the push!() function, the 2nd argument is given to indicate the data index we want to append new data.

f = x->x*x
g = x->f(x)+.2*randn()
p = plot(-1:.1:0, f, ylim=(-1,2), c=:blue)
scatter!(-1:.1:0, g, c=:red)

anim = Animation()
for i=1:10
    x = i/10
    push!(p, 1, x, f(x))
    push!(p, 2, x, g(x))
    frame(anim)
end
gif(anim, "test.gif", fps=2)
Pei Huang
  • 344
  • 1
  • 6
  • Ok, thanks, that works! I didn't know about `series_list`. Is there a way to get a handle to a particular line and modify that? The indexing-solution seems to be a little bit error-prone: just imagine swapping plot and scatter, or inserting a third plot between the two - the hard-coded indexing always needs to be updated. Some kind of variable would be a lot more convenient. Ideas? – mattu Sep 06 '19 at 23:42
  • Sorry, I don't know what the best answer is. In my opinion, (1) you can use a dictionary to create a link between your plot and the index. (2) use the array to store the data and make a new plot every round in the loop. – Pei Huang Sep 07 '19 at 06:35