PureLine
PureLine

Reputation: 103

How to generate a series of plot with `for`

I learn to program in Julia language.

I want to test which color is better, so I use the following code:

using Plots
x = 1:10; y = rand(10,2);
for i in [0 0.1 0.2]
    plot(x,y, seriestype=:scatter,background_color=RGB(0.4,0.8,i))
end

How, nothing show.

Can anyone tell me how to generate plot with loop?

P.S.

I have tried another way,

[plot(x,y, seriestype=:scatter,background_color=RGB(0.4,0.8,i)) for i in 0:0.1:1]

Nothing happened with above code.

The following code does not work either:

map(i->plot(x,y, seriestype=:scatter,background_color=RGB(0.4,0.8,i)), [0 0.1 0.2])

Upvotes: 0

Views: 122

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69949

In a script plot is not shown unless you use display function to show it (see section Plotting in scripts here http://docs.juliaplots.org/latest/tutorial/).

You have several options here. This one is the simplest:

for i in [0 0.1 0.2]
    display(plot(x,y, seriestype=:scatter,background_color=RGB(0.4,0.8,i)))
    sleep(1)
end

It will plot your figures in a sequence. I use sleep(1) to make Julia pause between plotting.

Otherwise you can do:

p = [plot(x,y, seriestype=:scatter,background_color=RGB(0.4,0.8,i)) for i in 0:0.1:1]

and then plot your figures from Julia REPL like this:

julia> p[5]

will plot fifth figure. Now you do not have to use display because in REPL it will be invoked anyway as I did not use ; at the end of the line. You could write display(p[5]) to get the same effect.

Finally you can consider saving the figures to PNG file and inspecting them later. You can do it either using p array defined above like this:

foreach(i -> savefig(p[i], "fig$i.png"), eachindex(p))

or in a loop like this:

for i in [0 0.1 0.2]
    p = plot(x,y, seriestype=:scatter,background_color=RGB(0.4,0.8,i))
    savefig(p, "fig$i.png)
end

Upvotes: 2

Related Questions