def testSetPlotFilledContourLargeRange(self):
   cube = iris.load_cube(iris.sample_data_path('air_temp.pp'))
   plt.subplot(1,2,1)
   cc.setPlot(cube, "Filled Contour", "brewer_Blues_09", 15, True, 400, 200)
   plt.subplot(1,2,2)
   qplt.contourf(cube, 15, cmap="brewer_Blues_09", vmin=200, vmax=400)
   
   plt.show()
Example #2
0
 def test_missing_cs(self):
     cube = tests.stock.simple_pp()
     cube.coord("latitude").coord_system = None
     cube.coord("longitude").coord_system = None
     qplt.contourf(cube)
     qplt.plt.gca().coastlines()
     self.check_graphic()
Example #3
0
def main():
    fname = iris.sample_data_path('air_temp.pp')
    temperature = iris.load_cube(fname)

    qplt.contourf(temperature, 15)
    plt.gca().coastlines()
    plt.show()
Example #4
0
def main():
    fname = iris.sample_data_path('ostia_monthly.nc')
    
    # load a single cube of surface temperature between +/- 5 latitude
    cube = iris.load_cube(fname, iris.Constraint('surface_temperature', latitude=lambda v: -5 < v < 5))
    
    # Take the mean over latitude
    cube = cube.collapsed('latitude', iris.analysis.MEAN)
    
    # Now that we have our data in a nice way, lets create the plot
    # contour with 20 levels
    qplt.contourf(cube, 20)
    
    # Put a custom label on the y axis 
    plt.ylabel('Time / years')
    
    # Stop matplotlib providing clever axes range padding
    plt.axis('tight')
    
    # As we are plotting annual variability, put years as the y ticks
    plt.gca().yaxis.set_major_locator(mdates.YearLocator())
    
    # And format the ticks to just show the year
    plt.gca().yaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    
    plt.show()
def read_and_plot(file_name, temp_model, var_name, output_directory):
    # function to read ans plot CMIP5 data

    print file_name.strip()

    var = iris.load_cube(file_name.strip())

    # Projection is required because the coords are not monotonic.
    var_regridded, extent = iris.analysis.cartography.project(var[0, :, :], ccrs.PlateCarree())

    # We now have two recognisable "x" and "y" coordinates,
    # which currently confuses plotting code.
    var_regridded.remove_coord("latitude")
    var_regridded.remove_coord("longitude")

    # set plot window size
    qplt.plt.figure()

    # plot
    qplt.contourf(var_regridded, 30)

    # add coastlines
    qplt.plt.gca().coastlines()
    plt.title(temp_model + " " + var_name)
    # show the plot
    # qplt.plt.show()
    outfile = output_directory + "/" + temp_model.strip() + "_" + var_name + ".png"
    plt.savefig(outfile)
Example #6
0
def main():
    # Enable a future option, to ensure that the netcdf load works the same way
    # as in future Iris versions.
    iris.FUTURE.netcdf_promote = True

    # Load the whole time-sequence as a single cube.
    file_path = iris.sample_data_path('E1_north_america.nc')
    cube = iris.load_cube(file_path)

    # Make an aggregator from the user function.
    SPELL_COUNT = Aggregator('spell_count',
                             count_spells,
                             units_func=lambda units: 1)

    # Define the parameters of the test.
    threshold_temperature = 280.0
    spell_years = 5

    # Calculate the statistic.
    warm_periods = cube.collapsed('time', SPELL_COUNT,
                                  threshold=threshold_temperature,
                                  spell_length=spell_years)
    warm_periods.rename('Number of 5-year warm spells in 240 years')

    # Plot the results.
    qplt.contourf(warm_periods, cmap='RdYlBu_r')
    plt.gca().coastlines()
    iplt.show()
 def testSetPlotFilledContourPlain(self):
   cube = iris.load_cube(iris.sample_data_path('air_temp.pp'))
   plt.subplot(1,2,1)
   cc.setPlot(cube, "Filled Contour", "Automatic", 15, False, None, None)
   plt.subplot(1,2,2)
   qplt.contourf(cube, 15)
   plt.show()
Example #8
0
def main():
    # Enable a future option, to ensure that the netcdf load works the same way
    # as in future Iris versions.
    iris.FUTURE.netcdf_promote = True

    # Load some test data.
    fname = iris.sample_data_path('hybrid_height.nc')
    theta = iris.load_cube(fname, 'air_potential_temperature')

    # Extract a single height vs longitude cross-section. N.B. This could
    # easily be changed to extract a specific slice, or even to loop over *all*
    # cross section slices.
    cross_section = next(theta.slices(['grid_longitude',
                                       'model_level_number']))

    qplt.contourf(cross_section, coords=['grid_longitude', 'altitude'],
                  cmap='RdBu_r')
    iplt.show()

    # Now do the equivalent plot, only against model level
    plt.figure()

    qplt.contourf(cross_section,
                  coords=['grid_longitude', 'model_level_number'],
                  cmap='RdBu_r')
    iplt.show()
Example #9
0
    def test_contourf_axes_specified(self):
        # Check that the contourf function does not modify the matplotlib
        # pyplot state machine.

        # Create a figure and axes to be used by contourf
        plt.figure()
        axes1 = plt.axes()

        # Create test figure and axes which will be the new results
        # of plt.gcf and plt.gca.
        plt.figure()
        axes2 = plt.axes()

        # Add a title to the test axes.
        plt.title('This should not be changed')
        # Draw the contourf on a specific axes.
        qplt.contourf(self._small(), axes=axes1)

        # Ensure that the correct axes got the appropriate title.
        self.assertEqual(axes2.get_title(), 'This should not be changed')
        self.assertEqual(axes1.get_title(), 'Air potential temperature')

        # Check that the axes labels were set correctly.
        self.assertEqual(axes1.get_xlabel(), 'Grid longitude / degrees')
        self.assertEqual(axes1.get_ylabel(), 'Altitude / m')
Example #10
0
def main():
    fname = iris.sample_data_path('air_temp.pp')
    temperature = iris.load_strict(fname)
    
    qplt.contourf(temperature, 15)
    iplt.gcm().drawcoastlines()
    plt.show()
