1

I am trying to use what I learned from plotting multiple plots but whith offset ranges python, but I can't seem to make the appropriate adjustments for my Legendre plotting code:

import numpy as np
import pylab
from numpy.polynomial.legendre import leggauss, legval


def f(x):
    if 0 <= x <= 1:
        return 1
    if -1 <= x <= 0:
        return -1


f = np.vectorize(f)

deg = 1000
x, w = leggauss(deg)  #  len(x) == deg
L = np.polynomial.legendre.legval(x, np.identity(deg))
integral = (L * (f(x) * w)[None,:]).sum(axis=1)
xx = np.linspace(-1, 1, 500000)
csum = []


for N in [5, 15, 25, 51, 97]:
    c = (np.arange(1, N) + 0.5) * integral[1:N]
    clnsum = (c[:,None] * L[1:N,:]).sum(axis = 0)
    csum.append(clnsum)


fig = pylab.figure()
ax = fig.add_subplot(111)


for i in csum:
    ax.plot(x, csum[i])


pylab.xlim((-1, 1))
pylab.ylim((-1.25, 1.25))
pylab.plot([0, 1], [1, 1], 'k')
pylab.plot([-1, 0], [-1, -1], 'k')
pylab.show()

I am using csum to hold each iteration of clnsum for N = 5, 15, 25, 51, 97. Then I want to plot each stored clnsum, but I believe this is where the problem is occurring.

I believe

for i in csum:

is the correct set up but ax.plot(x, csum[i]) must be the wrong way to plot each iteration. At least, this is what I believe, but maybe the whole set up is wrong or faulty.

How can I achieve the plotting of each clnsum for each N?

1 Answer 1

2
for i in csum:
    ax.plot(x, csum[i])

This is where your problem is. i is not an integer, it's an array. You probably mean

for i in range(len(csum)):

You could also do

for y in csum:
    ax.plot(x, y)
Sign up to request clarification or add additional context in comments.

2 Comments

Great thanks. Is one of those options more efficient of faster?
The latter is more "pythonic" and very slightly more efficient (but it doesn't matter for the number you're dealing with).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.