def cloud_lats(cubes, time_slice=-1, long=0): for cube in cubes: if cube.long_name == 'cloud_volume_fraction_in_atmosphere_layer': cloud_volume = cube.copy() if cube.long_name == 'liquid_cloud_volume_fraction_in_atmosphere_layer': liquid_cloud = cube.copy() if cube.long_name == 'ice_cloud_volume_fraction_in_atmosphere_layer': ice_cloud = cube.copy() if cube.standard_name == 'mass_fraction_of_cloud_ice_in_air': ice_condensate = cube.copy() if cube.standard_name == 'mass_fraction_of_cloud_liquid_water_in_air': liquid_condensate = cube.copy() longitudes = cloud_volume.coord('longitude').points for cube in (cloud_volume, liquid_cloud, ice_cloud, ice_condensate, liquid_condensate): if cube.standard_name == None: title = cube.long_name else: title = cube.standard_name iplt.contourf(cube[time_slice,:,:,long], brewer_bg.N, cmap=brewer_bg) plt.title('%s at %s' %(title,longitudes[long]), y=1.05) plt.ylabel('Height [m]') plt.xlabel('Latitude [degrees]') cbar = plt.colorbar(pad=0.1) cbar.ax.set_title('kg/kg') plt.show()
def test_y_fastest(self): cubes = iris.load(tests.get_data_path(("GRIB", "y_fastest", "y_fast.grib2"))) self.assertCML(cubes, ("grib_load", "y_fastest.cml")) iplt.contourf(cubes[0]) iplt.gcm(cubes[0]).drawcoastlines() plt.title("y changes fastest") self.check_graphic()
def plot_vorticity(cubes, level=15, time_slice=-1, omega=0.64617667): """ Uses windspharm package to plot the vorticity """ for cube in cubes: if cube.standard_name == 'x_wind': x_wind = cube.copy() if cube.standard_name == 'y_wind': y_wind = cube.copy() y_wind = y_wind.regrid(x_wind, iris.analysis.Linear()) heights = np.round(x_wind.coord('level_height').points*1e-03,0) wind = windspharm.iris.VectorWind(x_wind, y_wind) planet_vort = wind.planetaryvorticity(omega=omega) relative_vort = wind.vorticity() absolute_vort = wind.absolutevorticity() iplt.contourf(relative_vort[time_slice,level,:,:], brewer_redblu.N, cmap=brewer_redblu, norm=TwoSlopeNorm(0)) plt.title('Relative Vorticity, h = %s km' %(heights[level]), y=1.20) plt.ylabel('Latitude [degrees]') plt.xlabel('Longitude [degrees]') ax = plt.gca() ax.gridlines(draw_labels=True) plt.colorbar(orientation='horizontal') plt.show()
def test_xaxis_labels_with_axes(self): import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) iplt.contourf(self.cube, axes=ax, coords=('str_coord', 'bar')) plt.close(fig) self.assertPointsTickLabels('xaxis', ax)
def plotCode(timeseries, climatology, modelID): years = timeseries.coord('year').points f = plt.figure(figsize=(15, 5)) plt.subplot(1, 2, 1) plt.bar(years, timeseries.data) plt.xlabel('years') plt.ylabel('precip kg m-2 day-1') #plt.xlim(0, len(timeseries.data)) plt.title('JJAS pr 5S-20N ; 18W-15E: ' + modelID) plt.subplot(1, 2, 2) levs = np.linspace(1, 20, 20) iplt.contourf(climatology, levs, cmap='jet_r') m = bm.Basemap(projection='cyl', llcrnrlat=np.min(climatology.coord('latitude').points), urcrnrlat=np.max(climatology.coord('latitude').points), llcrnrlon=np.min(climatology.coord('longitude').points), urcrnrlon=np.max(climatology.coord('longitude').points), resolution='c') # medium resolution for grid m.drawcoastlines(linewidth=2) m.drawcountries(linewidth=1) plt.title('JJAS mean pr (1950-2005) 5S-20N ; 18W-15E:' + modelID) cbar = plt.colorbar(orientation="vertical") cbar.set_label('precip kg m-2 day-1') #qplt.pcolor(climatology) #plt.tight_layout() plt.savefig( '/nfs/see-fs-01_teaching/earv057/metrics_workshop/Ev_To/Figures_png/' + modelID + 'jjas.png')
def rossby_source(cubes, time_slice=-1, level=0): for cube in cubes: if cube.standard_name == 'x_wind': x_wind = cube.copy() if cube.standard_name == 'y_wind': y_wind = cube.copy() y_wind = y_wind.regrid(x_wind, iris.analysis.Linear()) winds = windspharm.iris.VectorWind(x_wind,y_wind) eta = winds.absolutevorticity() div = winds.divergence() uchi, vchi = winds.irrotationalcomponent() etax, etay = winds.gradient(eta) etax.units = 'm**-1 s**-1' etay.units = 'm**-1 s**-1' S = eta*-1.*div-(uchi*etax+vchi*etay) S.coord('longitude').attributes['circular'] = True print(S.shape) print(S) clevs = [-30,-25,-20,-15,-10,-5,0,5,10,15,20,25,30] iplt.contourf(S[time_slice,level,:,:]*1e11,clevs,cmap=brewer_redblu, extend='both') ax = plt.gca() ax.gridlines(draw_labels=True) plt.colorbar(orientation='horizontal') plt.title('Rossby Wave Source ($10^{-11}$s$^{-1}$)') plt.show()
def plot_timehgt(cube, levels, title, log=False, ax1=None): """ Plot fields as time-pressure. Routine to plot fields as time-pressure contours with given contour levels. Option to plot against log(pressure). """ (colormap, normalisation) = cmap_and_norm('brewer_RdBu_11', levels) if ax1 is None: ax1 = plt.gca() ax1.set_title(title) iplt.contourf(cube, levels=levels, cmap=colormap, norm=normalisation) lwid = 1. * np.ones_like(levels) cl1 = iplt.contour(cube, colors='k', linewidths=lwid, levels=levels) plt.clabel(cl1, cl1.levels, inline=1, fontsize=6, fmt='%1.0f') ax1.set_xlabel('Year', fontsize='small') time_coord = cube.coord('time') new_epoch = time_coord.points[0] new_unit_str = 'hours since {}' new_unit = new_unit_str.format(time_coord.units.num2date(new_epoch)) ax1.xaxis.axis_date() ax1.xaxis.set_label(new_unit) ax1.xaxis.set_major_locator(mdates.YearLocator(4)) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y')) ax1.set_ylabel('Pressure (Pa)', fontsize='small') ax1.set_ylim(100000., 10.) if log: ax1.set_yscale("log")
def make_plot(forecast, analysis, variable, levels, units, errlevs, clevs, cmap='coolwarm', mask=None): # Extract data and errors f = convert.calc(variable, forecast, levels=levels)[0] a = convert.calc(variable, analysis, levels=levels)[0] err = f - a for cube in [f, a, err]: cube.convert_units(units) if mask is not None: for cube in [f, a]: cube.data = np.ma.masked_where(mask, cube.data) # Plot error iplt.contourf(err, errlevs, cmap=cmap, extend='both') add_map() cbar = plt.colorbar(orientation='horizontal', spacing='proportional') errlevs.append(0) cbar.set_ticks(errlevs) cbar.set_label(units) # Overlay forecast and analysis cs = iplt.contour(f, clevs, colors='k', linewidths=2) iplt.contour(a, clevs, colors='k', linewidths=2, linestyles='--') plt.clabel(cs, fmt='%1.0f', colors='k') return
def test_ij_directions_ineg_jpos(self): cubes = self._old_compat_load("ineg_jpos.grib2") self.assertCML(cubes, ("grib_load", "ineg_jpos.cml")) iplt.contourf(cubes[0]) plt.gca().coastlines() plt.title("ineg_jpos cube") self.check_graphic()
def main(): fname = iris.sample_data_path('NAME_output.txt') boundary_volc_ash_constraint = iris.Constraint( 'VOLCANIC_ASH_AIR_CONCENTRATION', flight_level='From FL000 - FL200') # Callback shown as None to illustrate where a cube-level callback function would be used if required cube = iris.load_strict(fname, boundary_volc_ash_constraint, callback=None) map = iplt.map_setup(lon_range=[-70, 20], lat_range=[20, 75], resolution='i') map.drawcoastlines() iplt.contourf(cube, levels=(0.0002, 0.002, 0.004, 1), colors=('#80ffff', '#939598', '#e00404'), extend='max') time = cube.coord('time') time_date = time.units.num2date(time.points[0]).strftime(UTC_format) plt.title('Volcanic ash concentration forecast\nvalid at %s' % time_date) plt.show()
def make_plot(ax, dtheta, pv, tr): im = iplt.pcolormesh(dtheta, vmin=-30, vmax=30, cmap="seismic") print(dtheta.data.min(), dtheta.data.max()) ax.coastlines() ax.gridlines() # Add a contour for PV=2 and also shade PV>2 iplt.contour(pv, [2], colors='k') pv.data = (pv.data > 2).astype(float) iplt.contourf(pv, [0.9, 1.1], colors="k", alpha=0.25) # Need to use the cube's coordinate reference system to properly add regular # coordinates on top crs = dtheta.coord(axis="x").coord_system.as_cartopy_crs() plt.plot(tr.x[:, 0] - 360, tr.y[:, 0], transform=crs, lw=3, color='cyan') # With the projection the axis limits don't set well, so shrink it down as much as # possible x, y = pv.coord(axis="x"), pv.coord(axis="y") ax.set_extent( [x.points.min(), x.points.max(), y.points.min(), y.points.max()], crs=crs) return im
def _create_feedback_plot(tas_cube, cube, dataset_name, cfg, description=None): """Plot feedback parameter vs. remaining dimensions.""" var = cube.var_name logger.debug("Plotting '%s' vs. %s for '%s'", SHORTER_NAMES.get(var, var), COORDS['rad'], dataset_name) x_data = _get_data_time_last(tas_cube) y_data = _get_data_time_last(cube) coords = [(coord, idx - 1) for (idx, coord) in enumerate(cube.coords(dim_coords=True)) if coord.name() != 'time'] feedback_cube = iris.cube.Cube(_get_slope(x_data, y_data), var_name=var, dim_coords_and_dims=coords, units='W m-2 K-1') # Plot if feedback_cube.ndim == 1: iplt.plot(feedback_cube) plt.xlabel(f"{COORDS['rad'][0]} / " f"{cube.coord(COORDS['rad'][0]).units.origin}") plt.ylabel(f"{NICE_SYMBOLS.get(var, var)} / " f"{NICE_UNITS.get(feedback_cube.units.origin, 'unknown')}") colorbar = None elif feedback_cube.ndim == 2: iplt.contourf(feedback_cube, cmap='bwr', levels=_get_levels()) colorbar = plt.colorbar(orientation='horizontal') colorbar.set_label( f"{NICE_SYMBOLS.get(var, var)} / " f"{NICE_UNITS.get(feedback_cube.units.origin, 'unknown')}") ticks = [-8.0, -6.0, -4.0, -2.0, 0.0, 2.0, 4.0, 6.0, 8.0] colorbar.set_ticks(ticks) colorbar.set_ticklabels([str(tick) for tick in ticks]) if COORDS['rad'] == ['latitude', 'longitude']: plt.gca().coastlines() else: plt.xlabel(f"{COORDS['rad'][0]} / " f"{cube.coord(COORDS['rad'][0]).units.origin}") plt.ylabel(f"{COORDS['rad'][1]} / " f"{cube.coord(COORDS['rad'][1]).units.origin}") else: raise ValueError(f"Cube dimension {feedback_cube.ndim} not supported") # Appearance title = f'{SHORTER_NAMES.get(var, var)} for {dataset_name}' filename = ('{}_vs_{}_{}'.format(VAR_NAMES.get(var, var), '-'.join(COORDS['rad']), dataset_name)) if description is not None: title += f' ({description})' filename += f"_{description.replace(' ', '_')}" plt.title(title) plot_path = get_plot_filename(filename, cfg) plt.savefig(plot_path, bbox_inches='tight', orientation='landscape', additional_artists=[colorbar]) logger.info("Wrote %s", plot_path) plt.close() return (plot_path, feedback_cube)
def plotrun(cube, foldername, scaleLBound, scaleUBound): # Delete all the image files in the directory to ensure that only those # created in the loop end up in the movie. print("Deleting all .png files in the " + foldername + " directory...") SpawnCommand("rm " + foldername + "/*.png") # Add a new coordinate containing the year. icat.add_year(cube, 'time') # Set the end index for the loop over years, and do the loop. tmin = 0 tmax = cube.shape[0] # We want the files to be numbered sequentially, starting # from 000.png; this is so that the ffmpeg command can grok them. index = 0 #scaleBarArray = scaleBar(lowerBound, upperBound) for time in range(tmin, tmax): fig = plt.figure(figsize=(6, 3), dpi=200) rect = 0, 0, 1200, 600 fig.add_axes(rect) geo_axes = plt.axes(projection=ccrs.PlateCarree()) geo_axes.outline_patch.set_visible(False) plt.margins(0, 0) fig.subplots_adjust(left=0, right=1, bottom=0, top=1) iplt.contourf(cube[time], 10, vmin=scaleLBound, vmax=scaleUBound, cmap='YlOrRd') plt.gca().coastlines(color='b') # plt.figure(frameon=False) # Extract the year value and display it (coordinates used are # those of the data). year = cube.coord('year')[time].points[0] plt.text(-160, 0, year, horizontalalignment='center', size='large', fontdict={'family': 'monospace'}, color='b') filename = str(foldername) + '/' + "%03d.png" % index print('Now plotting: ', filename) plt.savefig(filename, dpi=200) plt.close() index += 1 # Now make the movie from the image files by spawning the ffmpeg command. # The options (of which there are many) are somewhat arcane, but these ones work. print("Converting images to movie...") options = ("-r 5 -vcodec png -y -i " + foldername + "/%03d.png -r 5 -vcodec msmpeg4v2 -qblur 0.01 -qscale 5 ") SpawnCommand("ffmpeg " + options + foldername + ".mp4")
def test_y_fastest(self): cubes = iris.load( tests.get_data_path(("GRIB", "y_fastest", "y_fast.grib2"))) self.assertCML(cubes, ("grib_load", "y_fastest.cml")) iplt.contourf(cubes[0]) plt.gca().coastlines() plt.title("y changes fastest") self.check_graphic()
def rotating_sequence(show_frames=True, save_frames=True, save_ani=False, show_ani=False, ani_path='./puffer.mp4', frames_basename='./puffer_frame_', airtemp_cubes=None, precip_cubes=None, n_steps_round=20, tilt_angle=21.7 ): plt.interactive(show_frames) figure = make_puffersphere_figure() # per_image_artists = [] for (i_plt, lon_rotate) in enumerate(np.linspace(0.0, 360.0, n_steps_round, endpoint=False)): print 'rotate=', lon_rotate,' ...' axes = make_puffersphere_axes( projection_kwargs={'central_longitude': lon_rotate, 'central_latitude': tilt_angle}) image = axes.stock_img() coast = axes.coastlines() # data = istk.global_pp() data = airtemp_cubes[i_plt] transparent_blue = (0.0, 0.0, 1.0, 0.25) transparent_red = (1.0, 0.0, 0.0, 0.25) cold_thresh = -10.0 cold_fill = iplt.contourf( data, levels=[cold_thresh, cold_thresh], colors=[transparent_blue], extend='min') cold_contour = iplt.contour( data, levels=[cold_thresh], colors=['blue'], linestyles=['solid']) data = precip_cubes[i_plt] precip_thresh = 0.0001 precip_fill = iplt.contourf( data, levels=[precip_thresh, precip_thresh], colors=[transparent_red], extend='max') precip_contour = iplt.contour( data, levels=[precip_thresh], colors=['red'], linestyles=['solid']) gridlines = draw_gridlines(n_meridians=6) # artists = [] # artists += [coast] # artists += [image] # artists += cold_fill.collections # artists += precip_fill.collections # for gridline in gridlines: # artists += gridline if show_frames: plt.draw() if save_frames: save_path = frames_basename+str(i_plt)+'.png' save_figure_for_puffersphere(figure, save_path) # per_image_artists.append(artists) print ' ..done.'
def test_coord_names(self): # Pass in names of dimension coords. iplt.contourf(self.cube, coords=["grid_longitude", "grid_latitude"]) plt.gca().coastlines("110m") self.check_graphic() # Pass in names of auxiliary coords. iplt.contourf(self.cube, coords=["longitude", "latitude"]) plt.gca().coastlines("110m") self.check_graphic()
def plot_hovmoller(nc_path, var, out_path, do_latitude=True, xlabel='', ylabel='', title='', cbar=''): """ Ref: http://scitools.org.uk/iris/docs/v0.9.1/examples/graphics/hovmoller.html :param nc_path: :param var: :param out_path: :param do_latitude: :param xlabel: :param ylabel: :param title: :param cbar: :return: """ logger.info('Plot hovmoller') # TODO: Iris install is not working on mac os x if os.name == 'mac' or os.name == 'posix': return import iris import iris.plot as iplt iris.FUTURE.netcdf_promote = True cubes = iris.load(nc_path, var) # Take the mean over latitude/longitude if do_latitude: cube = cubes[0].collapsed('latitude', iris.analysis.MEAN) else: cube = cubes[0].collapsed('longitude', iris.analysis.MEAN) # Create the plot contour with 20 levels iplt.contourf(cube, 20, cmap=palettable.colorbrewer.diverging.RdYlGn_9.mpl_colormap) if not do_latitude: plt.ylabel(xlabel) # Latitude plt.xlabel(ylabel) # Years else: plt.ylabel(ylabel) # Years plt.xlabel(xlabel) # Longitude plt.title(title) plt.colorbar(orientation='horizontal', extend='both', drawedges=False, spacing='proportional').set_label(cbar) # Stop matplotlib providing clever axes range padding and do not draw gridlines plt.grid(b=False) plt.axis('tight') plt.tight_layout() plt.savefig(out_path, dpi=constants.DPI) plt.close()
def test_coord_names(self): # Pass in names of dimension coords. iplt.contourf(self.cube, coords=['grid_longitude', 'grid_latitude']) plt.gca().coastlines() self.check_graphic() # Pass in names of auxiliary coords. iplt.contourf(self.cube, coords=['longitude', 'latitude']) plt.gca().coastlines() self.check_graphic()
def gif_longwave(i, outgoing_lw): iplt.contourf(outgoing_lw[i, :, :], brewer_reds.N, cmap=brewer_reds) ax = plt.gca() ax.gridlines(draw_labels=True) plt.title('Monthly Mean Outgoing LW Radiation, month %s' % (i + 1), y=1.10) plt.ylabel('Latitude [degrees]') plt.xlabel('Longitude [degrees]') plt.colorbar(pad=0.1)
def gif_airtemp(i, mean_absolute_temp): iplt.contourf(mean_absolute_temp[i, :, :], brewer_reds.N, cmap=brewer_reds) ax = plt.gca() ax.gridlines(draw_labels=True) plt.title('Monthly Mean Air Temperature, month %s' % (i + 1), y=1.10) plt.ylabel('Latitude [degrees]') plt.xlabel('Longitude [degrees]') plt.colorbar(pad=0.1)
def gif_cloudcover(i, cloud_cover): iplt.contourf(cloud_cover[i, :, :], brewer_bg.N, cmap=brewer_bg) ax = plt.gca() ax.gridlines(draw_labels=True) plt.title('Cloud cover, day %s' % (i + 1), y=1.10) plt.ylabel('Latitude [degrees]') plt.xlabel('Longitude [degrees]') plt.colorbar(pad=0.1)
def main(): # Delete all the image files in the current directory to ensure that only those # created in the loop end up in the movie. print "Deleting all .png files in this directory..." SpawnCommand("rm *.png") # Read all the temperature values. temperatures = iris.load_cube('temperatures.pp') # Get the range of values. minTemp = np.amin(temperatures.data) maxTemp = np.amax(temperatures.data) print "Range of temperatures is", minTemp, "to", maxTemp # Add a new coordinate containing the year. icat.add_year(temperatures, 'time') years = temperatures.coord('year') # Set the limits for the loop over years. minTime = 0 maxTime = temperatures.shape[0] print "Making images from year", years[minTime].points[0], "to", years[maxTime-1].points[0] for time in range(minTime, maxTime): # Contour plot the temperatures and add the coastline. iplt.contourf(temperatures[time], 10, vmin=minTemp, vmax=maxTemp, cmap='hot') plt.gca().coastlines() # We need to fix the boundary of the figure (otherwise we get a black border at left & top). # Cartopy removes matplotlib's axes.patch (which normally defines the boundary) and # replaces it with outline_patch and background_patch. It's the former which is causing # the black border. Get the axis object and make its outline patch invisible. ax = plt.gca() ax.outline_patch.set_visible(False) # Extract the year value and display it (coordinates used in locating the text are # those of the data). year = years[time].points[0] plt.text(0, -60, year, horizontalalignment='center') # Now save the plot in an image file. The files are numbered sequentially, starting # from 000.png; this is so that the ffmpeg command can grok them. filename = "%03d.png" % time plt.savefig(filename, bbox_inches='tight', pad_inches=0) # Discard the figure (otherwise the text will be overwritten # by the next iteration). plt.close() # Now make the movie from the image files by spawning the ffmpeg command. # The options (of which there are many) are somewhat arcane, but these ones work. print "Converting images to movie..." options = "-r 5 -vcodec png -y -i %03d.png -r 5 -vcodec msmpeg4v2 -qblur 0.01 -qscale 5" SpawnCommand("ffmpeg " + options + " plotTemperatures.avi")
def test_params(self): c = iplt.contourf(self.cube, self.few) self.check_graphic() iplt.contourf(self.cube, self.few_levels) self.check_graphic() iplt.contourf(self.cube, self.many_levels) self.check_graphic()
def calculate_timescales(cubes, stellar_constant=837): """ Implements formula from Koll & Abbot 2016 for: Timescale for equatorial waves to transport energy across the planet Atmosphere's radiative cooling time Stellar constant for FAST experiment: 1100 Stellar constant for SLOW experiment: 420 """ # I made every conceivable kind of error while writing this function for cube in cubes: if cube.long_name == 'surface_diffuse_albedo_assuming_no_snow': # long name not standard name albedo = cube.copy() # if cube.standard_name == 'specific_humidity': # q = cube.copy() R = 297.0 # gas constant for air in J/kgK, from UM Planet Constants a = 7160000 # planet's radius in m, from UM Planet Constants g = 10.9 # mean gravity in m/s2, from UM Planet Constants sigma = 5.67e-8 # Stefan-Boltzmann constant, SI units NOT BOLTZMANN'S CONSTANT GODDAMN ONLY 20 ORDERS OF MAGNITUDE OFF pressure = 100000 # surface pressure in Pa, from UM Planet Constants DO NOT PUT A COMMA IN HERE!! NUMPY NOT LIKE!! cp = 1038 # specific heat capacity at constant pressure for N2, J/kgK # solar_constant = 0.0017*3.828e26 # luminosity of Proxima Centauri in W, wrong constant, WHY DID U USE THE SYMBOL FOR STELLAR LUMINOSITY THEN DANIEL AND DORIAN mean_albedo = albedo.collapsed(['time','pseudo_level'], iris.analysis.MEAN) iplt.contourf(mean_albedo, brewer_bg.N, cmap=brewer_bg) ax = plt.gca() ax.gridlines(draw_labels=True) plt.title('Mean Surface Albedo [K]', y=1.20) plt.colorbar(pad=0.1) plt.show() lats = albedo.coord('latitude') longs = albedo.coord('longitude') if lats.bounds == None: albedo.coord('latitude').guess_bounds() if longs.bounds == None: albedo.coord('longitude').guess_bounds() global_grid = iris.analysis.cartography.area_weights(albedo) alpha = albedo.collapsed(['latitude', 'longitude', 'time', 'pseudo_level'], iris.analysis.MEAN, weights=global_grid) alpha = alpha.data Teq = ((stellar_constant*(1-alpha))/(4*sigma))**(1/4) # brackets matter cwave = R*np.sqrt(Teq/cp) twave = a/cwave trad = (cp*pressure)/(g*sigma*(Teq**3)) ratio = twave/trad print('Ratio of wave to radiative timescale is ' + str(ratio)) print('Wave timescale is ' + str(twave) + ' seconds') print('Radiative timescale is ' + str(trad) + ' seconds') return ratio
def plot_maps(obs, cubelist_dict, plot_order, figfile, season): fig = plt.figure(figsize=(3.5, 3)) axx = fig.add_subplot(221, projection=ccrs.PlateCarree()) plot1 = iplt.pcolormesh(obs.collapsed('time', iana.MEAN), cmap=cm.get_cmap('terrain_r'), vmin=0, vmax=7) plt.title('a. observations ({})'.format(season.upper()), fontsize=8) cbar = plt.colorbar( plot1, cax=plt.gcf().add_axes((0.02, 0.1, 0.43, 0.02)), orientation='horizontal', ) letter_dict = {'PRIMAVERA': 'b', 'EUR-44': 'd', 'EUR-11': 'c'} cbar.ax.tick_params(labelsize=8) plt.title('mm/day', fontsize=8, y=0.7) axx.set_extent([-22, 41, 33, 70]) for num, dataset in enumerate(plot_order, 2): numnum = '22' + str(num) axx = fig.add_subplot(int(numnum), projection=ccrs.PlateCarree()) model = cubelist_dict[dataset][0].collapsed('member_number', iana.MEAN) #plot = iplt.pcolormesh(model-obs, cmap=cm.get_cmap('RdBu'), vmin = -2, vmax=2) levels = np.linspace(-2, 2, 11) extend = 'both' sig_val = calculate_sig_val(obs, cubelist_dict[dataset][0]) cube2plot = model - obs.collapsed('time', iana.MEAN) cmap = cm.get_cmap('RdBu', 12) colors = np.concatenate([ cmap(range(0, 12)), ]) cmap1, norm = from_levels_and_colors(levels, colors, extend='both') plot = iplt.pcolormesh(cube2plot, norm=norm, cmap=cmap1) global_mask = generate_global_pvalue_mask(sig_val.data, sig_lev=0.1) cube2plot = mask_cube_where(cube2plot, global_mask) iplt.contourf(cube2plot, levels=levels, cmap=cm.get_cmap('RdBu'), extend=extend, hatches=['.....'], zorder=10, alpha=0.5) plt.title('{}. {} - observations'.format(letter_dict[dataset], dataset), fontsize=8) axx.set_extent([-22, 41, 33, 70]) cbar = plt.colorbar( plot, cax=plt.gcf().add_axes((0.52, 0.1, 0.43, 0.02)), orientation='horizontal', ) cbar.ax.tick_params(labelsize=8) plt.title('mm/day', fontsize=8, y=0.7) plt.box(False) plt.tight_layout(rect=[0, 0.12, 1, 1], pad=0.05) plt.savefig(figfile + '_'.join(r for r in plot_order) + '.png', dpi=300)
def plot_funct(cubes,vmin,vmax,sig=0.10,hatches=False): reg = cubes[0].copy() cor = cubes[1].copy() pval = cubes[-1].copy() qplt.pcmeshclf(reg,vmin=-vmin,vmax=vmax,cmap=mc.jetwhite()) if hatches: pval.data = np.ma.masked_greater(pval.data,sig) iplt.contourf(pval,hatches=[".."],colors="none",alpha=0.000001) name=reg.long_name.replace(" ","_") plt.savefig('./figures/'+name+'.amip.ens2.pdf')
def test_skip_contour(self): # Contours should not be added if data is all below second level. See #4086. cube = simple_2d() levels = [5, 15, 20, 200] colors = ["b", "r", "y"] with mock.patch("matplotlib.pyplot.contour") as mocked_contour: iplt.contourf(cube, levels=levels, colors=colors, antialiased=True) mocked_contour.assert_not_called()
def cross_sections(tracers, theta, rh, z_bl, fig): # Plot each cube separately for n, cube in enumerate(tracers): row = n / ncols col = n - row * ncols ax = plt.subplot2grid((nrows, ncols), (row, col)) # Interpolate along the cross section cube = cs_cube(cube, xs, xf, ys, yf) coords = ['grid_longitude', 'altitude'] # Make the plot im = iplt.contourf(cube, even_cscale(2), coords=coords, cmap='coolwarm', extend='both') cs = iplt.contour(theta, theta_levs, coords=coords, colors='k', linewidths=2) iplt.plot(z_bl.coord('grid_longitude'), z_bl, color='y') iplt.contour(rh, [0.8], coords=coords, colors='w') iplt.contourf(rh, [0.8, 2], coords=coords, colors='None', hatches=['.']) plt.title(second_analysis.all_diagnostics[cube.name()].symbol) if n == 0: plt.clabel(cs, fmt='%1.0f', colors='k') ax.set_ylim(0, 7) if n < 4: ax.set_xticks([]) # Add letter labels to panels for n, ax in enumerate(fig.axes): multilabel(ax, n) # Add colorbar at bottom of figure cbar = plt.colorbar(im, ax=fig.axes, orientation='horizontal', fraction=0.05, spacing='proportional') cbar.set_label('PVU') cbar.set_ticks(np.linspace(-2, 2, 9)) fig.text(0.075, 0.58, 'Height (km)', va='center', rotation='vertical') fig.text(0.5, 0.2, 'Grid Longitude', ha='center') return
def test_coords(self): # Pass in dimension coords. rlat = self.cube.coord('grid_latitude') rlon = self.cube.coord('grid_longitude') iplt.contourf(self.cube, coords=[rlon, rlat]) plt.gca().coastlines() self.check_graphic() # Pass in auxiliary coords. lat = self.cube.coord('latitude') lon = self.cube.coord('longitude') iplt.contourf(self.cube, coords=[lon, lat]) plt.gca().coastlines() self.check_graphic()
def test_apply_contour_nans(self): # Presence of nans should not prevent contours being added. cube = simple_2d() cube.data = cube.data.astype(np.float_) cube.data[0, 0] = np.nan levels = [2, 4, 6, 8] colors = ["b", "r", "y"] with mock.patch("matplotlib.pyplot.contour") as mocked_contour: iplt.contourf(cube, levels=levels, colors=colors, antialiased=True) mocked_contour.assert_called_once()
def make_plots(forecast, analysis, variable, levels, units, errlevs, clevs, cmap1='plasma', cmap='coolwarm', mask=None): # Extract data and errors f = convert.calc(variable, forecast, levels=levels)[0] a = convert.calc(variable, analysis, levels=levels)[0] err = f - a for cube in [f, a, err]: cube.convert_units(units) if mask is not None: for cube in [f, a]: cube.data = np.ma.masked_where(mask, cube.data) # Initialise the plot plt.figure(figsize=(18, 15)) # Plot absolute values plt.subplot2grid((25, 4), (0, 0), colspan=2, rowspan=10) im = iplt.contourf(f, clevs, extend='both', cmap=cmap1) #iplt.contour(f, [2], colors='k') plt.title('(a)'.ljust(28) + 'Forecast'.ljust(35)) add_map() plt.subplot2grid((25, 4), (0, 2), colspan=2, rowspan=10) im = iplt.contourf(a, clevs, extend='both', cmap=cmap1) #iplt.contour(a, [2], colors='k', linestyles='--') plt.title('(b)'.ljust(28) + 'Analysis'.ljust(35)) add_map() ax = plt.subplot2grid((25, 4), (10, 1), colspan=2, rowspan=1) cbar = plt.colorbar(im, cax=ax, orientation='horizontal') cbar.set_label(units) # cbar.set_ticks(range(11)) # Plot error plt.subplot2grid((25, 4), (13, 1), colspan=2, rowspan=10) im = iplt.contourf(err, errlevs, cmap=cmap, extend='both') #iplt.contour(f, [2], colors='k') #iplt.contour(a, [2], colors='k', linestyles='--') plt.title('(c)'.ljust(20) + 'Forecast Minus Analysis.'.ljust(38)) add_map() ax = plt.subplot2grid((25, 4), (23, 1), colspan=2, rowspan=1) cbar = plt.colorbar(im, cax=ax, orientation='horizontal', spacing='proportional') errlevs.append(0) cbar.set_ticks(errlevs) cbar.set_label(units) return
def test_ij_directions(self): def old_compat_load(name): cube = iris.load( tests.get_data_path(('GRIB', 'ij_directions', name)))[0] return [cube] cubes = old_compat_load("ipos_jpos.grib2") self.assertCML(cubes, ("grib_load", "ipos_jpos.cml")) iplt.contourf(cubes[0]) plt.gca().coastlines() plt.title("ipos_jpos cube") self.check_graphic() cubes = old_compat_load("ipos_jneg.grib2") self.assertCML(cubes, ("grib_load", "ipos_jneg.cml")) iplt.contourf(cubes[0]) plt.gca().coastlines() plt.title("ipos_jneg cube") self.check_graphic() cubes = old_compat_load("ineg_jneg.grib2") self.assertCML(cubes, ("grib_load", "ineg_jneg.cml")) iplt.contourf(cubes[0]) plt.gca().coastlines() plt.title("ineg_jneg cube") self.check_graphic() cubes = old_compat_load("ineg_jpos.grib2") self.assertCML(cubes, ("grib_load", "ineg_jpos.cml")) iplt.contourf(cubes[0]) plt.gca().coastlines() plt.title("ineg_jpos cube") self.check_graphic()
def test_ij_directions(self): def old_compat_load(name): cube = iris.load(tests.get_data_path(('GRIB', 'ij_directions', name)))[0] return [cube] cubes = old_compat_load("ipos_jpos.grib2") self.assertCML(cubes, ("grib_load", "ipos_jpos.cml")) iplt.contourf(cubes[0]) plt.gca().coastlines() plt.title("ipos_jpos cube") self.check_graphic() cubes = old_compat_load("ipos_jneg.grib2") self.assertCML(cubes, ("grib_load", "ipos_jneg.cml")) iplt.contourf(cubes[0]) plt.gca().coastlines() plt.title("ipos_jneg cube") self.check_graphic() cubes = old_compat_load("ineg_jneg.grib2") self.assertCML(cubes, ("grib_load", "ineg_jneg.cml")) iplt.contourf(cubes[0]) plt.gca().coastlines() plt.title("ineg_jneg cube") self.check_graphic() cubes = old_compat_load("ineg_jpos.grib2") self.assertCML(cubes, ("grib_load", "ineg_jpos.cml")) iplt.contourf(cubes[0]) plt.gca().coastlines() plt.title("ineg_jpos cube") self.check_graphic()
def plot_cross_section(cube, pv, theta, theta_e, z_bl, rh, ax, n, ylims): # Make the plot if cube.units == 'K': im = iplt.contourf(cube, even_cscale(20), coords=coords, cmap='coolwarm', extend='both') elif cube.units == 'PVU': im = iplt.contourf(cube, even_cscale(2), coords=coords, cmap='coolwarm', extend='both') else: print(cube.units) iplt.contour(pv, [2], colors='k', coords=coords) cs_theta = iplt.contour(theta, theta_levs, coords=coords, colors='k', linewidths=1, linestyles='-') cs_theta_e = iplt.contour(theta_e, theta_levs, coords=coords, colors='w', linewidths=1, linestyles='-') iplt.plot(z_bl.coord('grid_longitude'), z_bl, color='y') iplt.contour(rh, [0.8], coords=coords, colors='grey') iplt.contourf(rh, [0.8, 2], coords=coords, colors='None', hatches=['.']) plt.title(second_analysis.all_diagnostics[cube.name()].symbol) if n == 0: plt.clabel(cs_theta, fmt='%1.1f') plt.clabel(cs_theta_e, fmt='%1.1f') ax.set_ylim(*ylims) if n < (nrows - 1) * ncols: ax.set_xticks([]) if n % ncols != 0: ax.set_yticks([]) return im
def test_apply_contour_nans(self): # Presence of nans should not prevent contours being added. cube = simple_2d() cube.data = cube.data.astype(np.float_) cube.data[0, 0] = np.nan levels = [2, 4, 6, 8] colors = ["b", "r", "y"] iplt.contourf(cube, levels=levels, colors=colors, antialiased=True) ax = plt.gca() # If contour has been called, last collection will be a LineCollection. self.assertIsInstance(ax.collections[-1], matplotlib.collections.LineCollection)
def contourf(cube, *args, **kwargs): """ Draws filled contours on a labelled plot based on the given Cube. With the basic call signature, contour "level" values are chosen automatically:: contour(cube) Supply a number to use *N* automatically chosen levels:: contour(cube, N) Supply a sequence *V* to use explicitly defined levels:: contour(cube, V) See :func:`iris.plot.contourf` for details of valid keyword arguments. """ coords = kwargs.get('coords') axes = kwargs.get('axes') result = iplt.contourf(cube, *args, **kwargs) _label_with_points(cube, result, coords=coords, axes=axes) return result
def plot_cube(cube, pressure_level=None): metadata = {} level, is_3d, cslice = cube_level(cube) metadata['is_3d'] = is_3d metadata['pressure_level'] = level fig = plt.figure() log.info('Preparing plot for %s at level %s' % (cslice.name(), level)) metadata['name'] = cslice.name() ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=180)) ax.coastlines() fig.add_axes(ax) gl = ax.gridlines(draw_labels=True) gl.xlabels_top = False gl.ylabels_right = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlocator = mticker.FixedLocator([100, 140, 180, -140]) contours = iplt.contourf(cslice, axes=ax) cb = plt.colorbar(contours, orientation='horizontal') cb.ax.set_xlabel(cslice.units) cb.ax.set_aspect(0.03) ax.set_xlabel('longitude') ax.set_ylabel('latitude') metadata['time'] = cube.coord('time').units.num2date(cube.coord('time').points[0]).strftime('%Y-%m-%d_%H:%M:%S') ax.set_title('%s %s (level: %s)' % (cslice.name(), metadata['time'], level)) return fig, metadata
def main(): fname = iris.sample_data_path("NAME_output.txt") boundary_volc_ash_constraint = iris.Constraint("VOLCANIC_ASH_AIR_CONCENTRATION", flight_level="From FL000 - FL200") # Callback shown as None to illustrate where a cube-level callback function would be used if required cube = iris.load_cube(fname, boundary_volc_ash_constraint, callback=None) # draw contour levels for the data (the top level is just a catch-all) levels = (0.0002, 0.002, 0.004, 1e10) cs = iplt.contourf(cube, levels=levels, colors=("#80ffff", "#939598", "#e00404")) # draw a black outline at the lowest contour to highlight affected areas iplt.contour(cube, levels=(levels[0], 100), colors="black") # set an extent and a background image for the map ax = plt.gca() ax.set_extent((-90, 20, 20, 75)) ax.stock_img("ne_shaded") # make a legend, with custom labels, for the coloured contour set artists, _ = cs.legend_elements() labels = [ r"$%s < x \leq %s$" % (levels[0], levels[1]), r"$%s < x \leq %s$" % (levels[1], levels[2]), r"$x > %s$" % levels[2], ] ax.legend(artists, labels, title="Ash concentration / g m-3", loc="upper left") time = cube.coord("time") time_date = time.units.num2date(time.points[0]).strftime(UTC_format) plt.title("Volcanic ash concentration forecast\nvalid at %s" % time_date) iplt.show()
def animation_plot(i, pressure, wind, direction, step=24): """ Function to update the animation frame. """ # Clear figure to refresh colorbar plt.gcf().clf() ax = plt.axes(projection=ccrs.Mercator()) ax.set_extent([-10.5, 3.8, 48.3, 60.5], crs=ccrs.Geodetic()) contour_wind = iplt.contourf(wind[i][::10, ::10], cmap='YlGnBu', levels=range(0, 31, 5)) contour_press = iplt.contour(pressure[i][::10, ::10], colors='white', linewidth=1.25, levels=range(938, 1064, 4)) plt.clabel(contour_press, inline=1, fontsize=14, fmt='%i', colors='white') quiver_plot(wind[i], direction[i], step) plt.gca().coastlines(resolution='50m') time_points = pressure[i].coord('time').points time = str(pressure[i].coord('time').units.num2date(time_points)[0]) plt.gca().set_title(time) colorbar = plt.colorbar(contour_wind) colorbar.ax.set_ylabel('Wind speed ({})'.format(str(wind[i].units)))
def plot_data(cube, month, gridlines=False, levels=None): """Plot the data.""" if not levels: levels = numpy.arange(0, 10) fig = plt.figure(figsize=[12,5]) iplt.contourf(cube, cmap=cmocean.cm.haline_r, levels=levels, extend='max') plt.gca().coastlines() if gridlines: plt.gca().gridlines() cbar = plt.colorbar() cbar.set_label(str(cube.units)) title = '%s precipitation climatology (%s)' %(cube.attributes['model_id'], month) plt.title(title)
def test_cmap_override(self): # Diverging scheme. iplt.contourf(self.cube, cmap=mcm.get_cmap(name='BrBu_10')) self.check_graphic() # Other scheme. iplt.contourf(self.cube, cmap=mcm.get_cmap(name='StepSeq')) self.check_graphic() # Qualitative scheme. iplt.contourf(self.cube, cmap=mcm.get_cmap(name='PairedCat_12')) self.check_graphic() # Sequential scheme. iplt.contourf(self.cube, cmap=mcm.get_cmap(name='LBuDBu_10')) self.check_graphic()
def test_simple(self): # First sub-plot plt.subplot(221) plt.title('Default') iplt.contourf(self.cube) plt.gca().coastlines() # Second sub-plot plt.subplot(222, projection=ccrs.Mollweide(central_longitude=120)) plt.title('Molleweide') iplt.contourf(self.cube) plt.gca().coastlines() # Third sub-plot (the projection part is redundant, but a useful # test none-the-less) ax = plt.subplot(223, projection=iplt.default_projection(self.cube)) plt.title('Native') iplt.contour(self.cube) ax.coastlines() # Fourth sub-plot ax = plt.subplot(2, 2, 4, projection=ccrs.PlateCarree()) plt.title('PlateCarree') iplt.contourf(self.cube) ax.coastlines() self.check_graphic()
def main(): fname = iris.sample_data_path('NAME_output.txt') boundary_volc_ash_constraint = iris.Constraint('VOLCANIC_ASH_AIR_CONCENTRATION', flight_level='From FL000 - FL200') # Callback shown as None to illustrate where a cube-level callback function would be used if required cube = iris.load_strict(fname, boundary_volc_ash_constraint, callback=None) map = iplt.map_setup(lon_range=[-70, 20], lat_range=[20, 75], resolution='i') map.drawcoastlines() iplt.contourf(cube, levels=(0.0002, 0.002, 0.004, 1), colors=('#80ffff', '#939598', '#e00404'), extend='max' ) time = cube.coord('time') time_date = time.units.num2date(time.points[0]).strftime(UTC_format) plt.title('Volcanic ash concentration forecast\nvalid at %s' % time_date) plt.show()
def test_simple(self): # First sub-plot plt.subplot(221) plt.title('Default') iplt.contourf(self.cube) map = iplt.gcm() map.drawcoastlines() # Second sub-plot plt.subplot(222) plt.title('Molleweide') iplt.map_setup(projection='moll', lon_0=120) iplt.contourf(self.cube) map = iplt.gcm() map.drawcoastlines() # Third sub-plot plt.subplot(223) plt.title('Native') iplt.map_setup(cube=self.cube) iplt.contourf(self.cube) map = iplt.gcm() map.drawcoastlines() # Fourth sub-plot plt.subplot(224) plt.title('Three/six level') iplt.contourf(self.cube, 3) iplt.contour(self.cube, 6) map = iplt.gcm() map.drawcoastlines() self.check_graphic()
def test_simple(self): iplt.contourf(self.cube) self.check_graphic()
def test_unmappable(self): cube = self.cube[0, 0] cube.coord('grid_longitude').standard_name = None iplt.contourf(cube) self.check_graphic()
def test_contourf(self): cube = self.cube[0, 0] iplt.contourf(cube) self.check_graphic()
def test_keywords(self): iplt.contourf(self.cube, levels=self.few_levels) self.check_graphic() iplt.contourf(self.cube, levels=self.many_levels, alpha=0.5) self.check_graphic()
def main(): # Load diff cube gl = '/nfs/a90/eepdw/Data/EMBRACE/Mean_State/pp_files/dklz/dklzq/%s.pp' % pp_file glob = iris.load_cube(gl) for experiment_id in experiment_ids: expmin1 = experiment_id[:-1] pfile = '/nfs/a90/eepdw/Data/EMBRACE/Mean_State/pp_files/%s/%s/%s.pp' % (expmin1, experiment_id, pp_file) pcube = iris.load_cube(pfile) lat = pcube.coord('grid_latitude').points lon = pcube.coord('grid_longitude').points cs = pcube.coord_system('CoordSystem') if isinstance(cs, iris.coord_systems.RotatedGeogCS): print ' %s - Unrotate pole %s' % (experiment_id,cs) lons, lats = np.meshgrid(lon, lat) lons,lats = iris.analysis.cartography.unrotate_pole(lons,lats, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude) lon=lons[0] lat=lats[:,0] #pcube.remove_coord('grid_latitude') #pcube.remove_coord('grid_longitude') #pcube.add_dim_coord(iris.coords.DimCoord(points=lat, standard_name='grid_latitude', units='degrees', coord_system=csur), lat_dim_coord) #pcube.add_dim_coord(iris.coords.DimCoord(points=lon, standard_name='grid_longitude', units='degrees', coord_system=csur), lon_dim_coord) lon_min=np.min(lon) lon_max=np.max(lon) lon_low_tick=lon_min -(lon_min%divisor) lon_high_tick=math.ceil(lon_max/divisor)*divisor lat_min=np.min(lat) lat_max=np.max(lat) lat_low_tick=lat_min - (lat_min%divisor) lat_high_tick=math.ceil(lat_max/divisor)*divisor glob.units=pcube.units pcubediff=pcube-glob plt.figure(figsize=(8,8)) cmap= cmap=plt.cm.RdBu_r ax = plt.axes(projection=ccrs.PlateCarree(), extent=(lon_min+degs_crop_left,lon_max-degs_crop_right,lat_min+degs_crop_bottom,lat_max-degs_crop_top)) clevs = np.linspace(min_contour, max_contour,9) cont = iplt.contourf(pcubediff, clevs, cmap=cmap, extend='both') #plt.clabel(cont, fmt='%d') #ax.stock_img() ax.coastlines(resolution='110m', color='#262626') gl = ax.gridlines(draw_labels=True,linewidth=0.5, color='#262626', alpha=0.5, linestyle='--') gl.xlabels_top = False gl.ylabels_right = False #gl.xlines = False dx, dy = 10, 10 gl.xlocator = mticker.FixedLocator(range(int(lon_low_tick),int(lon_high_tick)+dx,dx)) gl.ylocator = mticker.FixedLocator(range(int(lat_low_tick),int(lat_high_tick)+dy,dy)) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 12, 'color':'#262626'} #gl.xlabel_style = {'color': '#262626', 'weight': 'bold'} gl.ylabel_style = {'size': 12, 'color':'#262626'} cbar = plt.colorbar(cont, orientation='horizontal', pad=0.05, extend='both', format = '%d') #cbar.set_label('') cbar.set_label(pcube.units, fontsize=10, color='#262626') cbar.set_ticks(np.arange(min_contour, max_contour+tick_interval,tick_interval)) ticks = (np.arange(min_contour, max_contour+tick_interval,tick_interval)) cbar.set_ticklabels(['%.1f' % i for i in ticks]) main_title='%s - Difference' % pcube.standard_name.title().replace('_',' ') model_info=re.sub('(.{68} )', '\\1\n', str(model_name_convert_title.main(experiment_id)), 0, re.DOTALL) model_info = re.sub(r'[(\']', ' ', model_info) model_info = re.sub(r'[\',)]', ' ', model_info) print model_info if not os.path.exists('%s%s/%s' % (save_path, experiment_id, pp_file)): os.makedirs('%s%s/%s' % (save_path, experiment_id, pp_file)) plt.savefig('%s%s/%s/%s_%s_notitle_diff_8km.png' % (save_path, experiment_id, pp_file, experiment_id, pp_file), format='png', bbox_inches='tight') plt.title('\n'.join(wrap('%s\n%s' % (main_title, model_info), 1000,replace_whitespace=False)), fontsize=16) #plt.show() plt.savefig('%s%s/%s/%s_%s_diff_8km.png' % (save_path, experiment_id, pp_file, experiment_id, pp_file), format='png', bbox_inches='tight') plt.close()
def test_yx_order(self): # Do not attempt to draw coastlines as it is not a map. iplt.contourf(self.cube, coords=['grid_latitude', 'grid_longitude']) self.check_graphic() iplt.contourf(self.cube, coords=['latitude', 'longitude']) self.check_graphic()
def main(): #experiment_ids = ['djznw', 'djzny', 'djznq', 'djzns', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkbhu', 'djznu', 'dkhgu' ] # All 12 #experiment_ids = ['djzny', 'djzns', 'djznw', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq' ] #experiment_ids = ['djzny', 'djzns', 'djznu', 'dkbhu', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkhgu'] #experiment_ids = ['djzns', 'djznu', 'dkbhu', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkhgu'] experiment_ids = ['dklzq', 'dkmbq', 'dkjxq', 'dklwu', 'dklyu', 'djzns'] #experiment_ids = ['djzns' ] #experiment_ids = ['dkhgu','dkjxq'] for experiment_id in experiment_ids: model_info=re.sub('(.{68} )', '\\1\n', str(model_name_convert_title.main(experiment_id)), 0, re.DOTALL) expmin1 = experiment_id[:-1] pfile = '/nfs/a90/eepdw/Data/EMBRACE/Mean_State/pp_files/%s/%s/%s.pp' % (expmin1, experiment_id, pp_file) #pc = iris(pfile) pcube = iris.load_cube(pfile) pcube=iris.analysis.maths.multiply(pcube,3600) # For each hour in cube # Get min and max latitude/longitude and unrotate to get min/max corners to crop plot automatically - otherwise end with blank bits on the edges lats = pcube.coord('grid_latitude').points lons = pcube.coord('grid_longitude').points cs = pcube.coord_system('CoordSystem') if isinstance(cs, iris.coord_systems.RotatedGeogCS): print 'Rotated CS %s' % cs lon_low= np.min(lons) lon_high = np.max(lons) lat_low = np.min(lats) lat_high = np.max(lats) lon_corners, lat_corners = np.meshgrid((lon_low, lon_high), (lat_low, lat_high)) lon_corner_u,lat_corner_u = unrotate.unrotate_pole(lon_corners, lat_corners, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude) lon_low = lon_corner_u[0,0] lon_high = lon_corner_u[0,1] lat_low = lat_corner_u[0,0] lat_high = lat_corner_u[1,0] else: lon_low= np.min(lons) lon_high = np.max(lons) lat_low = np.min(lats) lat_high = np.max(lats) #lon_low= 62 #lon_high = 102 #lat_low = -7 #lat_high = 33 #lon_high_box = 101.866 #lon_low_box = 64.115 #lat_high_box = 33. #lat_low_box =-6.79 #lon_high = 101.866 #lon_low = 64.115 #lat_high = 33. #lat_low =-6.79 lon_low_tick=lon_low -(lon_low%divisor) lon_high_tick=math.ceil(lon_high/divisor)*divisor lat_low_tick=lat_low - (lat_low%divisor) lat_high_tick=math.ceil(lat_high/divisor)*divisor print lat_high_tick print lat_low_tick for t, time_cube in enumerate(pcube.slices(['grid_latitude', 'grid_longitude'])): print time_cube # Get mid-point time of averages h_max = u.num2date(time_cube.coord('time').bounds[0].max()).strftime('%H%M') h_min = u.num2date(time_cube.coord('time').bounds[0].min()).strftime('%H%M') #Convert to India time from_zone = tz.gettz('UTC') to_zone = tz.gettz('Asia/Kolkata') h_max_utc = u.num2date(time_cube.coord('time').bounds[0].max()).replace(tzinfo=from_zone) h_min_utc = u.num2date(time_cube.coord('time').bounds[0].min()).replace(tzinfo=from_zone) h_max_local = h_max_utc.astimezone(to_zone).strftime('%H%M') h_min_local = h_min_utc.astimezone(to_zone).strftime('%H%M') #m = u.num2date(time_cube.coord('time').bounds[0].mean()).minute #h = u.num2date(time_cube.coord('time').bounds[0].mean()).hour #if t==0: fig = plt.figure(**figprops) ax = plt.axes(projection=ccrs.PlateCarree(), extent=(lon_low,lon_high,lat_low+degs_crop_bottom,lat_high-degs_crop_top)) #ax = fig.axes(projection=ccrs.PlateCarree(), extent=(lon_low,lon_high,lat_low,lat_high)) #ax = fig.axes(projection=ccrs.PlateCarree()) cont = iplt.contourf(time_cube, clevs, cmap=cmap, extend='both') #del time_cube #fig.clabel(cont, fmt='%d') #ax.stock_img() ax.coastlines(resolution='110m', color='#262626') gl = ax.gridlines(draw_labels=True,linewidth=0.5, color='#262626', alpha=0.5, linestyle='--') gl.xlabels_top = False gl.ylabels_right = False #gl.xlines = False dx, dy = 10, 10 gl.xlocator = mticker.FixedLocator(range(int(lon_low_tick),int(lon_high_tick)+dx,dx)) gl.ylocator = mticker.FixedLocator(range(int(lat_low_tick),int(lat_high_tick)+dy,dy)) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 12, 'color':'#262626'} #gl.xlabel_style = {'color': '#262626', 'weight': 'bold'} gl.ylabel_style = {'size': 12, 'color':'#262626'} cbar = fig.colorbar(cont, orientation='horizontal', pad=0.05, extend='both') cbar.set_label('mm/h', fontsize=10, color='#262626') #cbar.set_label(time_cube.units, fontsize=10, color='#262626') cbar.set_ticks(np.arange(min_contour, max_contour+tick_interval,tick_interval)) cbar.set_ticklabels(['${%.1f}$' % i for i in ticks]) cbar.ax.tick_params(labelsize=10, color='#262626') # fig.canvas.draw() # background = fig.canvas.copy_from_bbox(fig.bbox) # fig = plt.figure(frameon=False,**figprops) # make sure frame is off, or everything in existing background # will be obliterated. # ax = fig.add_subplot(111,frameon=False) # restore previous background. # fig.canvas.restore_region(background) # time_cube=iris.analysis.maths.multiply(time_cube,3600) # cont = iplt.contourf(time_cube, clevs, cmap=cmap, extend='both') #print cont.collections() ################################################################# ## Bug fix for Quad Contour set not having attribute 'set_visible' # def setvisible(self,vis): # for c in self.collections: c.set_visible(vis) # cont.set_visible = types.MethodType(setvisible,) # cont.axes = plt.gca() # cont.figure=fig #################################################################### #ims.append([im]) main_title='Mean Rainfall for EMBRACE Period -%s-%s UTC (%s-%s IST)' % (h_min, h_max, h_min_local, h_max_local) #main_title=time_cube.standard_name.title().replace('_',' ') #model_info = re.sub(r'[(\']', ' ', model_info) #model_info = re.sub(r'[\',)]', ' ', model_info) #print model_info if not os.path.exists('%s%s/%s' % (save_path, experiment_id, pp_file)): os.makedirs('%s%s/%s' % (save_path, experiment_id, pp_file)) #fig.show() fig.savefig('%s%s/%s/%s_%s_%s-%s_notitle.png' % (save_path, experiment_id, pp_file, experiment_id, pp_file, h_min, h_max), format='png', bbox_inches='tight') plt.title('%s-%s UTC %s-%s IST' % (h_min,h_max, h_min_local, h_max_local)) fig.savefig('%s%s/%s/%s_%s_%s-%s_short_title.png' % (save_path, experiment_id, pp_file, experiment_id, pp_file, h_min, h_max), format='png', bbox_inches='tight') plt.title('\n'.join(wrap('%s\n%s' % (main_title, model_info), 1000,replace_whitespace=False)), fontsize=16) fig.savefig('%s%s/%s/%s_%s_%s-%s.png' % (save_path, experiment_id, pp_file, experiment_id, pp_file, h_min, h_max), format='png', bbox_inches='tight') fig.clf() plt.close() #del time_cube gc.collect()
def main(): #experiment_ids = ['djzny', 'djzns', 'djznw', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq' ] experiment_ids = ['djzny', 'djzns', 'djznu', 'dkbhu', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkhgu'] #experiment_ids = ['djzns' ] #experiment_ids = ['dkhgu','dkjxq'] for experiment_id in experiment_ids: expmin1 = experiment_id[:-1] pfile = '/projects/cascade/pwille/moose_retrievals/%s/%s/%s.pp' % (expmin1, experiment_id, pp_file) #pc = iris(pfile) pcube = iris.load_cube(pfile) print pcube #print pc # Get min and max latitude/longitude and unrotate to get min/max corners to crop plot automatically - otherwise end with blank bits on the edges lats = pcube.coord('grid_latitude').points lons = pcube.coord('grid_longitude').points cs = pcube.coord_system('CoordSystem') if isinstance(cs, iris.coord_systems.RotatedGeogCS): print 'Rotated CS %s' % cs lon_low= np.min(lons) lon_high = np.max(lons) lat_low = np.min(lats) lat_high = np.max(lats) lon_corners, lat_corners = np.meshgrid((lon_low, lon_high), (lat_low, lat_high)) lon_corner_u,lat_corner_u = unrotate.unrotate_pole(lon_corners, lat_corners, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude) lon_low = lon_corner_u[0,0] lon_high = lon_corner_u[0,1] lat_low = lat_corner_u[0,0] lat_high = lat_corner_u[1,0] else: lon_low= np.min(lons) lon_high = np.max(lons) lat_low = np.min(lats) lat_high = np.max(lats) #lon_low= 62 #lon_high = 102 #lat_low = -7 #lat_high = 33 #lon_high_box = 101.866 #lon_low_box = 64.115 #lat_high_box = 33. #lat_low_box =-6.79 #lon_high = 101.866 #lon_low = 64.115 #lat_high = 33. #lat_low =-6.79 lon_low_tick=lon_low -(lon_low%divisor) lon_high_tick=math.ceil(lon_high/divisor)*divisor lat_low_tick=lat_low - (lat_low%divisor) lat_high_tick=math.ceil(lat_high/divisor)*divisor print lat_high_tick print lat_low_tick plt.figure(figsize=(8,8)) cmap=cm.s3pcpn_l ax = plt.axes(projection=ccrs.PlateCarree(), extent=(lon_low,lon_high,lat_low+degs_crop_bottom,lat_high-degs_crop_top)) #ax = plt.axes(projection=ccrs.PlateCarree(), extent=(lon_low,lon_high,lat_low,lat_high)) #ax = plt.axes(projection=ccrs.PlateCarree()) clevs = np.linspace(min_contour, max_contour,256) pcubeplot=iris.analysis.maths.multiply(pcube,3600) cont = iplt.contourf(pcubeplot, clevs, cmap=cmap, extend='both') #plt.clabel(cont, fmt='%d') #ax.stock_img() ax.coastlines(resolution='110m', color='#262626') gl = ax.gridlines(draw_labels=True,linewidth=0.5, color='#262626', alpha=0.5, linestyle='--') gl.xlabels_top = False gl.ylabels_right = False #gl.xlines = False dx, dy = 10, 10 gl.xlocator = mticker.FixedLocator(range(int(lon_low_tick),int(lon_high_tick)+dx,dx)) gl.ylocator = mticker.FixedLocator(range(int(lat_low_tick),int(lat_high_tick)+dy,dy)) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 12, 'color':'#262626'} #gl.xlabel_style = {'color': '#262626', 'weight': 'bold'} gl.ylabel_style = {'size': 12, 'color':'#262626'} cbar = plt.colorbar(cont, orientation='horizontal', pad=0.05, extend='both') cbar.set_label('mm/h', fontsize=14, color='#262626') #cbar.set_label(pcube.units, fontsize=10, color='#262626') cbar.set_ticks(np.arange(min_contour, max_contour+tick_interval,tick_interval)) ticks = (np.arange(min_contour, max_contour+tick_interval,tick_interval)) cbar.set_ticklabels(['%.1f' % i for i in ticks]) cbar.ax.tick_params(labelsize=14, color='#262626') main_title='Mean Rainfall for EMBRACE Period (smoothed to 24km)' #main_title=pcube.standard_name.title().replace('_',' ') model_info=re.sub('(.{68} )', '\\1\n', str(model_name_convert_title.main(experiment_id)), 0, re.DOTALL) #model_info = re.sub(r'[(\']', ' ', model_info) #model_info = re.sub(r'[\',)]', ' ', model_info) #print model_info if not os.path.exists('%s%s/%s' % (save_path, experiment_id, pp_file)): os.makedirs('%s%s/%s' % (save_path, experiment_id, pp_file)) plt.savefig('%s%s/%s/%s_%s_notitle.png' % (save_path, experiment_id, pp_file, experiment_id, pp_file), format='png', bbox_inches='tight') plt.title('\n'.join(wrap('%s\n%s' % (main_title, model_info), 1000,replace_whitespace=False)), fontsize=16) #plt.show() plt.savefig('%s%s/%s/%s_%s.png' % (save_path, experiment_id, pp_file, experiment_id, pp_file), format='png', bbox_inches='tight') plt.close()
w = VectorWind(uwnd, vwnd) # Compute the streamfunction and velocity potential. sf, vp = w.sfvp() # Pick out the field for December. time_constraint = iris.Constraint(month='Dec') add_month(sf, 'time', name='month') add_month(vp, 'time', name='month') sf_dec = sf.extract(time_constraint) vp_dec = vp.extract(time_constraint) # Plot streamfunction. clevs = [-120, -100, -80, -60, -40, -20, 0, 20, 40, 60, 80, 100, 120] ax = plt.subplot(111, projection=ccrs.PlateCarree(central_longitude=180)) fill_sf = iplt.contourf(sf_dec * 1e-06, clevs, cmap=plt.cm.RdBu_r, extend='both') ax.coastlines() ax.gridlines() plt.colorbar(fill_sf, orientation='horizontal') plt.title('Streamfunction ($10^6$m$^2$s$^{-1}$)', fontsize=16) # Plot velocity potential. plt.figure() clevs = [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10] ax = plt.subplot(111, projection=ccrs.PlateCarree(central_longitude=180)) fill_vp = iplt.contourf(vp_dec * 1e-06, clevs, cmap=plt.cm.RdBu_r, extend='both') ax.coastlines() ax.gridlines() plt.colorbar(fill_vp, orientation='horizontal') plt.title('Velocity Potential ($10^6$m$^2$s$^{-1}$)', fontsize=16)
def test_default(self): iplt.contourf(self.cube) plt.gca().coastlines() self.check_graphic()
import iris.plot as iplt import matplotlib.pyplot as plt import numpy as np import re import string import itertools input = '[AAAA]' n1 = len(input.split(' ')[0]) - 2 s1 = input[n1+2:] names = [''.join(x)+s1 for x in itertools.product(string.ascii_lowercase, repeat=n1)] #data from http://cdiac.ornl.gov/ftp/oceans/GLODAP_Gridded_Data/ cube = iris.load('/home/ph290/Downloads/CFC11/CFC11.nc','CFC-11') cube = cube[0] cube.coord('depth').points=cube.coord('depth').points*(-1.0) for i in np.arange(359): plt.figure() meridional_slice2 = cube.extract(iris.Constraint(longitude=-179.5+i)) qplt.contourf(meridional_slice2, levels = np.linspace(0.0,8,50), coords=['latitude','depth']) #plt.show() plt.savefig('/home/ph290/Downloads/anim3/anim_'+names[i]+'.png') for i in np.arange(359): plt.figure() iplt.contourf(cube[0], 50) plt.gca().coastlines() plt.plot([-180+i,-180+i],[-90,90],'k', linewidth = 5) plt.savefig('/home/ph290/Downloads/anim4/anim_'+names[i]+'.png')
# Create a VectorWind instance to handle the computations. w = VectorWind(uwnd, vwnd) # Compute components of rossby wave source: absolute vorticity, divergence, # irrotational (divergent) wind components, gradients of absolute vorticity. eta = w.absolutevorticity() div = w.divergence() uchi, vchi = w.irrotationalcomponent() etax, etay = w.gradient(eta) etax.units = 'm**-1 s**-1' etay.units = 'm**-1 s**-1' # Combine the components to form the Rossby wave source term. S = eta * -1. * div - (uchi * etax + vchi * etay) S.coord('longitude').attributes['circular'] = True # Pick out the field for December at 200 hPa. time_constraint = iris.Constraint(month='Dec') add_month(S, 'time') S_dec = S.extract(time_constraint) # Plot Rossby wave source. clevs = [-30, -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30] ax = plt.subplot(111, projection=ccrs.PlateCarree(central_longitude=180)) fill = iplt.contourf(S_dec * 1e11, clevs, cmap=plt.cm.RdBu_r, extend='both') ax.coastlines() ax.gridlines() plt.colorbar(fill, orientation='horizontal') plt.title('Rossby Wave Source ($10^{-11}$s$^{-1}$)', fontsize=16) plt.show()