Example #11
0
def main():
    file_path = iris.sample_data_path('polar_stereo.grib2')
    cube = iris.load_cube(file_path)
    qplt.contourf(cube)
    ax = plt.gca()
    ax.coastlines()
    ax.gridlines()
    plt.show()
Example #12
0
def plot_cube(cube, N, M, n, levels = [0, 0.1, 0.15, 0.2, .25, 0.3], cmap = 'brewer_Greys_09'):
    plt.subplot(N, M, n, projection=ccrs.Robinson())

    cmap = plt.get_cmap(cmap)
    norm = BoundaryNorm(levels, ncolors=cmap.N - 1)

    qplt.contourf(cube,levels = levels,  cmap = cmap, norm = norm, extend = 'max')
    plt.gca().coastlines() 
Example #13
0
def runme():

    # Load a cube into Iris
    filename = iris.sample_data_path("A1B.2098.pp")
    cube = iris.load_cube(filename)
    cube.coord(axis="x").guess_bounds()
    cube.coord(axis="y").guess_bounds()

    # Plot the cube with Iris, just to see it.
    qplt.contourf(cube)
    qplt.plt.gca().coastlines()
    qplt.show()
    
    # Export as GeoTIFF (shouldn't have to write to a physical file)
    iris.experimental.raster.export_geotiff(cube, 'temp.geotiff')
    data = open('temp.geotiff', "rb").read()

    # Publish to geoserver
    server = "localhost:8082"
    username, password = '******', 'geoserver'
    connect_to_server(server, username, password)

    workspace = "iris_test_ws"
    if not exists_workspace(server, workspace):
        create_workspace(server, workspace)
    
    coveragestore = "iris_test_cs"
    if not exists_coveragestore(server, workspace, coveragestore):
        create_coveragestore(server, workspace, coveragestore)

    filename = "file.geotiff"
    upload_file(server, workspace, coveragestore, filename, data)
    
    # Tell geoserver it's global EPSG:4326. Shouldn't need this eventually.
    coverage = coveragestore  # (they get the same name from geoserver)
    data = '<coverage>'\
                '<srs>EPSG:4326</srs>'\
                '<nativeCRS>EPSG:4326</nativeCRS>'\
                ' <nativeBoundingBox>'\
                    '<minx>-180.0</minx>'\
                    '<maxx>180.0</maxx>'\
                    '<miny>-90.0</miny>'\
                    '<maxy>90.0</maxy>'\
                    '<crs>EPSG:4326</crs>'\
                '</nativeBoundingBox>'\
                '<enabled>true</enabled>'\
            '</coverage>'
    update_coverage(server, workspace, coveragestore, coverage, data)

    # Use the new WMS service as a background image!
    wms_server = '{server}/{workspace}/wms?service=WMS'.format(server=server, workspace=workspace)
    layers = '{workspace}:{coveragestore}'.format(workspace=workspace, coveragestore=coveragestore)
    
    plt.axes(projection=ccrs.PlateCarree())
    plt.gca().set_extent([-40, 40, 20, 80])
    wms_image(wms_server, layers)
    plt.gca().coastlines()
    plt.show()
Example #14
0
def main():
    # Load the u and v components of wind from a pp file
    infile = iris.sample_data_path('wind_speed_lake_victoria.pp')

    uwind = iris.load_cube(infile, 'x_wind')
    vwind = iris.load_cube(infile, 'y_wind')

    ulon = uwind.coord('longitude')
    vlon = vwind.coord('longitude')

    # The longitude points go from 180 to 540, so subtract 360 from them
    ulon.points = ulon.points - 360.0
    vlon.points = vlon.points - 360.0

    # Create a cube containing the wind speed
    windspeed = (uwind ** 2 + vwind ** 2) ** 0.5
    windspeed.rename('windspeed')

    x = ulon.points
    y = uwind.coord('latitude').points
    u = uwind.data
    v = vwind.data

    # Set up axes to show the lake
    lakes = cfeat.NaturalEarthFeature('physical', 'lakes', '50m',
                                      facecolor='none')

    plt.figure()
    ax = plt.axes(projection=ccrs.PlateCarree())
    ax.add_feature(lakes)

    # Get the coordinate reference system used by the data
    transform = ulon.coord_system.as_cartopy_projection()

    # Plot the wind speed as a contour plot
    qplt.contourf(windspeed, 20)

    # Add arrows to show the wind vectors
    plt.quiver(x, y, u, v, pivot='middle', transform=transform)

    plt.title("Wind speed over Lake Victoria")
    qplt.show()

    # Normalise the data for uniform arrow size
    u_norm = u / np.sqrt(u ** 2.0 + v ** 2.0)
    v_norm = v / np.sqrt(u ** 2.0 + v ** 2.0)

    plt.figure()
    ax = plt.axes(projection=ccrs.PlateCarree())
    ax.add_feature(lakes)

    qplt.contourf(windspeed, 20)

    plt.quiver(x, y, u_norm, v_norm, pivot='middle', transform=transform)

    plt.title("Wind speed over Lake Victoria")
    qplt.show()
Example #15
0
 def test_polar_stereo_grib1(self):
     cube = iris.load_cube(tests.get_data_path(
         ("GRIB", "polar_stereo", "ST4.2013052210.01h")))
     self.assertCML(cube, ("grib_load", "polar_stereo_grib1.cml"))
     qplt.contourf(cube, norm=LogNorm())
     plt.gca().coastlines()
     plt.gca().gridlines()
     plt.title("polar stereo grib1")
     self.check_graphic()
Example #16
0
    def test_lambert_grib2(self):
        cube = iris.load_cube(tests.get_data_path(
            ("GRIB", "lambert", "lambert.grib2")))
        self.assertCML(cube, ("grib_load", "lambert_grib2.cml"))

        qplt.contourf(cube)
        plt.gca().coastlines()
        plt.gca().gridlines()
        plt.title("lambert grib2")
        self.check_graphic()
