user2153868
user2153868

Reputation:

What I think should be a simple plot

So basically I am trying to plot a graph with n on my x axis and r on my y axis

So for n=1 it has r=1, n=2 it has r=2, n=3 it has r=4, n=4 it has 8,.and then i plan to extend it.

I tried this:

import scipy
import scipy.linalg
import numpy as np
from matplotlib import pyplot as plt


for n in range(1,5):
    A=np.identity(n)
    for i in range(0,n):
        for j in range(0,i):
            A[i,j]=-1
    A[:,n-1]=1
    x=np.random.randn(n,1)
    b=A*x
    P, L, U = scipy.linalg.lu(A)
    print A
    r=U.max()/A.max()
    print r
    print n
    plt.plot(n,r)
    plt.show()

But it only plots the greatest value of n against the corresponding value of r rather than all values of n. Not sure what I'm doing wrong.

Thanks in advance

Upvotes: 0

Views: 81

Answers (3)

pelson
pelson

Reputation: 21839

I'm not sure if this is what you want (reading your description, I think it is, but looking at your code it looks like you're trying to do something altogether more difficult).

If you're really trying to get the sequence 1, 2, 4, 8, 16, ... I'd encourage you to work on the whole array in one operation, rather than using a for loop. It's more expressive and is much quicker for large arrays.

Anyway:

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> 
>>> n = np.arange(5)
>>> r = 2 ** n
>>> r
array([ 1,  2,  4,  8, 16])
>>> plt.plot(n, r, 'ob')
[<matplotlib.lines.Line2D object at 0x102d8ee10>]
>>> plt.show()

mpl output

Upvotes: 0

Robbert
Robbert

Reputation: 2724

plt.plot() can plot lines and markers. By default it will plot lines only. You only give a single point so no lines can be drawn and the markers won't be drawn. To turn on the markers set the attribute marker="o": plt.plot(x, y, markers="o"). If you want a line plot, you'll have to make lists of n and r and plot those. For a list with markers: http://matplotlib.org/api/artist_api.html#matplotlib.lines.Line2D.set_marker

Also, you may want to take plt.show() out of the for-loop. It makes an updated figure for every iteration, I'm not sure if you want that.

Upvotes: 1

Francesco Montesano
Francesco Montesano

Reputation: 8658

you first need to create the array to plot and then plot it

rr, nn = [], []
for n in range(1,5):
    A=np.identity(n)
    for i in range(0,n):
        for j in range(0,i):
            A[i,j]=-1
    A[:,n-1]=1
    x=np.random.randn(n,1)
    b=A*x
    P, L, U = scipy.linalg.lu(A)
    print A
    r=U.max()/A.max()
    print r
    print n
    rr.append(r)
    nn.append(n)

plt.plot(nn,rr)
plt.show()

The way you do creates a new plot with one point each loop.

Besides, if you plan to increase n, I suggest to check for more efficient ways of loopings (e.g. list comprehension or itertools)

Upvotes: 0

Related Questions