def main(): fname = iris.sample_data_path('air_temp.pp') temperature = iris.load_strict(fname) qplt.contourf(temperature, 15) iplt.gcm().drawcoastlines() 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 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]) iplt.gcm(cubes[0]).drawcoastlines() 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]) iplt.gcm(cubes[0]).drawcoastlines() 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]) iplt.gcm(cubes[0]).drawcoastlines() 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]) iplt.gcm(cubes[0]).drawcoastlines() plt.title("ineg_jpos cube") self.check_graphic()
def main(): fname = iris.sample_data_path('rotated_pole.nc') temperature = iris.load_strict(fname) # Calculate the lat lon range and buffer it by 10 degrees lat_range, lon_range = iris.analysis.cartography.lat_lon_range(temperature) lat_range = lat_range[0] - 10, lat_range[1] + 10 lon_range = lon_range[0] - 10, lon_range[1] + 10 # Plot #1: Point plot showing data values & a colorbar plt.figure() iplt.map_setup(temperature, lat_range=lat_range, lon_range=lon_range) points = qplt.points(temperature, c=temperature.data) cb = plt.colorbar(points, orientation='horizontal') cb.set_label(temperature.units) iplt.gcm().drawcoastlines() plt.show() # Plot #2: Contourf of the point based data plt.figure() iplt.map_setup(temperature, lat_range=lat_range, lon_range=lon_range) qplt.contourf(temperature, 15) iplt.gcm().drawcoastlines() plt.show() # Plot #3: Contourf overlayed by coloured point data plt.figure() iplt.map_setup(temperature, lat_range=lat_range, lon_range=lon_range) qplt.contourf(temperature) iplt.points(temperature, c=temperature.data) iplt.gcm().drawcoastlines() plt.show() # For the purposes of this example, add some bounds to the latitude and longitude temperature.coord('grid_latitude').guess_bounds() temperature.coord('grid_longitude').guess_bounds() # Plot #4: Block plot plt.figure() iplt.map_setup(temperature, lat_range=lat_range, lon_range=lon_range) iplt.pcolormesh(temperature) iplt.gcm().bluemarble() iplt.gcm().drawcoastlines() 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 main(): # Load the "total electron content" cube. filename = iris.sample_data_path('space_weather.nc') cube = iris.load_strict(filename, 'total electron content') # Explicitly mask negative electron content. cube.data = np.ma.masked_less(cube.data, 0) # Currently require to remove the multi-dimensional # latitude and longitude coordinates for Iris plotting. cube.remove_coord('latitude') cube.remove_coord('longitude') # Plot the cube using one hundred colour levels. qplt.contourf(cube, 100) plt.title('Total Electron Content') plt.xlabel('longitude / degrees') plt.ylabel('latitude / degrees') iplt.gcm().bluemarble(zorder=-1) iplt.gcm().drawcoastlines() 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(): # extract surface temperature cubes which have an ensemble member coordinate, adding appropriate lagged ensemble metadata surface_temp = iris.load_strict( iris.sample_data_path('GloSea4', 'ensemble_???.pp'), iris.Constraint('surface_temperature', realization=lambda value: True), callback=realization_metadata, ) # ---------------------------------------------------------------------------------------------------------------- # Plot #1: Ensemble postage stamps # ---------------------------------------------------------------------------------------------------------------- # for the purposes of this example, take the last time element of the cube last_timestep = surface_temp[:, -1, :, :] # Make 50 evenly spaced levels which span the dataset contour_levels = numpy.linspace(numpy.min(last_timestep.data), numpy.max(last_timestep.data), 50) # Create a wider than normal figure to support our many plots plt.figure(figsize=(12, 6), dpi=100) # Also manually adjust the spacings which are used when creating subplots plt.gcf().subplots_adjust(hspace=0.05, wspace=0.05, top=0.95, bottom=0.05, left=0.075, right=0.925) # iterate over all possible latitude longitude slices for cube in last_timestep.slices(['latitude', 'longitude']): # get the ensemble member number from the ensemble coordinate ens_member = cube.coord('realization').points[0] # plot the data in a 4x4 grid, with each plot's position in the grid being determined by ensemble member number # the special case for the 13th ensemble member is to have the plot at the bottom right if ens_member == 13: plt.subplot(4, 4, 16) else: plt.subplot(4, 4, ens_member + 1) cf = iplt.contourf(cube, contour_levels) # add coastlines m = iplt.gcm() m.drawcoastlines() # make an axes to put the shared colorbar in colorbar_axes = plt.gcf().add_axes([0.35, 0.1, 0.3, 0.05]) colorbar = plt.colorbar(cf, colorbar_axes, orientation='horizontal') colorbar.set_label('%s' % last_timestep.units) # limit the colorbar to 8 tick marks import matplotlib.ticker colorbar.locator = matplotlib.ticker.MaxNLocator(8) colorbar.update_ticks() # get the time for the entire plot time_coord = last_timestep.coord('time') time = time_coord.units.num2date(time_coord.points[0]) # set a global title for the postage stamps with the date formated by "monthname year" plt.suptitle('Surface temperature ensemble forecasts for %s' % time.strftime('%B %Y')) iplt.show() # ---------------------------------------------------------------------------------------------------------------- # Plot #2: ENSO plumes # ---------------------------------------------------------------------------------------------------------------- # Nino 3.4 lies between: 170W and 120W, 5N and 5S, so define a constraint which matches this nino_3_4_constraint = iris.Constraint( longitude=lambda v: -170 + 360 <= v <= -120 + 360, latitude=lambda v: -5 <= v <= 5) nino_cube = surface_temp.extract(nino_3_4_constraint) # Subsetting a circular longitude coordinate always results in a circular coordinate, so set the coordinate to be non-circular nino_cube.coord('longitude').circular = False # Calculate the horizontal mean for the nino region mean = nino_cube.collapsed(['latitude', 'longitude'], iris.analysis.MEAN) # Calculate the ensemble mean of the horizontal mean. To do this, remove the "forecast_period" and # "forecast_reference_time" coordinates which span both "relalization" and "time". mean.remove_coord("forecast_reference_time") mean.remove_coord("forecast_period") ensemble_mean = mean.collapsed('realization', iris.analysis.MEAN) # take the ensemble mean from each ensemble member mean -= ensemble_mean.data plt.figure() for ensemble_member in mean.slices(['time']): # draw each ensemble member as a dashed line in black iplt.plot(ensemble_member, '--k', coords=['time']) plt.title('Mean temperature anomaly for ENSO 3.4 region') plt.xlabel('Time') plt.ylabel('Temperature anomaly / K') plt.show()
def test_scatter(self): iplt.points(self.cube) map = iplt.gcm() map.drawcoastlines() self.check_graphic()
def main(): # Load e1 and a1 using the callback to update the metadata e1 = iris.load_strict(iris.sample_data_path('E1.2098.pp'), callback=cop_metadata_callback) a1b = iris.load_strict(iris.sample_data_path('A1B.2098.pp'), callback=cop_metadata_callback) # Load the global average data and add an 'Experiment' coord it global_avg = iris.load_strict(iris.sample_data_path('pre-industrial.pp')) # Define evenly spaced contour levels: -2.5, -1.5, ... 15.5, 16.5 with the specific colours levels = numpy.arange(20) - 2.5 red = numpy.array([0, 0, 221, 239, 229, 217, 239, 234, 228, 222, 205, 196, 161, 137, 116, 89, 77, 60, 51]) / 256. green = numpy.array([16, 217, 242, 243, 235, 225, 190, 160, 128, 87, 72, 59, 33, 21, 29, 30, 30, 29, 26]) / 256. blue = numpy.array([255, 255, 243, 169, 99, 51, 63, 37, 39, 21, 27, 23, 22, 26, 29, 28, 27, 25, 22]) / 256. # Put those colours into an array which can be passed to conourf as the specific colours for each level colors = numpy.array([red, green, blue]).T # Subtract the global # Iterate over each latitude longitude slice for both e1 and a1b scenarios simultaneously for e1_slice, a1b_slice in itertools.izip(e1.slices(['latitude', 'longitude']), a1b.slices(['latitude', 'longitude'])): time_coord = a1b_slice.coord('time') # Calculate the difference from the mean delta_e1 = e1_slice - global_avg delta_a1b = a1b_slice - global_avg # Make a wider than normal figure to house two maps side-by-side fig = plt.figure(figsize=(12, 5)) # Get the time datetime from the coordinate time = time_coord.units.num2date(time_coord.points[0]) # Set a title for the entire figure, giving the time in a nice format of "MonthName Year". Also, set the y value for the # title so that it is not tight to the top of the plot. fig.suptitle('Annual Temperature Predictions for ' + time.strftime("%Y"), y=0.9, fontsize=18) # Add the first subplot showing the E1 scenario plt.subplot(121) plt.title('HadGEM2 E1 Scenario', fontsize=10) iplt.contourf(delta_e1, levels, colors=colors, linewidth=0, extend='both') current_map = iplt.gcm() current_map.drawcoastlines() # get the current axes' subplot for use later on plt1_ax = plt.gca() # Add the second subplot showing the A1B scenario plt.subplot(122) plt.title('HadGEM2 A1B-Image Scenario', fontsize=10) contour_result = iplt.contourf(delta_a1b, levels, colors=colors, linewidth=0, extend='both') current_map = iplt.gcm() current_map.drawcoastlines() # get the current axes' subplot for use later on plt2_ax = plt.gca() # Now add a colourbar who's leftmost point is the same as the leftmost point of the left hand plot # and rightmost point is the rightmost point of the right hand plot # Get the positions of the 2nd plot and the left position of the 1st plot left, bottom, width, height = plt2_ax.get_position().bounds first_plot_left = plt1_ax.get_position().bounds[0] # the width of the colorbar should now be simple width = left - first_plot_left + width # Add axes to the figure, to place the colour bar colorbar_axes = fig.add_axes([first_plot_left, bottom + 0.07, width, 0.03]) # Add the colour bar cbar = plt.colorbar(contour_result, colorbar_axes, orientation='horizontal') # Label the colour bar and add ticks cbar.set_label(e1_slice.units) cbar.ax.tick_params(length=0) plt.show()
def main(): # extract surface temperature cubes which have an ensemble member coordinate, adding appropriate lagged ensemble metadata surface_temp = iris.load_strict(iris.sample_data_path('GloSea4', 'ensemble_???.pp'), iris.Constraint('surface_temperature', realization=lambda value: True), callback=realization_metadata, ) # ---------------------------------------------------------------------------------------------------------------- # Plot #1: Ensemble postage stamps # ---------------------------------------------------------------------------------------------------------------- # for the purposes of this example, take the last time element of the cube last_timestep = surface_temp[:, -1, :, :] # Make 50 evenly spaced levels which span the dataset contour_levels = numpy.linspace(numpy.min(last_timestep.data), numpy.max(last_timestep.data), 50) # Create a wider than normal figure to support our many plots plt.figure(figsize=(12, 6), dpi=100) # Also manually adjust the spacings which are used when creating subplots plt.gcf().subplots_adjust(hspace=0.05, wspace=0.05, top=0.95, bottom=0.05, left=0.075, right=0.925) # iterate over all possible latitude longitude slices for cube in last_timestep.slices(['latitude', 'longitude']): # get the ensemble member number from the ensemble coordinate ens_member = cube.coord('realization').points[0] # plot the data in a 4x4 grid, with each plot's position in the grid being determined by ensemble member number # the special case for the 13th ensemble member is to have the plot at the bottom right if ens_member == 13: plt.subplot(4, 4, 16) else: plt.subplot(4, 4, ens_member+1) cf = iplt.contourf(cube, contour_levels) # add coastlines m = iplt.gcm() m.drawcoastlines() # make an axes to put the shared colorbar in colorbar_axes = plt.gcf().add_axes([0.35, 0.1, 0.3, 0.05]) colorbar = plt.colorbar(cf, colorbar_axes, orientation='horizontal') colorbar.set_label('%s' % last_timestep.units) # limit the colorbar to 8 tick marks import matplotlib.ticker colorbar.locator = matplotlib.ticker.MaxNLocator(8) colorbar.update_ticks() # get the time for the entire plot time_coord = last_timestep.coord('time') time = time_coord.units.num2date(time_coord.points[0]) # set a global title for the postage stamps with the date formated by "monthname year" plt.suptitle('Surface temperature ensemble forecasts for %s' % time.strftime('%B %Y')) iplt.show() # ---------------------------------------------------------------------------------------------------------------- # Plot #2: ENSO plumes # ---------------------------------------------------------------------------------------------------------------- # Nino 3.4 lies between: 170W and 120W, 5N and 5S, so define a constraint which matches this nino_3_4_constraint = iris.Constraint(longitude=lambda v: -170+360 <= v <= -120+360, latitude=lambda v: -5 <= v <= 5) nino_cube = surface_temp.extract(nino_3_4_constraint) # Subsetting a circular longitude coordinate always results in a circular coordinate, so set the coordinate to be non-circular nino_cube.coord('longitude').circular = False # Calculate the horizontal mean for the nino region mean = nino_cube.collapsed(['latitude', 'longitude'], iris.analysis.MEAN) # Calculate the ensemble mean of the horizontal mean. To do this, remove the "forecast_period" and # "forecast_reference_time" coordinates which span both "relalization" and "time". mean.remove_coord("forecast_reference_time") mean.remove_coord("forecast_period") ensemble_mean = mean.collapsed('realization', iris.analysis.MEAN) # take the ensemble mean from each ensemble member mean -= ensemble_mean.data plt.figure() for ensemble_member in mean.slices(['time']): # draw each ensemble member as a dashed line in black iplt.plot(ensemble_member, '--k', coords=['time']) plt.title('Mean temperature anomaly for ENSO 3.4 region') plt.xlabel('Time') plt.ylabel('Temperature anomaly / K') plt.show()
def main(): # Load e1 and a1 using the callback to update the metadata e1 = iris.load_strict(iris.sample_data_path('E1.2098.pp'), callback=cop_metadata_callback) a1b = iris.load_strict(iris.sample_data_path('A1B.2098.pp'), callback=cop_metadata_callback) # Load the global average data and add an 'Experiment' coord it global_avg = iris.load_strict(iris.sample_data_path('pre-industrial.pp')) # Define evenly spaced contour levels: -2.5, -1.5, ... 15.5, 16.5 with the specific colours levels = numpy.arange(20) - 2.5 red = numpy.array([ 0, 0, 221, 239, 229, 217, 239, 234, 228, 222, 205, 196, 161, 137, 116, 89, 77, 60, 51 ]) / 256. green = numpy.array([ 16, 217, 242, 243, 235, 225, 190, 160, 128, 87, 72, 59, 33, 21, 29, 30, 30, 29, 26 ]) / 256. blue = numpy.array([ 255, 255, 243, 169, 99, 51, 63, 37, 39, 21, 27, 23, 22, 26, 29, 28, 27, 25, 22 ]) / 256. # Put those colours into an array which can be passed to conourf as the specific colours for each level colors = numpy.array([red, green, blue]).T # Subtract the global # Iterate over each latitude longitude slice for both e1 and a1b scenarios simultaneously for e1_slice, a1b_slice in itertools.izip( e1.slices(['latitude', 'longitude']), a1b.slices(['latitude', 'longitude'])): time_coord = a1b_slice.coord('time') # Calculate the difference from the mean delta_e1 = e1_slice - global_avg delta_a1b = a1b_slice - global_avg # Make a wider than normal figure to house two maps side-by-side fig = plt.figure(figsize=(12, 5)) # Get the time datetime from the coordinate time = time_coord.units.num2date(time_coord.points[0]) # Set a title for the entire figure, giving the time in a nice format of "MonthName Year". Also, set the y value for the # title so that it is not tight to the top of the plot. fig.suptitle('Annual Temperature Predictions for ' + time.strftime("%Y"), y=0.9, fontsize=18) # Add the first subplot showing the E1 scenario plt.subplot(121) plt.title('HadGEM2 E1 Scenario', fontsize=10) iplt.contourf(delta_e1, levels, colors=colors, linewidth=0, extend='both') current_map = iplt.gcm() current_map.drawcoastlines() # get the current axes' subplot for use later on plt1_ax = plt.gca() # Add the second subplot showing the A1B scenario plt.subplot(122) plt.title('HadGEM2 A1B-Image Scenario', fontsize=10) contour_result = iplt.contourf(delta_a1b, levels, colors=colors, linewidth=0, extend='both') current_map = iplt.gcm() current_map.drawcoastlines() # get the current axes' subplot for use later on plt2_ax = plt.gca() # Now add a colourbar who's leftmost point is the same as the leftmost point of the left hand plot # and rightmost point is the rightmost point of the right hand plot # Get the positions of the 2nd plot and the left position of the 1st plot left, bottom, width, height = plt2_ax.get_position().bounds first_plot_left = plt1_ax.get_position().bounds[0] # the width of the colorbar should now be simple width = left - first_plot_left + width # Add axes to the figure, to place the colour bar colorbar_axes = fig.add_axes( [first_plot_left, bottom + 0.07, width, 0.03]) # Add the colour bar cbar = plt.colorbar(contour_result, colorbar_axes, orientation='horizontal') # Label the colour bar and add ticks cbar.set_label(e1_slice.units) cbar.ax.tick_params(length=0) plt.show()