Fahad
Fahad

Reputation: 29

How can we plot multiple lines of a function with a for loop to minimize the coding?

def k(x,b):
    return x**b

x = np.linspace(0,10,100)

L = k(x,1)
plt.plot(x,L, label = 'n=1')


L2 = k(x,2)
plt.plot(x,L2, label = 'n=2')

plt.show()

I'm trying to plot multiply polynomials of x^b.

I can plot the function for different b values, but I need to make the code more efficient by using a for loop, or a good method to change the b value and then plot them into one graph.

Upvotes: 0

Views: 1066

Answers (3)

Jordan Brière
Jordan Brière

Reputation: 1055

I can plot the function for different b values, but I need to make the code more efficient by using a for loop or a good method to change the b value and then plot them into one graph.

A loop will not make your code more efficient. By definition:

ef·fi·cient

(especially of a system or machine) achieving maximum productivity with minimum wasted effort or expense

A loop, along with your wrappers are wasted efforts. It makes your code much harder to read, maintain, and also more expensive to compute as it means more frames to initialize. As stated in The Zen of Python:

Simple is better than complex.

There is absolutely no reason why you should not simply write:

x = np.linspace(0,10,100)
plt.plot(x, x**1, label='n=1')
plt.plot(x, x**2, label='n=2')

plt.show()

Upvotes: 0

hpaulj
hpaulj

Reputation: 231395

Check the plot docs. I believe y (2nd argument) can be (n,m) shape, where n is the same size as x, and m the number of lines you want to draw:

In [156]: x = np.linspace(0,10,11) 
In [160]: y = x[:,None]**np.array([1,2,3])                                                       
In [161]: y                                                                                      
Out[161]: 
array([[   0.,    0.,    0.],
       [   1.,    1.,    1.],
       [   2.,    4.,    8.],
       [   3.,    9.,   27.],
       [   4.,   16.,   64.],
       [   5.,   25.,  125.],
       [   6.,   36.,  216.],
       [   7.,   49.,  343.],
       [   8.,   64.,  512.],
       [   9.,   81.,  729.],
       [  10.,  100., 1000.]])
In [162]: plt.plot(x, y)                                                                         
Out[162]: 
[<matplotlib.lines.Line2D at 0x7ff738082940>,
 <matplotlib.lines.Line2D at 0x7ff738082a90>,
 <matplotlib.lines.Line2D at 0x7ff738082be0>]

Check the plot docs on how to provide labels for multiple lines.

The y calculation takes advantage of numpy broadcasting, allowing us to work with 2 1d arrays, producing a new 2d array.

Upvotes: 2

Nathan
Nathan

Reputation: 3648

You can do this like this:

def k(x,b):
    return x**b

x = np.linspace(0,10,100)
for n in range(1, 3):
    L = k(x,n)
    plt.plot(x,L, label = f'n={n}')

# To add the legend:
plt.legend()
plt.show()

Resulting figure

Upvotes: 0

Related Questions