# ----- DRILL ----- # The csv file temperatures.csv consists of two columns [year, temperature] # corresponding to the change in global temperatures (C) relative to a baseline # from 1880 to 2016. Read this csv file creating two lists consisting of the # year and temperature. Plot the change in temperature as a function of year # and label the axis accordingly. [NOTE: data will be read in as a string] import csv import matplotlib.pyplot as plt with open( 'temperatures.csv' ) as csvfile: csvdata = csv.reader(csvfile) next(csvdata, None) # skip the header T = [] Y = [] for row in csvdata: Y.append( int(row[0]) ) T.append( float(row[1]) ) plt.plot(Y,T) plt.xlabel('year') plt.ylabel('temperature difference (C)') plt.show() # extrapolate changes in temperature import csv import numpy as np from numpy.linalg import inv import matplotlib.pyplot as plt # ----- load year/temperature data ----- with open( 'temperatures.csv' ) as csvfile: reader = csv.reader(csvfile) next(reader, None) # skip the header T = [] Y = [] for row in reader: Y.append( int(row[0]) ) T.append( float(row[1]) ) # ----- fit second-order polynomial ----- # build matrix of years [Y^2 Y 1] a1 = np.matrix(Y) a0 = np.matrix( np.ones(len(Y)) ) a2 = np.power(a1,2) A = np.concatenate( (a2,a1,a0), axis=0 ) A = A.transpose() # build vector of temperatures [T] b = np.transpose( np.matrix(T) ) # least-squares estimate of temperature as a function of year m = inv(A.transpose()*A) * A.transpose() * b # evaluate and plot model estimates for y in range(1880,2100,10): t = m[0]*y*y + m[1]*y + m[2] # evaluate second-order model plt.plot(y,t,'r.') # plot original data plt.plot(Y,T) plt.xlabel('year') plt.ylabel('temperature difference (C)') plt.show()