Ben Reed
Ben Reed

Reputation: 93

Converting Numpy Array Element to String: TypeError: bad operand type for unary +: 'str'

I am writing a code using Python 2.7 which reads in multiple data files and plots from them. The relivant part of the code is as follows:

N = np.asarray([[10],[20],[30],[40],[50],[60],[70],[80],[90],[100]])
Num = np.transpose(N)
NumberOfFiles = np.size(Num)
Files = np.empty(NumberOfFiles,dtype=str)
Files = ['NumberOfBottomLayers/TM_O_trans_combined'+str(Num[0,i])+'.txt' for 
i in range(NumberOfFiles)]

StopBand = np.empty([NumberOfFiles,2],dtype=float)

for i in range(NumberOfFiles):
    Data = np.loadtxt(Files[i],dtype='float')
    #lambda, Trans, TransPhase, Ref, RefPhase

    Lambda = Data[:,0] #wavelegth of light
    R = Data[:,3]   #reflection coefficient

    plt.figure(figsize=(12,6))
    plt.plot(Lambda,R)
    plt.plot((780,905),(0.9,0.9),color = 'r')
    plt.xlabel('Wavelegth/ um')
    plt.ylabel('Reflection Coefficient')
    plt.minorticks_on()
    plt.grid(which='both')
    plt.xlim(788,902)
    plt.ylim(0,1.1)
    plt.title('Number of layers bellow cavity = ',+str(Num[0,i]))
    plt.show()

At the line plt.title('Number of layers bellow cavity = ',+str(Num[0,i])) I get an error reading 'TypeError: bad operand type for unary +: 'str''. Does anyone know what is causing this?

Upvotes: 0

Views: 444

Answers (2)

Ramon Crehuet
Ramon Crehuet

Reputation: 4017

You can also use format, which surprisingly ;-) allows you to formats the numbers. For example:

plt.title('Number of layers bellow cavity = {:4d}'.format(Num[0,i]))

Upvotes: 0

Allen Qin
Allen Qin

Reputation: 19947

Should it be?

plt.title('Number of layers bellow cavity = '+str(Num[0,i]))

Upvotes: 1

Related Questions