Example #17
0
    def test_polar_stereo_grib2(self):
        cube = iris.load_cube(tests.get_data_path(
            ("GRIB", "polar_stereo",
             "CMC_glb_TMP_ISBL_1015_ps30km_2013052000_P006.grib2")))
        self.assertCML(cube, ("grib_load", "polar_stereo_grib2.cml"))

        qplt.contourf(cube)
        plt.gca().coastlines()
        plt.gca().gridlines()
        plt.title("polar stereo grib2")
        self.check_graphic()
Example #18
0
def main():
    # Enable a future option, to ensure that the grib load works the same way
    # as in future Iris versions.
    iris.FUTURE.strict_grib_load = True

    file_path = iris.sample_data_path('polar_stereo.grib2')
    cube = iris.load_cube(file_path)
    qplt.contourf(cube)
    ax = plt.gca()
    ax.coastlines()
    ax.gridlines()
    iplt.show()
Example #19
0
def level_plot(cube,saving_path,name,level=0,color_levels=9,cmap=plt.cm.CMRmap_r,logscale=0):
    if logscale:
        qplt.contourf(cube[level,],color_levels,cmap=cmap,norm=matplotlib.colors.LogNorm())
    else:
        qplt.contourf(cube[level,],color_levels,cmap=cmap)
    plt.gca().coastlines()
    if level==0:
        saving_str=saving_path+'Surface_level_'+name+'.png'
    else:
        saving_str=saving_path+'Level_%i_'%level+name+'.png'
    plt.savefig(saving_str,bbox_inches='tight')
    plt.close()
Example #20
0
def main():
    fname = iris.sample_data_path('colpex.pp')
    
    # The list of phenomena of interest
    phenomena = ['air_potential_temperature', 'air_pressure']
    
    # Define the constraint on standard name and model level
    constraints = [iris.Constraint(phenom, model_level_number=1) for
                   phenom in phenomena]
    
    air_potential_temperature, air_pressure = iris.load_cubes(fname,
                                                              constraints) 
    
    # Define a coordinate which represents 1000 hPa
    p0 = coords.AuxCoord(1000, long_name='P0', units='hPa')
    # Convert reference pressure 'p0' into the same units as 'air_pressure'
    p0.convert_units(air_pressure.units)
    
    # Calculate Exner pressure
    exner_pressure = (air_pressure / p0) ** (287.05 / 1005.0)
    # Set the name (the unit is scalar)
    exner_pressure.rename('exner_pressure')
    
    # Calculate air_temp
    air_temperature = exner_pressure * air_potential_temperature
    # Set the name (the unit is K)
    air_temperature.rename('air_temperature')
    
    # Now create an iterator which will give us lat lon slices of
    # exner pressure and air temperature in the form
    # (exner_slice, air_temp_slice).
    lat_lon_slice_pairs = iris.iterate.izip(exner_pressure,
                                            air_temperature,
                                            coords=['grid_latitude',
                                                    'grid_longitude'])

    plt.figure(figsize=(8, 4))
    for exner_slice, air_temp_slice in lat_lon_slice_pairs:
        plt.subplot(121)
        cont = qplt.contourf(exner_slice)
    
        # The default colorbar has a few too many ticks on it, causing text to
        # overlap. Therefore, limit the number of ticks.
        limit_colorbar_ticks(cont)
    
        plt.subplot(122)
        cont = qplt.contourf(air_temp_slice)
        limit_colorbar_ticks(cont)
        plt.show()
    
        # For the purposes of this example, break after the first loop - we
        # only want to demonstrate the first plot.
        break
Example #21
0
    def test_load(self):
        cube = iris.load(
            tests.get_data_path(
                ('NIMROD', 'uk2km', 'WO0000000003452',
                 '201007020900_u1096_ng_ey00_visibility0180_screen_2km')))[0]
        self.assertCML(cube, ("nimrod", "load.cml"))

        ax = plt.subplot(1, 1, 1, projection=ccrs.OSGB())
        qplt.contourf(cube, coords=["projection_x_coordinate",
                                    "projection_y_coordinate"],
                      levels=np.linspace(-25000, 6000, 10))
        ax.coastlines()
        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()
Example #23
0
def level_plot(cube,saving_path,name='',level=0,color_levels=9,cmap=plt.cm.CMRmap_r,logscale=0,saving_format='.png'):

    '''
    This function works for 3 dimensional cubes (model_level_number, latitude, longitude)


    It plots and saves a png file (by default)
    You can use it like:
        ukl.level_plot(cube_time_mean,saving_path)

    By default, it plots the cube at level 0 (surface_level) in linear scale and saves it in the path given.

    you can change 'level' for plotting a different level
    For example

    lev=22
    ukl.level_plot(cube_time_mean,saving_path,level=lev)


    Other kargs:

    'name' sets a different name in the saved file. By default it uses cube.var_name
    'color_levels' is an integrer number for setting how many levels you want
    'logscale' if set to true, the plot will be in logarithmic scale
    'cmap' changes the mapping colors
    'saving_format' can be set to something different than png to change the format of the plot

    '''

    if cube.ndim!=3:
        raise NameError('The cube has to have 3 dimensions (model_level_number, latitude, longitude) \n \
        Currently its shape is: %s' % (cube.shape,) )

    if logscale:
        qplt.contourf(cube[level,],color_levels,cmap=cmap,norm=matplotlib.colors.LogNorm())
        log_str='_log_scale'
    else:
        qplt.contourf(cube[level,],color_levels,cmap=cmap)
        log_str=''

    plt.gca().coastlines()
    if name=='':
        name=cube.var_name
    if level==0:
        saving_str=saving_path+'Surface_level_'+name+log_str+saving_format
    else:
        saving_str=saving_path+'Level_%i_'%level+name+log_str+saving_format
    plt.savefig(saving_str,bbox_inches='tight')
    plt.close()
Example #24
0
def main():
    fname = iris.sample_data_path("hybrid_height.nc")
    theta = iris.load_cube(fname)

    # Extract a single height vs longitude cross-section. N.B. This could easily be changed to
    # extract a specific slice, or even to loop over *all* cross section slices.
    cross_section = next(theta.slices(["grid_longitude", "model_level_number"]))

    qplt.contourf(cross_section, coords=["grid_longitude", "altitude"], cmap="RdBu_r")
    iplt.show()

    # Now do the equivalent plot, only against model level
    plt.figure()

    qplt.contourf(cross_section, coords=["grid_longitude", "model_level_number"], cmap="RdBu_r")
    iplt.show()
