0

I have the following simple code:

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


for i in range(10):

        M=np.array([[i**2,0],[0,i**3]]) # 2 x 2 matrix
        eval,evec=np.linalg.eig(M)

        # Plotting first and second eigenvalues
        # Style 1
        plt.plot(i,eval[0])
        plt.plot(i,eval[1])
                         # Doesn't work
        # Style 2
        plt.plot(i,eval[0], '-r')
        plt.plot(i,eval[1], '-b')
                         # Doesn't work

        # Style 3
        plt.plot(i,eval[0], 'ro-')
        plt.plot(i,eval[1], 'bs')
                        # Does work

plt.xlabel('x')
plt.ylabel('y')
plt.savefig('plot.png')
plt.show()

While plotting with three different styles, only the third style (i.e. point or scatter plots) works successfully. Hence I have very limited customization options. Any way out?

Also, can these three differently styled plots be saved into three different files without creating separately three for-loops?

Output attached below. enter image description here

hbaromega
  • 2,317
  • 2
  • 24
  • 32
  • I think it doesn't work because the connected lines expect to have an array of values, but since you're code is in a loop it will only get one value in the call to plot. One solution would be to move the plotting outside the loop and collect the calculated values in an array and then pass them to the plotting function. Style 1 and Style 2 expect to draw lines connecting the points. – iamchoosinganame May 22 '19 at 16:14
  • You mean by saving it into a data file and then reading it and plotting the data? – hbaromega May 22 '19 at 16:17
  • You don't need to save it to a file, you could just collect the results of the computation in an array or list and then pass that to the plot function. – iamchoosinganame May 22 '19 at 16:25

1 Answers1

0

Move the plotting outside the loop where computation occurs. In order to plot connected lines the plot function is expecting an array of values.

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

yvals=[]
for i in range(10):

    M=np.array([[i**2,0],[0,i**3]]) # 2 x 2 matrix
    eval_,evec=np.linalg.eig(M)
    yvals.append(eval_)

yvals=np.array(yvals)
xvals=np.array(range(10))
plt.plot(xvals,yvals[:,0],'-r')
plt.plot(xvals,yvals[:,1],'-b')

All of your plotting styles should work now.

iamchoosinganame
  • 1,090
  • 6
  • 15