def plotWindVectorsOnMap(date, showIt=True): from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import wUUtils as Util # setup Lambert Conformal basemap. m = Basemap(width=3200000,height=2500000,projection='lcc', resolution='i',lat_1=45.,lat_0=43.6,lon_0=-80.) # draw coastlines. m.drawcoastlines() m.drawcountries() m.drawstates() # draw a boundary around the map, fill the background. # this background will end up being the ocean color, since # the continents will be drawn on top. m.drawmapboundary(fill_color='aqua') # fill continents, set lake color same as ocean color. m.fillcontinents(color='wheat',lake_color='aqua') # get city locations (Toronto, Montreal, Detroit) cityName = Util.getStationList() lon, lat = Util.getStationLonLat(cityName) # convert to map projection coords. # Note that lon,lat can be scalars, lists or numpy arrays. xpt,ypt = m(lon,lat) m.plot(xpt,ypt,'bo') # plot a blue dot there # compute wind vectors windX = Util.loadDailyVariable(cityName, date, 'WindMeanX') windY = Util.loadDailyVariable(cityName, date, 'WindMeanY') for icity in range(len(cityName)): stretch = 20000 dx, dy = stretch*windX[icity], stretch*windY[icity] plt.arrow(xpt[icity],ypt[icity],dx,dy,color='r',width=12000,head_length=40000,head_width=40000) plt.text(xpt[icity]+30000,ypt[icity]+20000,cityName[icity], size='large') plt.title("Daily-mean wind: " + date) if showIt: plt.show()
def contourPlotMeanVarOnMap(variable, startDate, endDate, \ npts = 20, ncntrs = 10, \ width_fac = 16, height_fac = 12): import numpy as np import wUUtils as Util import matplotlib.pyplot as plt import scipy.interpolate from mpl_toolkits.basemap import Basemap # open new figure window plt.figure() # setup Lambert Conformal basemap. m = Basemap(width=width_fac*100000,height=height_fac*100000, \ projection='lcc', resolution='i', \ lat_1=45.,lat_0=43.6,lon_0=-82.) # draw coastlines. m.drawcoastlines() m.drawcountries() m.drawstates() # draw a boundary around the map, fill the background. # this background will end up being the ocean color, since # the continents/data will be drawn on top. m.drawmapboundary(fill_color='aqua') # load data stations = Util.getStationList() lon, lat = Util.getStationLonLat(stations) data = [] for station in stations: vals = Util.loadDailyVariableRange(station, startDate, endDate, \ variable, castFloat=True) data.append(np.mean(vals)) # print(zip(stations,data)) # convert data to arrays: x, y, z = np.array(lon), np.array(lat), np.array(data) # map data points to projection coordinates xmap, ymap = m(x,y) # Set up a regular grid of interpolation points xi, yi = np.linspace(x.min(), x.max(), npts), \ np.linspace(y.min(), y.max(), npts) # map regular lon-lat grid to projection coordinates xi, yi = m(*np.meshgrid(xi,yi)) # Interpolate data to projected regular grid # function is one of 'linear', 'multiquadric', 'gaussian', # 'inverse', 'cubic', 'quintic', 'thin_plate' rbf = scipy.interpolate.Rbf(xmap, ymap, z, \ function='linear') zi = rbf(xi, yi) # draw filled contours cs = m.contourf(xi,yi,zi,ncntrs,cmap=plt.cm.jet) # plot circles at original (projected) data points m.scatter(xmap,ymap,c=z) # add colorbar. cbar = m.colorbar(cs,location='bottom',pad="5%") cbar.set_label(variable) plt.title(variable + " -- Mean " + startDate + " to " + endDate) # display plot plt.show()
def contourPlotVarOnMapFrame(variable, date, \ contours, npts = 20, \ figname='figure', frameNum=0, \ title='Data', units='units', \ width_fac = 16, height_fac = 12): import wUUtils as Util stations = Util.getStationList() data = Util.loadDailyVariable(stations, date, variable) contourPlotDataOnMapFrame(data, contours, npts, \ figname, frameNum, title, \ units, width_fac, height_fac)
def plotMeanWindVectorsOnMap(startDate, endDate, showIt=True): import numpy as np import wUUtils as Util from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt # setup Lambert Conformal basemap. m = Basemap(width=3200000,height=2500000,projection='lcc', resolution='i',lat_1=45.,lat_0=43.6,lon_0=-80.) # draw coastlines. m.drawcoastlines() m.drawcountries() m.drawstates() # draw a boundary around the map, fill the background. # this background will end up being the ocean color, since # the continents will be drawn on top. m.drawmapboundary(fill_color='aqua') # fill continents, set lake color same as ocean color. m.fillcontinents(color='wheat',lake_color='aqua') # get station locations (Toronto, Montreal, Detroit) stations = Util.getStationList() lon, lat = Util.getStationLonLat(stations) # convert to map projection coords. # Note that lon,lat can be scalars, lists or numpy arrays. xpt,ypt = m(lon,lat) m.plot(xpt,ypt,'bo') # plot a blue dot there # calculate mean wind at each station windX = [] windY = [] for station in stations: wX = Util.loadDailyVariableRange(station, startDate, endDate, \ 'WindMeanX', castFloat=True) windX.append(np.mean(wX)) wY = Util.loadDailyVariableRange(station, startDate, endDate, \ 'WindMeanY', castFloat=True) windY.append(np.mean(wY)) for istation in range(len(stations)): stretch = 50000 dx, dy = stretch*windX[istation], stretch*windY[istation] plt.arrow(xpt[istation],ypt[istation],dx,dy,color='r',width=12000,head_length=40000,head_width=40000) plt.text(xpt[istation]+30000,ypt[istation]+20000,stations[istation], size='large') plt.title("Time-mean Wind: " + startDate + " to " + endDate) if showIt: plt.show()
def plotAdvectionOnMap(targetStation, variable, date, \ width_fac = 16, height_fac = 12): from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import wUAdvection as Adv import wUUtils as Util # setup Lambert Conformal basemap. m = Basemap(width=width_fac*100000,height=height_fac*100000, \ projection='lcc', resolution='i', \ lat_1=45.,lat_0=43.6,lon_0=-82.) # draw coastlines. m.drawcoastlines() m.drawcountries() m.drawstates() # draw a boundary around the map, fill the background. # this background will end up being the ocean color, since # the continents will be drawn on top. m.drawmapboundary(fill_color='aqua') # fill continents, set lake color same as ocean color. m.fillcontinents(color='wheat',lake_color='aqua') # get station locations (Toronto, Montreal, Detroit) stations = Util.getStationList() lon, lat = Util.getStationLonLat(stations) # convert to map projection coords. # Note that lon,lat can be scalars, lists or numpy arrays. xpt,ypt = m(lon,lat) m.plot(xpt,ypt,'bo') # plot a blue dot there # compute advection arrows between all other cities # and the target station for istation in range(len(stations)): if stations[istation] != targetStation: # print(targetStation, stations[istation], variable, date, date) dD, uVec = Adv.dDeriv(targetStation, stations[istation], variable, \ date, nextDay(date)) stretch = 2500 dD = stretch*dD[0] dx, dy = dD*uVec plt.arrow(xpt[istation],ypt[istation],dx,dy,color='r',width=12000,head_length=40000,head_width=40000) for istation in range(len(stations)): plt.text(xpt[istation]+30000,ypt[istation]+20000,stations[istation]) plt.show()
def plotStationsOnMap(showIt=True): import wUUtils as Util from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt # setup Lambert Conformal basemap. m = Basemap(width=3200000,height=2500000,projection='lcc', resolution='i',lat_1=45.,lat_0=43.6,lon_0=-81.) # draw coastlines. m.drawcoastlines(color='gray') m.drawcountries(color='gray') m.drawstates(color='gray') # draw a boundary around the map, fill the background. # this background will end up being the ocean color, since # the continents will be drawn on top. m.drawmapboundary(fill_color='lightblue') # fill continents, set lake color same as ocean color. m.fillcontinents(color='navajowhite',lake_color='lightblue') # plot city locations cityName = Util.getStationList() lon, lat = Util.getStationLonLat(cityName) # convert to map projection coords. # Note that lon,lat can be scalars, lists or numpy arrays. xpt,ypt = m(lon,lat) m.plot(xpt,ypt,'bo') # plot a blue dot there for icity, city in enumerate(cityName): if city == 'KBUF': xoff, yoff = 20000, -40000 elif city == 'CYOW': xoff, yoff = -100000, 23000 else: xoff, yoff = 20000, 20000 plt.text(xpt[icity]+xoff,ypt[icity]+yoff, \ city, \ fontweight='bold', \ fontsize='medium', \ color='navy') if showIt: plt.show()
def collectAllStats(stationList = None): import wUUtils as Util import wUnderground as wU import os if not os.path.exists('CSV_DATA'): os.mkdir('CSV_DATA') #stations = ['CYYZ', 'CYUL'] if stationList == None: stations = Util.getStationList() else: stations = stationList for station in stations: print('Processing ' + station) # open file for csv output outfile = open('CSV_DATA/' + station + '.csv','w') # calculate summary statistics dates, data = wU.getJSONFolder(station) TimeZone = getTimeZoneOffset(data) TempMean = dailyMean(data,'TemperatureC') TempMin, TempMinTime = dailyMax(data,'TemperatureC',-1) TempMax, TempMaxTime = dailyMax(data,'TemperatureC',1) TotalPrecip = dailySum(data,'Precipitationmm') VisibilityMean = dailyMean(data,'VisibilityKm') PressMean = dailyMean(data, 'Sea Level PressurehPa') PressMin, PressMinTime = dailyMax(data,'Sea Level PressurehPa',-1) PressMax, PressMaxTime = dailyMax(data,'Sea Level PressurehPa',1) HumidityMean = dailyMean(data,'Humidity') WindMaxSpd, WindMaxDir, WindMaxTime = dailyMaxWind(data) addWindVectors(data) WindMeanX = dailyMean(data,'xSpeed') WindMeanY = dailyMean(data,'ySpeed') headString = 'date, TimeZone, TempMean, TempMin, TempMinTime, ' \ + 'TempMax, TempMaxTime, TotalPrecip, VisibilityMean, ' \ + 'PressMean, PressMin, PressMinTime, ' \ + 'PressMax, PressMaxTime, HumidityMean, ' \ + 'WindMaxSpd, WindMaxDir, WindMaxTime, ' \ + 'WindMeanX, WindMeanY' # print(headString) outfile.write(headString + '\n') for ii, dd in enumerate(dates): dataString = dd.isoformat() + ', ' dataString += unicode(TimeZone[ii]) + ', ' dataString += unicode('%.2f' % TempMean[ii]) + ', ' dataString += unicode(TempMin[ii]) + ', ' dataString += unicode(TempMinTime[ii]) + ', ' dataString += unicode(TempMax[ii]) + ', ' dataString += unicode(TempMaxTime[ii]) + ', ' dataString += unicode(TotalPrecip[ii]) + ', ' dataString += unicode('%.1f' % VisibilityMean[ii]) + ', ' dataString += unicode('%.0f' % PressMean[ii]) + ', ' dataString += unicode(PressMin[ii]) + ', ' dataString += unicode(PressMinTime[ii]) + ', ' dataString += unicode(PressMax[ii]) + ', ' dataString += unicode(PressMaxTime[ii]) + ', ' dataString += unicode('%.0f' % HumidityMean[ii]) + ', ' dataString += unicode(WindMaxSpd[ii]) + ', ' dataString += unicode(WindMaxDir[ii]) + ', ' dataString += unicode(WindMaxTime[ii]) + ', ' dataString += unicode('%.2f' % WindMeanX[ii]) + ', ' dataString += unicode('%.2f' % WindMeanY[ii]) # write daily summary to csv file outfile.write(dataString + '\n') # print(dataString) outfile.close()
def VariableWithInset(data, insetData, \ contours, npts = 20, \ figname='figure', frameNum=0, \ title='Data', units='units', \ width_fac = 16, height_fac = 12): import numpy as np import wUUtils as Util import matplotlib.pyplot as plt import scipy.interpolate from mpl_toolkits.basemap import Basemap # open new figure window fig = plt.figure() # get station locations lon, lat = Util.getStationLonLat(Util.getStationList()) # compute centre of lon/lat set lon0, lat0 = 0.5*(np.min(lon)+np.max(lon)), \ 0.5*(np.min(lat)+np.max(lat)) # print('centre at: ', lon0, lat0) # open new figure window plt.figure() # setup Lambert Conformal basemap. m = Basemap(width=width_fac*100000,height=height_fac*100000, \ projection='lcc', resolution='i', \ lat_1=45.,lat_0=lat0,lon_0=lon0) # draw coastlines. m.drawcoastlines() m.drawcountries() m.drawstates() # draw a boundary around the map, fill the background. # this background will end up being the ocean color, since # the continents/data will be drawn on top. m.drawmapboundary(fill_color='aqua') # load data stations = Util.getStationList() lon, lat = Util.getStationLonLat(stations) # convert data to arrays: x, y, z = np.array(lon), np.array(lat), np.array(data) # print('\nmain axes:') # print(data) # map data points to projection coordinates xmap, ymap = m(x,y) # Set up a regular grid of interpolation points xi, yi = np.linspace(x.min(), x.max(), npts), \ np.linspace(y.min(), y.max(), npts) # map regular lon-lat grid to projection coordinates xi, yi = m(*np.meshgrid(xi,yi)) # Interpolate data to projected regular grid # function is one of 'linear', 'multiquadric', 'gaussian', # 'inverse', 'cubic', 'quintic', 'thin_plate' rbf = scipy.interpolate.Rbf(xmap, ymap, z, \ function='linear') zi = rbf(xi, yi) # draw filled contours cs = m.contourf(xi,yi,zi,levels=contours,cmap=plt.cm.jet) # add colorbar. cbar = m.colorbar(cs,location='bottom',pad="5%") cbar.set_label(units) plt.title(title) # create insets for iax in range(len(insetData)): corner = 0.65-0.22*iax ax1 = plt.axes([0.7, corner, 0.2, 0.2]) m1 = Basemap(width=width_fac*100000,height=height_fac*100000, \ projection='lcc', resolution='i', \ lat_1=45.,lat_0=lat0,lon_0=lon0) # draw coastlines. m1.drawcoastlines() m1.drawcountries() m1.drawstates() # draw a boundary around the map, fill the background. # this background will end up being the ocean color, since # the continents/data will be drawn on top. m1.drawmapboundary(fill_color='aqua') # convert data to arrays: x, y, z = np.array(lon), np.array(lat), np.array(insetData[iax]) # print('\niax ' + str(iax) + ':') # print(insetData[iax]) # map data points to projection coordinates xmap, ymap = m1(x,y) # Set up a regular grid of interpolation points xi, yi = np.linspace(x.min(), x.max(), npts), \ np.linspace(y.min(), y.max(), npts) # map regular lon-lat grid to projection coordinates xi, yi = m1(*np.meshgrid(xi,yi)) # Interpolate data to projected regular grid # function is one of 'linear', 'multiquadric', 'gaussian', # 'inverse', 'cubic', 'quintic', 'thin_plate' rbf1 = scipy.interpolate.Rbf(xmap, ymap, z, \ function='linear') zi = rbf1(xi, yi) # draw filled contours cs1 = m1.contourf(xi,yi,zi,levels=contours,cmap=plt.cm.jet) # save plot filename = '%s_frame_%03d.png' % (figname, frameNum) # print('saving file: ' + filename) plt.savefig(filename, bbox_inches='tight') plt.close()