Example #25
0
File: TEC.py Project: QuLogic/iris
def main():
    # Load the "total electron content" cube.
    filename = iris.sample_data_path('space_weather.nc')
    cube = iris.load_cube(filename, 'total electron content')

    # Explicitly mask negative electron content.
    cube.data = ma.masked_less(cube.data, 0)

    # 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')
    plt.gca().stock_img()
    plt.gca().coastlines()
    iplt.show()
Example #26
0
def main():
    fname = iris.sample_data_path('hybrid_height.nc')
    theta = iris.load_strict(fname)
    
    # Extract a single height vs longitude cross-section. N.B. This could easily be changed to
    # extract a specific slice, or even to loop over *all* cross section slices.
    cross_section = theta.slices(['grid_longitude', 'model_level_number']).next()
    
    qplt.contourf(cross_section, coords=['grid_longitude', 'altitude'])
    plt.show()
    
    # Now do the equivalent plot, only against model level
    plt.figure()
    
    qplt.contourf(cross_section, coords=['grid_longitude', 'model_level_number'])
    plt.show()
def main():
    dir='/data/local2/hador/ostia_reanalysis/' # ELD140
    filename = dir + '*.nc'

    cube = iris.load_cube(filename,'sea_surface_temperature',callback=my_callback)
    #reads in data using a special callback, because it is a nasty netcdf file

    sst_mean = cube.collapsed('time', iris.analysis.MEAN)
    #average all 12 months together

    caribbean = iris.Constraint(
                                    longitude=lambda v: 260 <= v <= 320,
                                    latitude=lambda v: 0 <= v <= 40,
                                    name='sea_surface_temperature'
                                    )

    caribbean_sst_mean = sst_mean.extract(caribbean)
    #extract the Caribbean region
    
    plt.figure()
    contour=qplt.contourf(caribbean_sst_mean, 50)
    contour=qplt.contour(caribbean_sst_mean, 5,colors='k')
    plt.clabel(contour, inline=1, fontsize=10,fmt='%1.1f' )
    plt.gca().coastlines()
    #plt.gca().set_extent((-100,-60,0,40))
    plt.show()
Example #28
0
def zonal_mean_plot(cube,saving_path,name,cmap='CMRmap_r',logscale=0):
    for coord in cube.coords():
        #print coord.name()
        if coord.name()=='surface_altitude':
            cube.remove_coord('surface_altitude')
            #print 'removed'
    #coords_name=[coord.name() for coord in cube.coords()]
    #print coords_name
    cube_zonal_mean=cube.collapsed(['longitude'],iris.analysis.MEAN)
    if logscale:
        qplt.contourf(cube_zonal_mean,cmap=cmap,norm=matplotlib.colors.LogNorm())
    else:
        qplt.contourf(cube_zonal_mean,cmap=cmap)
    plt.yscale('log')
    plt.savefig(saving_path+'Zonal_mean_'+name+'.png',bbox_inches='tight')
    plt.close()
Example #29
0
def main():
    fname = iris.sample_data_path('air_temp.pp')
    temperature = iris.load_cube(fname)

    # Plot #1: contourf with axes longitude from -180 to 180
    fig = plt.figure(figsize=(12, 5))
    plt.subplot(121)
    qplt.contourf(temperature, 15)
    plt.gca().coastlines()

    # Plot #2: contourf with axes longitude from 0 to 360
    proj = ccrs.PlateCarree(central_longitude=-180.0)
    ax = plt.subplot(122, projection=proj)
    qplt.contourf(temperature, 15)
    plt.gca().coastlines()
    iplt.show()
Example #30
0
def main():
    # Load the "total electron content" cube.
    filename = iris.sample_data_path("space_weather.nc")
    cube = iris.load_cube(filename, "total electron content")

    # Explicitly mask negative electron content.
    cube.data = ma.masked_less(cube.data, 0)

    # 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")
    plt.gca().stock_img()
    plt.gca().coastlines()

    iplt.show()
Example #31
0
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)
Example #32
0
    def test_orography(self):
        qplt.contourf(self.cube)
        iplt.orography_at_points(self.cube)
        iplt.points(self.cube)
        self.check_graphic()

        coords = ['altitude', 'grid_longitude']
        qplt.contourf(self.cube, coords=coords)
        iplt.orography_at_points(self.cube, coords=coords)
        iplt.points(self.cube, coords=coords)
        self.check_graphic()

        # TODO: Test bounds once they are supported.
        with self.assertRaises(NotImplementedError):
            qplt.pcolor(self.cube)
            iplt.orography_at_bounds(self.cube)
            iplt.outline(self.cube)
            self.check_graphic()
Example #33
0
def plot_cube(cube, Ns, N, cmap):
    plt.subplot(Ns - 1, 2, N, projection=ccrs.Robinson())
    print cube.name()
    try:
        cube = cube.collapsed('time', iris.analysis.MEAN)
    except:
        cube = cube.collapsed('forecast_reference_time', iris.analysis.MEAN)
    
    cmap = plt.get_cmap(cmap)
    levels, extend = hist_limits(cube, 7)
    
    if (extend =='max'): 
        norm = BoundaryNorm(levels, ncolors=cmap.N - 1)
    else:
        norm = BoundaryNorm(levels, ncolors=cmap.N)

    qplt.contourf(cube, levels = levels, cmap = cmap, norm = norm, extend = extend)
    plt.gca().coastlines()
