user2095624
user2095624

Reputation: 381

Python plotting with for loop

I am a newbie in python and plotting stuff. I was trying to generate a plot using the following script. The goal was to draw a plot of Q vs F for all values.

from pylab import *

n = 5
D = 13
B = 10

x = linspace(-6.5, 6.5, 1000)
y = 1/sqrt(2*pi)*exp(-(x)**2/2)

for i in range(1,n):
    F = sum(y*cos(2*pi*i*x/D)*exp(-i**2*B/(4*D**2)))
    print F

for j in range(1,n):
    Q = 2*pi*(j)/D
    print Q

plt.plot(Q,F,'rx')
plt.show()

When I am running the script, it plots only one data point instead of all. I am sure, I did some stupid mistake. Someone could pls help me out here? Thank you.

Upvotes: 0

Views: 10293

Answers (2)

will
will

Reputation: 10650

It's because you're setting F and Q equal to the value on each loop, rather than appending the value to the end of an array.

from pylab import *

n = 5
D = 13
B = 10

x = linspace(-6.5, 6.5, 1000)
y = 1/sqrt(2*pi)*exp(-(x)**2/2)

F,Q = [],[]

for i in range(1,n):
    F.append(sum(y*cos(2*pi*i*x/D)*exp(-i**2*B/(4*D**2))))
    Q.append(2*pi*(j)/D)

plt.plot(Q,F,'rx')
plt.show()

Upvotes: 2

John Lotacs
John Lotacs

Reputation: 1254

You are only setting Q, F equal in the loops.

from pylab import *

n = 5
D = 13
B = 10

x = linspace(-6.5, 6.5, 1000)
y = 1/sqrt(2*pi)*exp(-(x)**2/2)

for i in range(1,n):
    F.append(sum(y*cos(2*pi*i*x/D)*exp(-i**2*B/(4*D**2))))
    print F
    Q.append(2*pi*(j)/D)
    print Q

plt.plot(Q,F, 'rx')    
plt.show()

Upvotes: 1

Related Questions