Ask Your Question

# Add graphs produced by a for loop?

Anonymous

How can I plot all my graphs that i produce from a for loop on top of each other? I have this:

for i in range(-3,3,1):

p1 = parametric_plot((t,i),(t,-5,5),color="red")

p2 = parametric_plot((i,t),(t,-5,5),color="gray")

show(p1+p2)


I just get all the graphs one after the other.

edit retag close merge delete

## Comments

By the way, you can do for i in [-3..2] if you are looking for a more intuitive way to write that range.

( 2012-06-08 13:37:38 +0200 )edit

## 3 Answers

Sort by » oldest newest most voted

Try this. Use p1=p1+ ... instead of p1 = ...

t=var('t')
for i in range(-3,3,1):
p1 = p1+parametric_plot((t,i),(t,-5,5),color="red")
p2 = p2+parametric_plot((i,t),(t,-5,5),color="gray")
show(p1+p2)

more

## Comments

Thanks this is a nice consice way of doing it.

( 2012-06-08 13:35:03 +0200 )edit

You can also replace p1 = p1+... to p1 += ... This just means "add to itself".

( 2012-06-08 19:23:12 +0200 )edit

You'll also need to use Graphics() prior to your for loop to define p1 and p2 to be graphics objects.

t=var('t')
p1=Graphics()
p2=Graphics()
for i in range(-3,3,1):
p1 +=parametric_plot((t,i),(t,-5,5),color="red")
p2 +=parametric_plot((i,t),(t,-5,5),color="gray")
show(p1+p2)

more

## Comments

Thanks, thats exactly what i was looking for! You have pointed me in the right direction! :)

( 2012-06-08 13:34:14 +0200 )edit

Or you could make the first one i=-3 be outside the loop and then use the += construction in the rest of the loop (which would then be -2 to 3).

( 2012-06-08 13:37:03 +0200 )edit

Just on the off chance that you are trying to just make gridlines, here are some examples from the documentation:

sage: p = polar_plot(2 + 2*cos(x), 0, 2*pi, color=hue(0.3))
sage: p.show(gridlines=True,
...     hgridlinesstyle=dict(color="orange", linewidth=1.0),
...     vgridlinesstyle=dict(color="blue", linestyle=":"))

Change the style of each grid line individually.

sage: x, y = var('x, y')
sage: p = implicit_plot((y^2-x^2)*(x-1)*(2*x-3)-4*(x^2+y^2-2*x)^2,
...             (x,-2,2), (y,-2,2), plot_points=1000)
sage: p.show(gridlines=(
...    [
...     (1,{"color":"red","linestyle":":"}),
...     (0,{"color":"blue","linestyle":"--"})
...    ],
...    [
...     (-1,{"color":"red","linestyle":":"}),
...     (0,{"color":"blue","linestyle":"--"}),
...     (1,{"color":"red","linestyle":":"}),
...    ]
...    ),
...    gridlinesstyle=dict(marker='x',color="black"))


There are pretty finely-grained options available.

more

## Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

## Stats

Asked: 2012-06-08 12:01:40 +0200

Seen: 636 times

Last updated: Jun 08 '12