def main():
    fname = iris.sample_data_path('hybrid_height.nc')
    theta = iris.load_cube(fname)

    # Extract a single height vs longitude cross-section. N.B. This could easily be changed to
    # extract a specific slice, or even to loop over *all* cross section slices.
    cross_section = theta.slices(['grid_longitude',
                                  'model_level_number']).next()

    qplt.contourf(cross_section, coords=['grid_longitude', 'altitude'])
    plt.show()

    # Now do the equivalent plot, only against model level
    plt.figure()

    qplt.contourf(cross_section,
                  coords=['grid_longitude', 'model_level_number'])
    plt.show()
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()
Example #36
0
 def test_2d_coords_contour(self):
     ny, nx = 4, 6
     x1 = np.linspace(-20, 70, nx)
     y1 = np.linspace(10, 60, ny)
     data = np.zeros((ny, nx))
     data.flat[:] = np.arange(nx * ny) % 7
     cube = Cube(data, long_name='Odd data')
     x2, y2 = np.meshgrid(x1, y1)
     true_lons, true_lats = unrotate_pole(x2, y2, -130., 77.)
     co_x = AuxCoord(true_lons, standard_name='longitude', units='degrees')
     co_y = AuxCoord(true_lats, standard_name='latitude', units='degrees')
     cube.add_aux_coord(co_y, (0, 1))
     cube.add_aux_coord(co_x, (0, 1))
     ax = plt.axes(projection=ccrs.PlateCarree())
     qplt.contourf(cube)
     ax.coastlines(color='red')
     ax.gridlines(draw_labels=True)
     ax.set_extent((0, 180, 0, 90))
     self.check_graphic()
Example #37
0
def main():
    # Enable a future option, to ensure that the netcdf load works the same way
    # as in future Iris versions.
    iris.FUTURE.netcdf_promote = True

    # Load some test data.
    fname = iris.sample_data_path('rotated_pole.nc')
    air_pressure = iris.load_cube(fname)

    # Plot #1: Point plot showing data values & a colorbar
    plt.figure()
    points = qplt.points(air_pressure, c=air_pressure.data)
    cb = plt.colorbar(points, orientation='horizontal')
    cb.set_label(air_pressure.units)
    plt.gca().coastlines()
    iplt.show()

    # Plot #2: Contourf of the point based data
    plt.figure()
    qplt.contourf(air_pressure, 15)
    plt.gca().coastlines()
    iplt.show()

    # Plot #3: Contourf overlayed by coloured point data
    plt.figure()
    qplt.contourf(air_pressure)
    iplt.points(air_pressure, c=air_pressure.data)
    plt.gca().coastlines()
    iplt.show()

    # For the purposes of this example, add some bounds to the latitude
    # and longitude
    air_pressure.coord('grid_latitude').guess_bounds()
    air_pressure.coord('grid_longitude').guess_bounds()

    # Plot #4: Block plot
    plt.figure()
    plt.axes(projection=ccrs.PlateCarree())
    iplt.pcolormesh(air_pressure)
    plt.gca().stock_img()
    plt.gca().coastlines()
    iplt.show()
Example #38
0
def zonal_mean_plot(cube,saving_path,name,cmap='CMRmap_r',logscale=0):
    for coord in cube.coords():
        #print coord.name()
        if coord.name()=='surface_altitude':
            cube.remove_coord('surface_altitude')
            #print 'removed'
    #coords_name=[coord.name() for coord in cube.coords()]
    #print coords_name
    cube_zonal_mean=cube.collapsed(['longitude'],iris.analysis.MEAN)
    if logscale:
        qplt.contourf(cube_zonal_mean,cmap=cmap,norm=matplotlib.colors.LogNorm())
    else:
        qplt.contourf(cube_zonal_mean,cmap=cmap)
    # data=cube_zonal_mean.data
    #
    # title=cube.var_name+' max:%1.2f mean:%1.2f min:%1.2f'%(data.max(),data.mean(),data.min())
    # plt.title(title)
    plt.yscale('log')
    plt.savefig(saving_path+'Zonal_mean_'+name+'.png',bbox_inches='tight')
    plt.close()
Example #39
0
def main():
    # Enable a future option, to ensure that the netcdf load works the same way
    # as in future Iris versions.
    iris.FUTURE.netcdf_promote = True

    # Load the "total electron content" cube.
    filename = iris.sample_data_path('space_weather.nc')
    cube = iris.load_cube(filename, 'total electron content')

    # Explicitly mask negative electron content.
    cube.data = ma.masked_less(cube.data, 0)

    # 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')
    plt.gca().stock_img()
    plt.gca().coastlines()
    iplt.show()
Example #40
0
def add_map_subplot(subplot,
                    cube,
                    nspace,
                    title='',
                    cmap='',
                    extend='neither',
                    log=False):
    """
    Add a map subplot to the current pyplot figure.

    Parameters
    ----------
    subplot: int
        The matplotlib.pyplot subplot number. (ie 221)
    cube: iris.cube.Cube
        the iris cube to be plotted.
    nspace: numpy.array
        An array of the ticks of the colour part.
    title: str
        A string to set as the subplot title.
    cmap: str
        A string to describe the matplotlib colour map.
    extend: str
        Contourf-coloring of values outside the levels range
    log: bool
        Flag to plot the colour scale linearly (False) or
        logarithmically (True)
    """
    plt.subplot(subplot)
    logger.info('add_map_subplot: %s', subplot)
    if log:
        qplot = qplt.contourf(cube,
                              nspace,
                              linewidth=0,
                              cmap=plt.cm.get_cmap(cmap),
                              norm=LogNorm(),
                              zmin=nspace.min(),
                              zmax=nspace.max())
        qplot.colorbar.set_ticks([0.1, 1., 10.])
    else:
        qplot = iris.plot.contourf(cube,
                                   nspace,
                                   linewidth=0,
                                   cmap=plt.cm.get_cmap(cmap),
                                   extend=extend,
                                   zmin=nspace.min(),
                                   zmax=nspace.max())
        cbar = pyplot.colorbar(orientation='horizontal')
        cbar.set_ticks(
            [nspace.min(), (nspace.max() + nspace.min()) / 2.,
             nspace.max()])

    plt.gca().coastlines()
    plt.title(title)
Example #41
0
 def plot(self, cube, name):
     plt.figure(figsize=(8, 6))
     proj = ccrs.EuroPP()
     plt.axes(projection=proj)
     contour = qplt.contourf(cube)
     plt.gca().coastlines()
     plt.clabel(contour, inline=False)
     plt.savefig(
         os.path.join('/esarchive/scratch/jcos/esmvaltool/output/figures/',
                      name))
     plt.clf()
