from __future__ import (absolute_import, division, print_function) import matplotlib.pyplot as plt import iris import iris.quickplot as qplt import iris.plot as iplt fname = iris.sample_data_path('air_temp.pp') temperature_cube = iris.load_cube(fname) # Get the Purples "Brewer" palette. brewer_cmap = plt.get_cmap('brewer_Purples_09') # Draw the contours, with n-levels set for the map colours (9). # NOTE: needed as the map is non-interpolated, but matplotlib does not provide # any special behaviour for these. qplt.contourf(temperature_cube, brewer_cmap.N, cmap=brewer_cmap) # Add a citation to the plot. iplt.citation(iris.plot.BREWER_CITE) # Add coastlines to the map created by contourf. plt.gca().coastlines() plt.show()
import matplotlib.cm as mpl_cm import matplotlib.pyplot as plt import iris import iris.quickplot as qplt import iris.plot as iplt fname = iris.sample_data_path('air_temp.pp') temperature_cube = iris.load_cube(fname) # Load a Cynthia Brewer palette. brewer_cmap = mpl_cm.get_cmap('brewer_RdBu_11') # Draw the contour with 25 levels qplt.contourf(temperature_cube, 25, cmap=brewer_cmap) # Add a citation to the plot. iplt.citation(iris.plot.BREWER_CITE) # Add coastlines to the map created by contourf plt.gca().coastlines() plt.show()
def compare_variable(varname, limits, scaling, units): varname = varname[0] def open_variable(veg): annual_average, grid = loadFile(veg, varname, 2000, 1) annual_average[:,:,:] = 0.0 TS = np.zeros([len(years)*12]) t = 0 for y in years: for m in range(1,13): dat, nn = loadFile(veg, varname, y, m, grid = grid) annual_average = annual_average + dat TS[t] = global_total(dat) t = t + 1 annual_average = annual_average * scaling / t fname = arr_output_dir + veg + '_' + varname + '.nc' output_file(fname, varname, annual_average) TS = TS * scaling /(12 * 1000000000000.0) return(fname, TS) aa1, ts1 = open_variable(veg_dir[0]) aa2, ts2 = open_variable(veg_dir[1]) ############# ## Plot ## ############# ## setup plot git = 'repo: ' + git_info.url + '\n' + 'rev: ' + git_info.rev crs_latlon = ccrs.PlateCarree() crs_proj = ccrs.Robinson() nz = iris.load_cube(aa1).shape[0] if nz== 5: figsize = (28, 12) fontsize = 16 px = 3 py = 5 labs = [['BL'],['NL'],['C3'],['C4'],['Shrub']] ndiagnose_lims = 6 elif nz == 4: figsize = (20, 12) fontsize = 16 px = 3 py = 4 labs =[['DPM'], ['RPM'], ['BIO'], ['HUM']] ndiagnose_lims = 6 elif nz == 1: figsize = (12, 8) fontsize = 20 px = 2 py = 2 labs = [['']] ndiagnose_lims = 6 else: browser() cmap1 = mpl_cm.get_cmap('brewer_YlGn_09') cmap2 = mpl_cm.get_cmap('brewer_RdYlBu_11') #revserse #cmap2 = reverse_colourmap(cmap2) dcmap = mpl_cm.get_cmap('brewer_PRGn_11') ## Plot maps def plot_map(fname , limits, title, ssp, extend = 'max'): if len(fname) == 2: plotable = [iris.load_cube(i) for i in fname] plotable = plotable[1] - plotable[0] else: plotable = iris.load_cube(fname) nz = iris.load_cube(aa1).shape[0] ssp = (ssp - 1) * nz for i in range(0, nz): ssp = ssp + 1 print(ssp) ax = fig.add_subplot(px, py, ssp, projection = crs_proj) ax.set_extent((-180, 170, -65, 90.0), crs = crs_latlon) ax.coastlines(linewidth = 0.5, color = 'navy') ax.gridlines(crs = crs_latlon, linestyle = '--') if diagnose_lims: limits = hist_limits(plotable[i], ndiagnose_lims) if limits[0] < 0.0: if limits[-1] <= 0.0: cmap = cmap2 #norm = colours.BoundaryNorm(boundaries = np.append(limits, 0.01), ncolors = 8) norm = colours.BoundaryNorm(boundaries = limits, ncolors = 7) else: cmap = dcmap norm = colours.BoundaryNorm(boundaries = limits, ncolors = 12) #norm = MidpointNormalize(midpoint=0.) else: cmap = cmap1 norm = colours.BoundaryNorm(boundaries = limits, ncolors = 8) plt.gca().coastlines() cbi = qplt.contourf(plotable[i], limits, cmap = cmap, extend = extend, norm = norm) #plt.colorbar(cbi) titlei = title + labs[i][0] plt.title(titlei) fig = plt.figure(figsize = figsize) fig.suptitle(varname, fontsize = fontsize) plot_map(aa1, limits[0], 'Veg1', 1) plot_map(aa2, limits[0], 'Veg2', 2) plot_map([aa1, aa2], limits[1], 'Difference', 3, 'both') iplt.citation(git) ## line plot if nz == 1: ax = fig.add_subplot(224) t = np.arange(years[0], years[-1] + 1, 1.0/12.0) ax.get_xaxis().get_major_formatter().set_scientific(False) plt.plot(t, ts1, 'r', label="Veg 1") plt.plot(t, ts2, 'b--', label="Veg 2") #plt.plot(t, ts1, 'r', t, ts2, 'b--') plt.ylabel(units) plt.legend(bbox_to_anchor=(0., 0.898, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) fig_name = 'figs/' + varname + '_veg2-veg1_comparison.pdf' plt.savefig(fig_name, bbox_inches = 'tight')
def plot_map_helper(cube, title_name, save_out=False): """ Plot (and save) maps given date and variable in cube :param cube: data :param title_name: title of graph :param save_out: if set, then saves to png file """ # Plot the graph fig, ax = plt.subplots(figsize=(11, 4)) # Get the Purples "Brewer" palette for plot brewer_cmap = plt.get_cmap('brewer_Purples_09') # Draw the contours, with n-levels set for the map colours lats = cube.coord('latitude') lons = cube.coord('longitude') masked_array = np.ma.array(cube.data, mask=np.isnan(cube.data)) # Get max and min of lons and lats lon_min, lon_max, lat_min, lat_max = min(lons.points), max( lons.points), min(lats.points), max(lats.points) # Only set if one lat/lon frame, cf = False, None try: # Overlay world map m = Basemap(projection='mill', lat_ts=10, resolution='c', ax=ax) # Plot actual data scat = False if len(lons.points) < 30 or len(lats.points) < 30: scat = True if len(lons.points) == 1 and len(lats.points) == 1: frame = True label = "Point (" + str(lons.points[0]) + ", " + str( lons.points[0]) + ")" m.scatter(lons.points, lats.points, latlon=True, s=20, c='blue', marker='o', label=label) else: m.scatter(lons.points, lats.points, latlon=True, s=20, c='blue', marker='o') else: # Overlay world map m = Basemap(projection='mill', lat_ts=10, llcrnrlon=lon_min, \ urcrnrlon=lon_max, llcrnrlat=lat_min, urcrnrlat=lat_max, \ resolution='c', ax=ax) x, y = m(*np.meshgrid(lons.points, lats.points)) cf = m.contourf(x, y, masked_array, shading='flat', cmap=brewer_cmap) m.drawcoastlines() m.drawparallels(np.arange(-90., 90., 30.), labels=[1, 0, 0, 0], ax=ax) m.drawmeridians(np.arange(-180., 180., 60.), labels=[0, 0, 0, 1], ax=ax) except Exception as err: print("ERROR in function plot_map: " + str(err)) plt.close(fig) return None if not scat: fig.colorbar(cf, ax=ax, label=cube.units) # Add a citation to the plot. iplt.citation(iris.plot.BREWER_CITE) ax.set_title(title_name) # Have legend if point if frame: plt.legend(frameon=True) if save_out: title_name = make_into_file_name(title_name) plt.savefig(os.path.join(directories.ANALYSIS, title_name)) print("Map is saved in the " + directories.ANALYSIS + " folder as a png file.")
def test_figure(self): iplt.citation(self.text, figure=self.figure) self.check_graphic()
def test_axes(self): iplt.citation(self.text, axes=self.axes) self.check_graphic()
def test(self): iplt.citation(self.text) self.check_graphic()
lonLat[1:, 0] = round2grid(lonLat[1:, 0], lon) lonLat[1:, 1] = round2grid(lonLat[1:, 1], lat) ################################################# ## Output ## ################################################# git = 'repo: ' + git_info.url() + '\n' + 'rev: ' + git_info.rev ## Write to file np.savetxt(file_out, lonLat[:,[1,0]], fmt = '%.4f', delimiter = '\t') ## Plot crs_latlon = ccrs.PlateCarree() crs_proj = ccrs.Robinson() fig = plt.figure() ax = plt.axes(projection = crs_proj) ax.set_extent((-180, 170, -65, 90.0), crs=crs_latlon) ax.coastlines(linewidth=0.75, color='navy') ax.gridlines(crs=crs_latlon, linestyle='--') iplt.contourf(mask, [-0.5, 0.5, 1.5], colors=('#6666ff', '#acff88', 'b')) lonLat = crs_proj.transform_points(crs_latlon,lonLat[1:,0],lonLat[1:,1])# lonLat[1:,] plt.scatter(lonLat[:,0],lonLat[:,1], c = '#aa0000', marker = 'x') plt.gca().coastlines() iplt.citation(git) plt.savefig(fig_name, bbox_inches='tight')