def main(): # Load data filepath = iris.sample_data_path('orca2_votemper.nc') cube = iris.load_cube(filepath) # Choose plot projections projections = {} projections['Mollweide'] = ccrs.Mollweide() projections['PlateCarree'] = ccrs.PlateCarree() projections['NorthPolarStereo'] = ccrs.NorthPolarStereo() projections['Orthographic'] = ccrs.Orthographic(central_longitude=-90, central_latitude=45) pcarree = projections['PlateCarree'] # Transform cube to target projection new_cube, extent = iris.analysis.cartography.project(cube, pcarree, nx=400, ny=200) # Plot data in each projection for name in sorted(projections): fig = plt.figure() fig.suptitle('ORCA2 Data Projected to {}'.format(name)) # Set up axes and title ax = plt.subplot(projection=projections[name]) # Set limits ax.set_global() # plot with Iris quickplot pcolormesh qplt.pcolormesh(new_cube) # Draw coastlines ax.coastlines() plt.show()
def cosp_plot_column_2D(fnc, varname='equivalent_reflectivity_factor', level=0, column = 0, time = 0): """ Function that plots one column of lat/lon data. """ plt.interactive(True) fig=plt.figure() ax = fig.add_subplot(111) # Read cube z=iris.load(fnc) z=z[0] # Get coords c = z.coord('column') t = z.coord('time') # Select time and column y=z.extract(iris.Constraint(column=c.points[column])) y=y.extract(iris.Constraint(time=t.points[time])) # Select level. Not managed to make constrain with 'atmospheric model level' y=y[level] color_map = mpl_cm.get_cmap('Paired') qplt.pcolormesh(y,cmap=color_map,vmin=-20,vmax=20) plt.gca().coastlines() return
def test_pcolormesh(self): qplt.pcolormesh(self._small()) #cube = self._small() #iplt.orography_at_bounds(cube) self.check_graphic()
def testSetPlotpcolormeshLargeRange(self): cube = iris.load_cube(iris.sample_data_path('air_temp.pp')) plt.subplot(1,2,1) cc.setPlot(cube, "pcolormesh", "brewer_Blues_09", 15, True, 400, 200) plt.subplot(1,2,2) qplt.pcolormesh(cube, cmap="brewer_Blues_09", vmin=200, vmax=400) plt.show()
def testSetPlotpcolormeshPlain(self): cube = iris.load_cube(iris.sample_data_path('air_temp.pp')) plt.subplot(1,2,1) cc.setPlot(cube, "pcolormesh", "Automatic", 15, False, None, None) plt.subplot(1,2,2) qplt.pcolormesh(cube) plt.show()
def test_global_data_same_res(self): src = iris.tests.stock.global_pp() src.coord('latitude').guess_bounds() src.coord('longitude').guess_bounds() res = regrid_area_weighted(src, src) qplt.pcolormesh(res) self.check_graphic()
def test_subsample(self): src = global_pp() grid = src[::2, ::3] result = regrid(src, grid) qplt.pcolormesh(result) qplt.plt.gca().coastlines() self.check_graphic()
def test_global_data_increase_res(self): src = iris.tests.stock.global_pp() src.coord('latitude').guess_bounds() src.coord('longitude').guess_bounds() dest = _resampled_grid(src, 1.5, 1.5) res = regrid_area_weighted(src, dest) qplt.pcolormesh(res) self.check_graphic()
def test_single_boxcar(target_point, tmpfile, source_data_function): '''Smooth a single point''' import iris.quickplot as qplt, matplotlib.pyplot as plt from gridsmoother import GridSmoother import os #lat,lon = target_point dlat = 180. / 1#CUBE_SHAPE[0] dlon = 360. / 1#CUBE_SHAPE[1] print "point lat = %s, lon = %s" % target_point assert int(target_point[0] / dlat) - target_point[0] / dlat < SMALL_NUMBER assert int(target_point[1] / dlon) - target_point[1] / dlon < SMALL_NUMBER print "dlat = %s, dlon = %s" % (dlat, dlon) #centre = (lat,lon)#(dlat / 2., dlon / 2.) source_cube = gen_or_load_2D(tmpfile , [source_data_function], ["unsmoothed data"], {"GS_centre_lat":target_point[0], 'GS_centre_lon':target_point[1]},nlat=180, nlon=360)[0] lat_width = 6. lon_width = 18. print "box car parameters: lat_width %s, lon_width %s" % (lat_width, lon_width) gs = GridSmoother() filename= "boxcar_%s_x_%s.json.gz" % (lon_width,lat_width) if os.path.exists(filename): gs.load(filename) else: gs.build_boxcar_lat_lon(source_cube, lat_width, lon_width) gs.save(filename) smoothed_cube = gs.smooth_2d_cube(source_cube) if PLOT: import cartopy.crs as ccrs fig = plt.figure() subpl = fig.add_subplot(111, projection=ccrs.PlateCarree()) qplt.pcolormesh(smoothed_cube, cmap='Reds') qplt.outline(smoothed_cube) # subpl.add_artist(plt.Circle(target_point, smoothing_width, edgecolor='blue', facecolor='none', transform=ccrs.PlateCarree())) for i, lat in enumerate(smoothed_cube.coord('latitude').points): for j, lon in enumerate(smoothed_cube.coord('longitude').points): if smoothed_cube.data[i, j] > 0: plt.text(lon, lat, smoothed_cube.data[i, j] ** -1, transform=ccrs.PlateCarree(), ha='center', va='center') qplt.plt.gca().coastlines() qplt.show()
def plot_surface(cube, model=''): z = z_coord(cube) positive = z.attributes.get('positive', None) if positive == 'up': idx = np.argmax(z.points) else: idx = np.argmin(z.points) c = cube[idx, ...] c.data = ma.masked_invalid(c.data) t = time_coord(cube) t = t.units.num2date(t.points)[0] qplt.pcolormesh(c) plt.title('{}: {}\nVariable: {} level: {}'.format(model, t, c.name(), idx))
def set_plot(cube, plot_type, cmap, num_contours, contour_labels, colorbar_range): """ Produces a plot object for the desired cube using quickplot. Args: * cube The cube to be plotted. * plot_type String holding the type of plot to be used. Choose from pcolormesh, Contour and Contourf. * cmap String representing the colormap to be used. Can be any of the Brewer Colormaps supported by Iris, or Automatic. * num_contour int holding the number of contours to be plotted. * contour_labels Boolean representing whether the contours on a Contour plot (not contourf) should be labeled. * colorbar_range Dictionary containing ints representing the max and min to which the colorbar will be set. """ # We unpack the colorbar_range dictionary colorbar_max = colorbar_range["max"] colorbar_min = colorbar_range["min"] # We obtain the levels used to define the contours. levels = get_levels(cube, colorbar_max, colorbar_min, num_contours) if plot_type == "Filled Contour": qplt.contourf(cube, num_contours, cmap=get_colormap(cmap), levels=levels, vmax=colorbar_max, vmin=colorbar_min) elif plot_type == "Contour": contours = qplt.contour( cube, num_contours, cmap=get_colormap(cmap), levels=levels, vmax=colorbar_max, vmin=colorbar_min ) if contour_labels: plt.clabel(contours, inline=1, fontsize=8) else: qplt.pcolormesh(cube, cmap=get_colormap(cmap), vmax=colorbar_max, vmin=colorbar_min)
def test_hybrid_height(self): src = self.realistic_cube dest = _resampled_grid(src, 0.7, 0.8) res = regrid_area_weighted(src, dest) self.assertCMLApproxData(res, RESULT_DIR + ('hybridheight.cml',)) # Consider a single slice to allow visual tests of altitudes. src = src[1, 2] res = res[1, 2] qplt.pcolormesh(res) self.check_graphic() plt.contourf(res.coord('grid_longitude').points, res.coord('grid_latitude').points, res.coord('altitude').points) self.check_graphic() plt.contourf(res.coord('grid_longitude').points, res.coord('grid_latitude').points, res.coord('surface_altitude').points) self.check_graphic()
def test_circular_subset(self): src = iris.tests.stock.global_pp() src.coord('latitude').guess_bounds() src.coord('longitude').guess_bounds() dest_lat = src.coord('latitude')[0:40] dest_lon = iris.coords.DimCoord([-15., -10., -5., 0., 5., 10., 15.], standard_name='longitude', units='degrees', coord_system=dest_lat.coord_system) # Note target grid (in -180 to 180) src in 0 to 360 dest_lon.guess_bounds() data = np.zeros((dest_lat.shape[0], dest_lon.shape[0])) dest = iris.cube.Cube(data) dest.add_dim_coord(dest_lat, 0) dest.add_dim_coord(dest_lon, 1) res = regrid_area_weighted(src, dest) qplt.pcolormesh(res) plt.gca().coastlines() self.check_graphic()
def _viz_slice(self, slice, subplot): # Plot a latlon slice in a given subplot position. ax = plt.subplot(*subplot) # If we're using pcolormesh we need bounds if not slice.coord("latitude").has_bounds(): slice.coord("latitude").guess_bounds() slice.coord("longitude").guess_bounds() # How many ticks along the colourbar? # Depends on the number of subplots. if subplot[0] == 1: num_ticks = None elif subplot[0] == 2: num_ticks = 8 elif subplot[0] == 3: num_ticks = 6 else: num_ticks = 5 qplt.pcolormesh(slice, cmap=self.cmap, num_ticks=num_ticks, pad=self.pad) plt.gca().coastlines()
def cosp_plot_column_1D(fnc, varname='equivalent_reflectivity_factor', column = 0, time = 0): """ Function that plots one column of curtain data. """ plt.interactive(True) fig=plt.figure() # Read cube z=iris.load(fnc) z=z[0] # Get coords c = z.coord('column') t = z.coord('time') # Select time and column y=z.extract(iris.Constraint(column=c.points[column])) y=y.extract(iris.Constraint(time=t.points[time])) qplt.pcolormesh(y) return
# <codecell> plt.pcolormesh(lon,lat,ma.masked_invalid(t),vmin=5,vmax=30) plt.title('my plot') # <codecell> #plot with Iris import iris import iris.quickplot as qplt time0=time.time() cube = iris.load_cube(url,'sea_water_potential_temperature') # <codecell> qplt.pcolormesh(cube[-1,-1,:,:]) # <codecell> last_step = cube[-1,-1,:,:] last_step.data = ma.masked_invalid(last_step.data) qplt.pcolormesh(last_step) # <codecell> print cube # <codecell> cube.plot
def test_single_point(target_point, tmpfile, source_data_function, num_expected_distinct_values=2): '''Smooth a single point''' import iris.quickplot as qplt, matplotlib.pyplot as plt from gridsmoother import GridSmoother import os #lat,lon = target_point dlat = 180. / CUBE_SHAPE[0] dlon = 360. / CUBE_SHAPE[1] print "point lat = %s, lon = %s" % target_point assert int(target_point[0] / dlat) - target_point[0] / dlat < SMALL_NUMBER assert int(target_point[1] / dlon) - target_point[1] / dlon < SMALL_NUMBER print "dlat = %s, dlon = %s" % (dlat, dlon) #centre = (lat,lon)#(dlat / 2., dlon / 2.) source_cube = gen_or_load_2D(tmpfile , [source_data_function], ["unsmoothed data"], {"GS_centre_lat":target_point[0], 'GS_centre_lon':target_point[1]})[0] for smoothing_width in np.arange(2.0, 5, 0.5) * dlat: print "smoothing_width: ", smoothing_width gs = GridSmoother() filename = 'smoothing_%s.json.gz' % smoothing_width smoothing_function = lambda s: (s <= smoothing_width) * 1.0 if os.path.exists(filename): gs.load(filename) else: gs.build(source_cube, smoothing_function) gs.save('smoothing_%s.json.gz' % smoothing_width) smoothed_cube = gs.smooth_2d_cube(source_cube) assert np.isclose(smoothed_cube.data.sum(), source_cube.data.sum(), atol=SMALL_NUMBER) #will fail for smoothing functions other than a hard cut off: if num_expected_distinct_values is not None: assert len(set(smoothed_cube.data.ravel().tolist())) == num_expected_distinct_values for i, j in zip(*np.where(smoothed_cube.data > 0.0)): assert smoothing_function(angular_separation(source_cube.coord('latitude').points[i], source_cube.coord('longitude').points[j], *target_point) ) > 0. for i, j in zip(*np.where(smoothed_cube.data == 0.0)): assert smoothing_function(angular_separation(source_cube.coord('latitude').points[i], source_cube.coord('longitude').points[j], *target_point) ) == 0. if PLOT: import cartopy.crs as ccrs fig = plt.figure() subpl = fig.add_subplot(111, projection=ccrs.PlateCarree()) qplt.pcolormesh(smoothed_cube, cmap='Reds') qplt.outline(smoothed_cube) subpl.add_artist(plt.Circle(target_point, smoothing_width, edgecolor='blue', facecolor='none', transform=ccrs.PlateCarree())) for i, lat in enumerate(smoothed_cube.coord('latitude').points): for j, lon in enumerate(smoothed_cube.coord('longitude').points): if smoothed_cube.data[i, j] > 0: plt.text(lon, lat, smoothed_cube.data[i, j] ** -1, transform=ccrs.PlateCarree(), ha='center', va='center') qplt.plt.gca().coastlines() qplt.show()
def test_2d_positive_up(self): path = tests.get_data_path(('NetCDF', 'testing', 'small_theta_colpex.nc')) cube = iris.load_cube(path, 'air_potential_temperature')[0, :, 42, :] qplt.pcolormesh(cube) self.check_graphic()
def test_2d_positive_down(self): path = tests.get_data_path(('NetCDF', 'ORCA2', 'votemper.nc')) cube = iris.load_cube(path)[0, :, 42, :] qplt.pcolormesh(cube) self.check_graphic()
qplt.contourf(cube2.collapsed('TMNTH',iris.analysis.MEAN, weights = grid_areas),np.linspace(-100,100)) plt.gca().coastlines() plt.show(block = False) plt.figure() qplt.contourf(cube.collapsed('TMNTH',iris.analysis.MEAN, weights = grid_areas),np.linspace(300,500)) plt.gca().coastlines() plt.show(block = False) ts = cube2.collapsed(['latitude','longitude'],iris.analysis.MEAN, weights = grid_areas) plt.figure() qplt.plot(ts) plt.show() plt.figure() qplt.pcolormesh(cube2[-20]) plt.gca().coastlines() plt.show(block = False) plt.figure() qplt.pcolormesh(cube2[-1]) plt.gca().coastlines() plt.show(block = False) west = -70 east = -10 south = 50 north = 70 spg_region = iris.Constraint(longitude=lambda v: west <= v <= east,latitude=lambda v: south <= v <= north) spg_cube = cube2.extract(spg_region)
def _regrid(self, method): regridder = Regridder(self.src, self.grid, method, 'mask') result = regridder(self.src) qplt.pcolormesh(result) qplt.plt.gca().coastlines()
def test_xaxis_labels(self): qplt.pcolormesh(self.cube, coords=("str_coord", "bar")) self.assertBoundsTickLabels("xaxis")
def test_2d_coord_bounds_northpolarstereo(self): cube = simple_cube_w_2d_coords()[0, 0] ax = plt.axes(projection=ccrs.NorthPolarStereo()) qplt.pcolormesh(cube) ax.coastlines(color='red') self.check_graphic()
filename= "boxcar_%s_x_%s.json.gz" % (lon_width,lat_width) if os.path.exists(filename): print 'read existing file ',filename gs.load(filename) else: gs.build_boxcar_lat_lon(sst_field[0], lat_width, lon_width) gs.save(filename) smoothed_cube_masked = gs.smooth_3d_cube(sst_field, masked = True) anomaly_cube_masked = sst_field - smoothed_cube_masked if not os.path.exists('data_out'): os.makedirs('data_out') iris.save(anomaly_cube_masked ,'data_out/anomaly_masked.nc') reference_anomaly = iris.load_cube('gridsmoother/data_ref/anomaly_masked.nc') difference_from_ref = reference_anomaly - anomaly_cube_masked iris.save(difference_from_ref, './data_out/difference_from_ref.nc') fig = plt.figure() for i,cube in enumerate([sst_field[0], smoothed_cube_masked, anomaly_cube_masked[0]]): print 'cube ',cube vmax = cube.data.max() vmin = cube.data.min() subpl = fig.add_subplot(221+i) qplt.pcolormesh(cube, vmin=vmin, vmax = vmax) plt.gca().coastlines() plt.show()
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_strict(fname) # put bounds on the latitude and longitude coordinates temperature_cube.coord('latitude').guess_bounds() temperature_cube.coord('longitude').guess_bounds() # Draw the contour with 25 levels qplt.pcolormesh(temperature_cube) # Get the map created by pcolormesh current_map = iplt.gcm() # Add coastlines to the map current_map.drawcoastlines() plt.show()
def main(): import os#, sys #smoothing_width = float(sys.argv[1]) #resolution = int(sys.argv[2]) smoothing_width = 10. resolution = 48 dlat = 180. / int(resolution*1.5) lat_p = np.arange(-90.+dlat/2, 90., dlat) dlon = 360. / int(resolution*2) lon_p = np.arange(dlon/2, 360.,dlon) lat = iris.coords.DimCoord(lat_p, 'latitude', units = 'degrees') lon = iris.coords.DimCoord(lon_p, 'longitude', units = 'degrees') data = np.empty((len(lat_p),len(lon_p))) source_cube = iris.cube.Cube(data, dim_coords_and_dims = [(lat,0),(lon,1)]) # smoothing_width = 2. # fn = lambda x: np.exp(-x**2 / (2. *smoothing_width**2)) fn = lambda x: (x <= smoothing_width) * 1.0 gs = GridSmoother() filename = "simple_%s_grid_smoother_%s_%s.json.gz" %(smoothing_width,dlat,dlon) if os.path.exists(filename): print "loading ", filename gs.load(filename) else: print "generating smoother for %sx%s (lat x lon) degree source grid" %(dlat,dlon) gs.build(source_cube, fn, quiet=False, metadata={'source_grid':"N48","smoothing radius":smoothing_width}) print "saving to ", filename gs.save(filename) print "filling test cube with data" source_cube.data.fill(0) source_cube.long_name = "Source data" for i,ilat in enumerate(lat_p): for j,jlon in enumerate(lon_p): R = np.sqrt((ilat-0)**2 + (jlon-60.)**2) if R > 20 and R < 25: source_cube.data[i,j] = 10 tmpcube, extent = iac.project(source_cube, ccrs.RotatedPole(90, 20)) source_cube.data = tmpcube.data + tmpcube.data[:, ::-1] for i,ilat in enumerate(lat_p): for j,jlon in enumerate(lon_p): if 17.5 <= ilat <= 22.5 and (jlon < 60 or jlon > 300): source_cube.data[i,j] = 10 print "smoothing test cube" result_cube = gs.smooth_2d_cube(source_cube) result_cube.long_name = "Smoothed data" print "plotting" proj = ccrs.Orthographic(0,65) #proj = ccrs.PlateCarree() fig = plt.figure() s = fig.add_subplot(121, projection=proj) qplt.pcolormesh(source_cube, cmap='Greens') s.set_global() s.gridlines() plt.gca().coastlines() r = fig.add_subplot(122, projection= proj) qplt.pcolormesh(result_cube,cmap='Blues') r.set_global() r.gridlines() plt.gca().coastlines() # plt.savefig(filename[:-8]+".png") plt.show()
def cosp_plot_cfad_2D(fnc, varname=cfadDbze94, time = 0): """ Function that plots an area-averaged CFAD from a 2D file. """ # Read cube z=iris.load(fnc) z=z[0] # Select time t = z.coord('time') z=z.extract(iris.Constraint(time=t.points[time])) # Obtain area average cfad = area_average(z) if varname is not clisccp: cfad = change_data_units(cfad,varname) change_coord_units(cfad,coord_name='altitude') if cfad.standard_name in [cfadLidarsr532, clisccp]: change_pseudo_level(cfad, origin = 'nc') # Set limits yticks = None if cfad.standard_name == cfadDbze94: xlim = [-30, 20] ylim = [ 0, 18] vmax = 8 elif cfad.standard_name == cfadLidarsr532: xlim = [ 3, 15] ylim = [ 0, 18] vmax = 3 xt1 = xlim[0] xt2 = xlim[1] + 1 xticks = xt1 + np.arange(xt2 - xt1) xlabels = ['0', '0.01', '1.2', '3', '5', '7', '10', '15', '20', '25', '30', '40', '50', '60', '80', ''] elif cfad.standard_name == clisccp: xlim = [ 0, 7] ylim = [ 1000, 100] vmax = 8 xt1 = xlim[0] xt2 = xlim[1] + 1 xticks = xt1 + np.arange(xt2 - xt1) xlabels = ['0', '0.3', '1.3', '3.6', '9.4', '23', '60', ''] yticks = [1000, 800, 680, 560, 440, 310, 180] else: raise NameError('Variable not supported: ' + x.standard_name) # Plot block plot plt.interactive(True) fig=plt.figure() ax = fig.add_subplot(111) qplt.pcolormesh(cfad,vmin=0,vmax=vmax) # Title and limits ax.set_xlim(xlim) ax.set_ylim(ylim) # Xlabels if cfad.standard_name == cfadLidarsr532: ax.set_xticks(xticks) ax.set_xticklabels(xlabels[xt1:xt2]) if cfad.standard_name == clisccp: ax.set_xticklabels(xlabels) # Ylabels if yticks is not None: ax.set_yticks(yticks) return
y = cube.coord(axis='Y') y.guess_bounds() y # <codecell> %matplotlib inline import matplotlib.pyplot as plt plt.pcolormesh(x.points, y.points, cube.data) # <codecell> import iris.quickplot as qplt cs = qplt.pcolormesh(cube) # <codecell> import cartopy.crs as ccrs from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter fig, ax = plt.subplots(subplot_kw=dict(projection=ccrs.PlateCarree())) cs = qplt.pcolormesh(cube) ax.set_xticks(x.points, crs=ccrs.PlateCarree()) ax.set_yticks(y.points, crs=ccrs.PlateCarree()) lon_formatter = LongitudeFormatter(zero_direction_label=True) lat_formatter = LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter)
def test_check_extent_required(self): cube = setup_2d_cube() plt.axes(projection=ccrs.Stereographic()) qplt.pcolormesh(cube) set_global = cl.check_extent("using quickplot", True) self.assertTrue(set_global)
import glob from collections import OrderedDict import pylab import iris import iris.plot as iplt import iris.quickplot as qplt PATH='/Users/Rola/Documents/Science/JHU/Wildfires/NCEP_meteorology' fnameh = [PATH+'/hgt.2002.nc'] hgt = iris.load_cube(fnameh) fnamev = [PATH+'/vwnd.2002.nc'] vwnd = iris.load_cube(fnamev) fnameu = [PATH+'/uwnd.2002.nc'] uwnd = iris.load_cube(fnameu) fnamevs = [PATH+'/vwnd.sig995.2002.nc'] vwnds = iris.load_cube(fnamevs) fnameus = [PATH+'/uwnd.sig995.2002.nc'] uwnds = iris.load_cube(fnameus) for i in range(40,45): print i qplt.pcolormesh(hgt[i,5,:,:]) plt.gca().coastlines() plt.clim(4600,6000) F = pylab.gcf() name=str(i) F.savefig(name, dpi = (500)) plt.clf()
def test_xaxis_labels(self): qplt.pcolormesh(self.cube, coords=('str_coord', 'bar')) self.assertBoundsTickLabels('xaxis')