Example #42
0
    def plot_2D(self, results, data):
        # Plot the results for each dataset in the same plot
        for result in results:
            dataset = data[result][0]['dataset']
            qplt.contourf(results[result], label=dataset)
        plot_name = 'tas_mn_20002010_djf.{out}'.format(
            out=self.cfg[n.OUTPUT_FILE_TYPE])

        # Get the path to the plot directory
        plot_dir = self.cfg[n.PLOT_DIR]

        # Some tweaks using matplotlib
        plt.legend()
        plt.tick_params(axis='x', labelsize=8)

        # Save the plot
        # plt.savefig(os.path.join(plot_dir, plot_name))
        plt.savefig(
            os.path.join('/home/Earth/jcos/es-esmvaltool/output/', plot_name))
        plt.close()
Example #43
0
def plot_band_list(List, fname, lev, O3_bands, rates_in_bands):
    fig = plt.figure(figsize=(13, 18), dpi=100)
    index_grid = np.arange(9).reshape([3, 3])
    gs = gridspec.GridSpec(4, 3)
    for i in range(3):
        for j in range(3):
            plt1 = plt.subplot(gs[i, j])
            divs = List[index_grid[i, j]]

            qplt.contourf(divs, lev, cmap='bwr')
            qplt.contour(divs, levels=[0], colors='black')

            plt.title(
                str(rates_in_bands[index_grid[i, j]]) +
                ' events/year, O$_3$ Percentile ' +
                str(10 * index_grid[i, j]) + '-' +
                str(10 + 10 * index_grid[i, j]))
            plt1.set_yscale('log', basey=10, subsy=None)
            plt.ylim(5, 10000)
            plt1.invert_yaxis()
            plt.ylabel('Pressure (Pa)')
            plt.xlabel('Latitude')

    plt1 = plt.subplot(gs[3, 0])
    divs = List[9]
    qplt.contourf(divs, lev, cmap='bwr')
    qplt.contour(divs, levels=[0], colors='black')

    plt.title(
        str(rates_in_bands[index_grid[i, j]]) +
        ' events/year, O$_3$ Percentile 90-100')
    plt1.set_yscale('log', basey=10, subsy=None)
    plt.ylim(5, 10000)
    plt1.invert_yaxis()
    plt.ylabel('Pressure (Pa)')
    plt.xlabel('Latitude')
    plt.tight_layout()
    plt.show()
    fig.savefig('./figures/' + fname, dpi=200)

    return
def main():
    fname = iris.sample_data_path('rotated_pole.nc')
    temperature = iris.load_cube(fname)
    
    # Plot #1: Point plot showing data values & a colorbar
    plt.figure()
    points = qplt.points(temperature, c=temperature.data)
    cb = plt.colorbar(points, orientation='horizontal')
    cb.set_label(temperature.units)
    plt.gca().coastlines()
    plt.show()
    
    
    # Plot #2: Contourf of the point based data
    plt.figure()
    qplt.contourf(temperature, 15)
    plt.gca().coastlines()
    plt.show()
    
    
    # Plot #3: Contourf overlayed by coloured point data
    plt.figure()
    qplt.contourf(temperature)
    iplt.points(temperature, c=temperature.data)
    plt.gca().coastlines()
    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()
    ax = plt.axes(projection=ccrs.PlateCarree())
    iplt.pcolormesh(temperature)
    plt.gca().stock_img()
    plt.gca().coastlines()
    plt.show()
Example #45
0
def main():
    # Load the "total electron content" cube.
    filename = iris.sample_data_path('space_weather.nc')
    cube = iris.load_cube(filename, 'total electron content')

    # Explicitly mask negative electron content.
    cube.data = 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')
    plt.gca().stock_img()
    plt.gca().coastlines()
    plt.show()
Example #46
0
def main():
    """
    """
    filename = datadir + 'iop5_36h.pp'
    cubes = files.load(filename)

    theta = convert.calc('air_potential_temperature', cubes)

    plotter = CSP(False,
                  qplt.contourf,
                  theta,
                  np.linspace(270, 350, 15),
                  cmap='cubehelix_r',
                  extend='both')

    onselect = CS([plotter])

    qplt.contourf(theta[0], np.linspace(270, 300, 31), cmap='cubehelix_r')
    RectangleSelector(plt.gca(), onselect, drawtype='line')

    plt.show()
Example #47
0
def main():
    # This is a function that controls everything
    #    mycube = iris.load_cube('/nfs/a266/data/CMIP5_AFRICA/BC_0.5x0.5/HadGEM2-CC/rcp45/pr_WFDEI_1979-2013_0.5x0.5_day_HadGEM2-CC_africa_rcp45_r1i1p1_full.nc')

    figdir = '/nfs/see-fs-01_teaching/earv057/plots'
    try:
        cube2plot = iris.load_cube(figdir + 'hovmoller.nc')
        print cube2plot
    except IOError:
        mycube = iris.load_cube(
            '/nfs/a266/data/CMIP5_AFRICA/0.5x0.5/CanESM2/historical/pr_day_CanESM2_africa_0.5x0.5_historical_r1i1p1_full.nc'
        )
        print mycube.coord('time').points[0:40]
        reg_cube = mycube.intersection(latitude=(4, 25), longitude=(-10, 10))
        reg_cube.coord('latitude').guess_bounds()
        reg_cube.coord('longitude').guess_bounds()
        reg_cube_coll = reg_cube.collapsed('longitude', iris.analysis.MEAN)
        iris.coord_categorisation.add_month(reg_cube_coll,
                                            'time',
                                            name='month')
        cube2plot = reg_cube_coll.aggregated_by('month', iris.analysis.MEAN)
        cube2plot.convert_units('kg m-2 day-1')
        print cube2plot
        iris.save(cube2plot, figdir + 'hovmoller.nc')
        print reg_cube_coll.coord('time')


