Skip to main content

plot_exercise_bradford_data.py


"""
Solution for plotting exercise
1. solve the Numpy challenge : mean temperature
a. read in weather data from Bradford station
skip rows and specify missing_values string as appropriate
b. calculate monthly mean temperature (tmean)
as the average of tmin and tmax
2.plot tmin, tmax and tmean on the same graph
To go further, try plotting only the last 10 years (either subset the arrays
or adjust the limit of the plot).
Author: L J Gregoire
"""
import numpy as np
import matplotlib.pyplot as plt
import datetime
###
# read in Bradford weather data
###
filename='bradforddata.txt'  # put full path to data if needed
data=np.genfromtxt(filename,
           skip_header=7,usecols=(0,1,2,3),
           missing_values='---')
tmax=data[:,2]
tmin=data[:,3]
print tmin[:5]
print tmax[:5]
##########
# caculate mean monthly temperature
# as the average of min and max tempeartures
tmean=(tmin+tmax)/2.
print tmean[:5]
##################
# Plotting results
# convert month and year into dates for the labels
# using the date function of the datetime module
dates=[datetime.date(day=15,month=int(data[i,1]),year=int(data[i,0])) for i in range(len(data[:,0]))]
plt.plot(dates,tmin,'b--',
         dates,tmax,'r--',
         dates,tmean,'k-')
#plt.show()
plt.savefig('bradford_temperature.png')