#    print reg_cube_coll
#    print reg_cube_coll[0]
#    iris.coord_categorisation.add_day_of_year(reg_cube_coll, 'time', name = 'day_of_year')

# partition
#mycube = mycube.collapsed('longitude', iris.analysis.MEAN)
#    print mycube
    levels = np.linspace(1, 20, 50)
    plt.clf()
    qplt.contourf(cube2plot, levels=levels, extend='max')
    plt.ylabel('latitude')
    plt.xlabel('time/months')
    plt.show()
Example #48
0
def main():

    file_path = iris.sample_data_path(
        '/nfs/a266/data/CMIP5_AFRICA/BC_0.5x0.5/IPSL-CM5A-LR/historical/pr_WFDEI_1979-2013_0.5x0.5_day_IPSL-CM5A-LR_africa_historical_r1i1p1_full.nc'
    )

    cube = iris.load_cube(file_path)

    cube_wafr = cube.intersection(latitude=(-10.0, 10.0),
                                  longitude=(4.0, 25.0))

    iris.coord_categorisation.add_year(cube_wafr, 'time', name='year')

    iris.coord_categorisation.add_month_number(cube_wafr,
                                               'time',
                                               name='month_number')

    iris.coord_categorisation.add_season(cube_wafr, 'time', name='season')

    SPELL_COUNT = Aggregator('spell_count',
                             count_spells,
                             units_func=lambda units: 1)

    threshold_rainfall = 0.1

    spell_days = 10

    dry_periods = cube.collapsed('time',
                                 SPELL_COUNT,
                                 threshold=threshold_rainfall,
                                 spell_length=spell_days)

    dry_periods.rename('Number of 10-days dry spells in 35 years')

    qplt.contourf(dry_periods, cmap='RdYlBu_r')

    plt.gca().coastlines()

    iplt.show()
Example #49
0
def main():
    # Load the u and v components of wind from a pp file.
    infile = iris.sample_data_path("wind_speed_lake_victoria.pp")

    uwind = iris.load_cube(infile, "x_wind")
    vwind = iris.load_cube(infile, "y_wind")

    # Create a cube containing the wind speed.
    windspeed = (uwind ** 2 + vwind ** 2) ** 0.5
    windspeed.rename("windspeed")

    # Plot the wind speed as a contour plot.
    qplt.contourf(windspeed, 20)

    # Show the lake on the current axes.
    lakes = cfeat.NaturalEarthFeature(
        "physical", "lakes", "50m", facecolor="none"
    )
    plt.gca().add_feature(lakes)

    # Add arrows to show the wind vectors.
    iplt.quiver(uwind, vwind, pivot="middle")

    plt.title("Wind speed over Lake Victoria")
    qplt.show()

    # Normalise the data for uniform arrow size.
    u_norm = uwind / windspeed
    v_norm = vwind / windspeed

    # Make a new figure for the normalised plot.
    plt.figure()

    qplt.contourf(windspeed, 20)
    plt.gca().add_feature(lakes)
    iplt.quiver(u_norm, v_norm, pivot="middle")

    plt.title("Wind speed over Lake Victoria")
    qplt.show()
Example #50
0
def map(incube, plotpath, modelID):
    # plot a map for a smaller domain
    print 'plotting a map'
    fig = plt.figure(figsize=(12, 5))
    qplt.contourf(incube[5, :, :])

    plt.gca().coastlines()
    #    # get the current axes' subplot for use later on
    #    plt1_ax = plt.gca()
    #
    #    # Add the second subplot showing the A1B scenario
    #    plt.subplot(122)
    #    contour_result = iplt.contourf(spi_ts)
    #
    #    # get the current axes' subplot for use later on
    #    plt2_ax = plt.gca()ttom, width, height = plt2_ax.get_position().bounds
    #    first_plot_left = plt1_ax.get_position().bounds[0]
    #    colorbar_axes = fig.add_axes([first_plot_left, bottom + 0.07, width, 0.03])
    cbar = plt.colorbar(spi_ts, colorbar_axes, orientation='horizontal')
    plt.suptitle('Monthly distribution of the SPI over WA', fontsize=18)
    #plt.show()
    plt.savefig(plotpath + 'ts_' + modelID + '.png')
Example #51
0
def main():
    # Load some test data.
    fname = iris.sample_data_path('hybrid_height.nc')
    theta = iris.load_cube(fname, 'air_potential_temperature')

    # Extract a single height vs longitude cross-section. N.B. This could
    # easily be changed to extract a specific slice, or even to loop over *all*
    # cross section slices.
    cross_section = next(theta.slices(['grid_longitude',
                                       'model_level_number']))

    qplt.contourf(cross_section, coords=['grid_longitude', 'altitude'],
                  cmap='RdBu_r')
    iplt.show()

    # Now do the equivalent plot, only against model level
    plt.figure()

    qplt.contourf(cross_section,
                  coords=['grid_longitude', 'model_level_number'],
                  cmap='RdBu_r')
    iplt.show()
Example #52
0
def main():
    # Load the u and v components of wind from a pp file
    infile = iris.sample_data_path("wind_speed_lake_victoria.pp")

    uwind = iris.load_cube(infile, "x_wind")
    vwind = iris.load_cube(infile, "y_wind")

    uwind.convert_units("knot")
    vwind.convert_units("knot")

    # To illustrate the full range of barbs, scale the wind speed up to pretend
    # that a storm is passing over
    magnitude = (uwind**2 + vwind**2)**0.5
    magnitude.convert_units("knot")
    max_speed = magnitude.collapsed(("latitude", "longitude"),
                                    iris.analysis.MAX).data
    max_desired = 65

    uwind = uwind / max_speed * max_desired
    vwind = vwind / max_speed * max_desired

    # Create a cube containing the wind speed
    windspeed = (uwind**2 + vwind**2)**0.5
    windspeed.rename("windspeed")
    windspeed.convert_units("knot")

    plt.figure()

    # Plot the wind speed as a contour plot
    qplt.contourf(windspeed)

    # Add wind barbs except for the outermost values which overhang the edge
    # of the plot if left
    iplt.barbs(uwind[1:-1, 1:-1], vwind[1:-1, 1:-1], pivot="middle", length=6)

    plt.title("Wind speed during a simulated storm")
    qplt.show()
def main():
     figdir = '/nfs/see-fs-01_teaching/earv052/metrics_workshop/Yo_Sa'
     try:
        cube2plot = iris.load_cube(figdir+'/Leeds_numberdays30mm.nc')
        print cube2plot
     except IOError: 
        cube = iris.load_cube('/nfs/a266/data/CMIP5_AFRICA/BC_0.5x0.5/IPSL-CM5A-LR/historical/pr_WFDEI_1979-2013_0.5x0.5_day_IPSL-CM5A-LR_africa_historical_r1i1p1_full.nc')
        precip = cube[0]
        #print(precip)
        precip = cube.intersection(longitude=(-18.0, 0.0), latitude=(10.0, 20.0))
        precip.coord('latitude').guess_bounds()
        precip.coord('longitude').guess_bounds()
        precip.convert_units('kg m-2 day-1')
        #print(precip)
        iris.coord_categorisation.add_month_number(precip, 'time', name='month')
        print(precip)
        #iris.coord_categorisation.add_day_of_year(precip, 'time', name='day_of_year')
        #ann_long = np.unique(precip.coord('year').points)
        #ann = len(ann_long)
        val=30.0
        bigger = precip.aggregated_by('month', iris.analysis.COUNT, function = lambda values: values > val )
        monthcount = precip.aggregated_by('month', iris.analysis.COUNT, function = lambda values: values > -5000)
        monthcount.data = monthcount.data.astype(float)
        print bigger
        print monthcount.data
        aug = bigger/monthcount
      #  aug = bigger.extract(iris.Constraint(month=8))/monthcount.extract(iris.Constraint(month=8))
        print aug.data
        qplt.contourf(aug.extract(iris.Constraint(month=8)))
##        qplt.contourf(bigger.extract(iris.Constraint(month=8)))
        #d = plt.gca() # get axis object
        #d.coastlines() # to draw coastlines
        m = bm.Basemap(projection='cyl', llcrnrlat=10.0, urcrnrlat=20.0, llcrnrlon=-18.0, urcrnrlon=0.0, resolution='c')  # coarse resolution for grid
        m.drawcoastlines(linewidth=2)
        m.drawcountries(linewidth=2)
        plt.show()
Example #54
0
 def plot2D(self, results, data, name):
   
      for result in results:
         dataset = data[result][0]['dataset']
         central_lon, central_lat = 20, 30
         extent = [-10, 40, 20, 60]
         plt.figure(figsize=(8,6))
         ax = plt.axes(projection=ccrs.Orthographic(central_lon, central_lat))
         ax.set_extent(extent)
         contour = qplt.contourf(results[result])
         plt.gca().coastlines()
         plt.clabel(contour, inline=False)
         plt.title('2000-05 period temperature anomaly, with respect to 1950-1980 climatology. '+dataset)
         plt.savefig(os.path.join('/esarchive/scratch/jcos/esmvaltool/output/figures/', dataset+name))
         plt.clf()
Example #55
0
    def test_contourf(self):
        qplt.contourf(self._small())

        cube = self._small()
        iplt.orography_at_points(cube)

        self.check_graphic()

        qplt.contourf(self._small(), coords=['model_level_number', 'grid_longitude'])
        self.check_graphic()

        qplt.contourf(self._small(), coords=['grid_longitude', 'model_level_number'])
        self.check_graphic()
Example #56
0
# wind_speed = wind_speed[
#     times_to_use,
#     pressure_levels_to_use,
#     lats_to_use,
#     lons_to_use
# ]
# altitude = altitude[
#     times_to_use,
#     pressure_levels_to_use,
#     lats_to_use,
#     lons_to_use
# ]

import iris.quickplot as qplt
import iris.analysis as an

fig = qplt.contourf(wind_speed[0, -1, :, :], cmap="viridis")
plt.xlabel("Longitude")
plt.ylabel("Latitude")
plt.title("Winds at Ground, 6/15/1972 0:00 GMT")
plt.tight_layout()
plt.savefig("ground_winds_demo.svg")
plt.show()

fig = qplt.contourf(wind_speed[0, 8, :, :], cmap="viridis")
plt.xlabel("Longitude")
plt.ylabel("Latitude")
plt.title("Winds at 5 kPa PL (~20908 m, ~68596 ft.), 6/15/1972 0:00 GMT")
plt.tight_layout()
plt.savefig("aloft_winds_demo.svg")
plt.show()
Example #57
0
    def _check(self, cube):
        qplt.contourf(cube)
        self.check_graphic()

        qplt.pcolor(cube)
        self.check_graphic()
Example #58
0
 def test_points(self):
     cube = simple_cube()
     qplt.contourf(cube)
     self.check_graphic()
import matplotlib.cm as mpl_cm
import matplotlib.pyplot as plt

import iris
import iris.quickplot as qplt


fname = iris.sample_data_path('air_temp.pp')
temperature_cube = iris.load_cube(fname)

# Load a Cynthia Brewer palette.
brewer_cmap = mpl_cm.get_cmap('brewer_RdBu_11')

# Draw the contour with 25 levels.
qplt.contourf(temperature_cube, 25, cmap=brewer_cmap)

# Add coastlines to the map created by contourf.
plt.gca().coastlines()

plt.show()
Example #60
0
import matplotlib.pyplot as plt

import iris
import iris.quickplot as qplt

## only 2dim
f = iris.load_cube('file_name')

iplt.contourf(f) # no color bar & name
qplt.contourf(f) # color bar & name

iplt.pcolormesh(f) 
qplt.pcolormesh(f)

# applying cmap
import matplotlib.cm as mpl_cm
cmap = mpl_cm.get_cmap('brewer_OrRd_09')

qplt.contourf(temperature_cube, brewer_cmap.N, cmap=brewer_cmap)
qplt.pcolormesh(temperature_cube, cmap=brewer_cmap)

# ciation
qplt.contourf(temperature_cube, brewer_cmap.N, cmap=brewer_cmap)
iplt.citation('ciation')

plt.gca().coastlines()