Beispiel #1
0
def plot_grid2D(lons, lats, tec_grid2D, datetime, title_label = ''):

	LATS, LONS = np.meshgrid(lats, lons)

	m = Basemap(llcrnrlon=-180,
	            llcrnrlat=-55,
	            urcrnrlon=180,
	            urcrnrlat=75,
	            projection='merc',
	            area_thresh=1000,
	            resolution='i')

	m.drawstates()
	m.drawcountries()
	m.drawcoastlines()

	parallels = np.arange(-90,90,20)
	m.drawparallels(parallels,labels=[True,False,False,True])
	meridians = np.arange(0,360,40)
	m.drawmeridians(meridians,labels=[True,False,False,True])

	m.scatter(LONS, LATS, c=tec_grid2D, latlon = True, linewidths=0, s=5)
	m.colorbar()

	plt.title('%s\n%s' % (title_label, datetime.isoformat(' ')))
    def do_subplot(field, title, lons, lats, plot_num, pole, diff=False): 
        """
        Make an individual subplot. 
        """

        if pole == 'north':
            projection = 'nplaea'
            boundinglat = 50
        else:
            projection = 'splaea'
            boundinglat = -50

        m_base = Basemap(projection=projection, boundinglat=boundinglat,
                         lon_0=0) 
        x, y = m_base(lons, lats)
        ax = fig.add_subplot(plot_num)

        max = get_max_within_area(field, lats, boundinglat, pole)
        if diff:
            cmap = plt.get_cmap('RdBu_r')
            min = -max
        else:
            cmap = plt.get_cmap()
            min = 0

        # Set the land points to be gray. 
        cmap.set_bad('0.65')
        m_base.pcolormesh(x, y, field, vmax=max, vmin=min, cmap=cmap)

        m_base.colorbar()
        m_base.drawparallels(np.arange(-80.,81.,20.))
        m_base.drawmeridians(np.arange(-180.,181.,20.))
        if title:
            plt.title(title)
Beispiel #3
0
def main():

    plot_utils.apply_plot_params(width_cm=20, height_cm=20, font_size=10)

    high_hles_years = [1993, 1995, 1998]
    low_hles_years = [1997, 2001, 2006]
    data_path = "/BIG1/skynet1_rech1/diro/sample_obsdata/eraint/eraint_uvslp_years_198111_201102_NDJmean_ts.nc"





    with xr.open_dataset(data_path) as ds:
        print(ds)


        u = get_composit_for_name(ds, "u10", high_years_list=high_hles_years, low_years_list=low_hles_years)
        v = get_composit_for_name(ds, "v10", high_years_list=high_hles_years, low_years_list=low_hles_years)
        msl = get_composit_for_name(ds, "msl", high_years_list=high_hles_years, low_years_list=low_hles_years)

        lons = ds["longitude"].values
        lats = ds["latitude"].values

        print(lats)
        print(msl.shape)
        print(lons.shape, lats.shape)


        lons2d, lats2d = np.meshgrid(lons, lats)


    fig = plt.figure()

    map = Basemap(llcrnrlon=-130, llcrnrlat=22, urcrnrlon=-28,
                  urcrnrlat=65, projection='lcc', lat_1=33, lat_2=45,
                  lon_0=-95, resolution='i', area_thresh=10000)


    clevs = np.arange(-11.5, 12, 1)
    cmap = cm.get_cmap("bwr", len(clevs) - 1)
    bn = BoundaryNorm(clevs, len(clevs) - 1)

    x, y = map(lons2d, lats2d)
    im = map.contourf(x, y, msl / 100, levels=clevs, norm=bn, cmap=cmap) # convert to mb (i.e hpa)
    map.colorbar(im)


    stride = 2
    ux, vy = map.rotate_vector(u, v, lons2d, lats2d)
    qk = map.quiver(x[::stride, ::stride], y[::stride, ::stride], ux[::stride, ::stride], vy[::stride, ::stride],
               scale=10, width=0.01, units="inches")
    plt.quiverkey(qk, 0.5, -0.1, 2, "2 m/s", coordinates="axes")


    map.drawcoastlines(linewidth=0.5)
    map.drawcountries()
    map.drawstates()
    #plt.show()

    fig.savefig("hles_wind_compoosits.png", bbox_inches="tight", dpi=300)
Beispiel #4
0
def visualiseUrl( fig , url , fig1 ):

	nc = url #netCDF4.Dataset(url,'r')

	title = clipc_combine_process.getTitleNC(nc)

	lats = nc.variables['lat'][:]  # extract/copy the data
	lons = nc.variables['lon'][:]

	lat_0 = lats.mean()
	lon_0 = lons.mean()

	ax = fig.add_subplot(fig1)
	basemap = Basemap(resolution='l',projection='ortho', lat_0=lat_0,lon_0=lon_0) #lat_ts=40,

	if len(lons.shape) == 1:
		# 2D Array no time dimmension
		data = nc.variables[title][:][:]
		xi, yi = basemap(*np.meshgrid(lons, lats))
	elif len(lons.shape) == 2:
		# 3D Array time dimmension
		data = nc.variables[title][0][:][:]	 
		xi, yi = basemap(lons, lats)
	else:
		print "DATA SIZE NOT HANDLED"
		data = None

	# Plot Data
	cs = basemap.pcolormesh(xi,yi,np.squeeze(data))

	# Add Coastlines, States, and Country Boundaries
	basemap.drawcoastlines()
	basemap.drawcountries()
	basemap.colorbar()
Beispiel #5
0
def vec_plot_on_earth(lons, lats, x_data, y_data, vmin=-4, vmax=12, ax=None):
    if ax == None:
	ax = plt.gca()
    plot_lons, plot_x_data = extend_data(lons, lats, x_data)
    plot_lons, plot_y_data = extend_data(lons, lats, y_data)

    lons, lats = np.meshgrid(plot_lons, lats)

    m = Basemap(ax=ax, projection='cyl', resolution='c', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180)
    x, y = m(lons, lats)

    mag = np.sqrt(plot_x_data**2 + plot_y_data**2)
    vmin, vmax = mag.min(), mag.max()
    m.contourf(x[:-1,:], y[:-1,:], mag, ax=ax)
    #m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax)
    #m.quiver(x, y, plot_x_data, plot_y_data)
    skip = 5
    m.quiver(x[::skip, ::skip], y[::skip, ::skip], plot_x_data[::skip, ::skip], plot_y_data[::skip, ::skip], ax=ax)

    m.drawcoastlines(ax=ax)
    m.drawparallels(np.arange(-90.,90.,45.), labels=[1, 0, 0, 0], fontsize=10, ax=ax)
    m.drawmeridians(np.arange(-180.,180.,60.), labels=[0, 0, 0, 1], fontsize=10, ax=ax)


    m.colorbar(location='bottom', pad='7%', ax=ax)
    plt.show()
Beispiel #6
0
def plot_on_earth(lons, lats, data, vmin=-4, vmax=12, cbar_loc='left', cbar_ticks=None):
    #import ipdb; ipdb.set_trace()
    #if ax == None:
	#ax = plt.gca()
    plot_lons, plot_data = extend_data(lons, lats, data)

    lons, lats = np.meshgrid(plot_lons, lats)

    m = Basemap(projection='cyl', resolution='c', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180)
    x, y = m(lons, lats)

    m.pcolormesh(x, y, plot_data, vmin=vmin, vmax=vmax)
    #m.pcolormesh(x, y, plot_data)

    m.drawcoastlines()
    if cbar_loc == 'left':
	p_labels = [0, 1, 0, 0]
    else:
	p_labels = [1, 0, 0, 0]

    m.drawparallels(np.arange(-90.,90.1,45.), labels=p_labels, fontsize=10)
    m.drawmeridians(np.arange(-180.,180.,60.), labels=[0, 0, 0, 1], fontsize=10)

    #import ipdb; ipdb.set_trace()
    if cbar_ticks == None:
	cbar = m.colorbar(location=cbar_loc, pad='7%')
    else:
	cbar = m.colorbar(location=cbar_loc, pad='7%', ticks=cbar_ticks)

    if cbar_loc == 'left':
	cbar.ax.xaxis.get_offset_text().set_position((10,0))
Beispiel #7
0
def vec_plot_south_america(lons, lats, sa_mask, data_x, data_y, ax=None):
    if ax == None:
	ax = plt.gca()
    #print(sa_mask.shape)
    #print(data_x.shape)
    #print(data_y.shape)
    #data_x_masked = np.ma.array(data_x, mask=sa_mask)
    #data_y_masked = np.ma.array(data_y, mask=sa_mask)
    plot_lons, plot_x_data = extend_data(lons, lats, data_x)
    plot_lons, plot_y_data = extend_data(lons, lats, data_y)

    lons, lats = np.meshgrid(plot_lons, lats)

    m = Basemap(ax=ax, projection='cyl', resolution='c', llcrnrlat=-60, urcrnrlat=15, llcrnrlon=-85, urcrnrlon=-32)
    x, y = m(lons, lats)

    mag = np.sqrt(plot_x_data**2 + plot_y_data**2)
    vmin, vmax = mag.min(), mag.max()
    m.contourf(x[:-1,:], y[:-1,:], mag, ax=ax)
    #m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax, ax=ax)
    m.quiver(x, y, plot_x_data, plot_y_data, scale=40, ax=ax)

    m.drawcoastlines(ax=ax)
    m.drawparallels(np.arange(-60.,15.,10.), labels=[1, 0, 0, 0], fontsize=10, ax=ax)
    m.drawmeridians(np.arange(-90.,-30.,10.), labels=[0, 0, 0, 1], fontsize=10, ax=ax)

    m.colorbar(location='right', pad='5%', ax=ax)
    plt.show()
def nsolLots():
	''' Compare nSol estimates to insolation. '''
	# Read the data first:
	nsolTable = readNsol()
	lons = [p['LonW'] for p in nsolTable]
	lats = [p['LatN'] for p in nsolTable]
	sizes = [p['ArrayOutput'] for p in nsolTable]
	insolSizes = [p['TotalAnnualInsolation'] for p in nsolTable]
	bmOptions = {'projection':'merc', 'lon_0':-95, 'lat_0':35, 'llcrnrlat':20, 'urcrnrlat':50,
		'llcrnrlon':-130, 'urcrnrlon':-60, 'rsphere':6371200., 'resolution':'l', 'area_thresh':10000}
	# First Plot
	plt.subplot(211)
	m1 = Basemap(**bmOptions)
	m1.drawcoastlines()
	m1.drawstates()
	m1.drawcountries()
	plt.title('Panel Output')
	mesh1 = m1.pcolor(lons, lats, sizes, latlon=True, tri=True)
	cbar1 = m1.colorbar(mesh1,location='right',pad='5%')
	cbar1.set_label('kWh')
	# Second Plot
	plt.subplot(212)
	m2 = Basemap(**bmOptions)
	m2.drawcoastlines()
	m2.drawstates()
	m2.drawcountries()
	plt.title('Annual Insolation')
	mesh2 = m2.pcolor(lons, lats, insolSizes, latlon=True, tri=True)
	cbar2 = m2.colorbar(mesh2,location='right',pad='5%')
	cbar2.set_label('kWh/m^2')
Beispiel #9
0
 def plot(self, projection='lambert', geopolygons=None, vmin=None, vmax=None):
     # fig=plt.figure(num=None, figsize=(12, 12), dpi=80, facecolor='w', edgecolor='k')
     lat_centre = (self.maxlat+self.minlat)/2.0
     lon_centre = (self.maxlon+self.minlon)/2.0
     if projection=='merc':
         m=Basemap(projection='merc', llcrnrlat=self.minlat-5., urcrnrlat=self.maxlat+5., llcrnrlon=self.minlon-5.,
                   urcrnrlon=self.maxlon+5., lat_ts=20, resolution=resolution)
         # m.drawparallels(np.arange(self.minlat,self.maxlat,self.dlat), labels=[1,0,0,1])
         # m.drawmeridians(np.arange(self.minlon,self.maxlon,self.dlon), labels=[1,0,0,1])
         m.drawparallels(np.arange(-80.0,80.0,5.0), labels=[1,0,0,1])
         m.drawmeridians(np.arange(-170.0,170.0,5.0), labels=[1,0,0,1])
         m.drawstates(color='g', linewidth=2.)
     elif projection=='global':
         m=Basemap(projection='ortho',lon_0=lon_centre, lat_0=lat_centre, resolution=resolution)
         m.drawparallels(np.arange(-80.0,80.0,10.0), labels=[1,0,0,1])
         m.drawmeridians(np.arange(-170.0,170.0,10.0), labels=[1,0,0,1])
     
     elif projection=='regional_ortho':
         m1 = Basemap(projection='ortho', lon_0=self.minlon, lat_0=self.minlat, resolution='l')
         m = Basemap(projection='ortho', lon_0=self.minlon, lat_0=self.minlat, resolution=resolution,\
             llcrnrx=0., llcrnry=0., urcrnrx=m1.urcrnrx/mapfactor, urcrnry=m1.urcrnry/3.5)
         m.drawparallels(np.arange(-80.0,80.0,10.0), labels=[1,0,0,0],  linewidth=2,  fontsize=20)
         # m.drawparallels(np.arange(-90.0,90.0,30.0),labels=[1,0,0,0], dashes=[10, 5], linewidth=2,  fontsize=20)
         # m.drawmeridians(np.arange(10,180.0,30.0), dashes=[10, 5], linewidth=2)
         m.drawmeridians(np.arange(-170.0,170.0,10.0),  linewidth=2)
     elif projection=='lambert':
         distEW, az, baz=obspy.geodetics.gps2dist_azimuth(self.minlat, self.minlon,
                             self.minlat, self.maxlon) # distance is in m
         distNS, az, baz=obspy.geodetics.gps2dist_azimuth(self.minlat, self.minlon,
                             self.maxlat+2., self.minlon) # distance is in m
         m = Basemap(width=distEW, height=distNS, rsphere=(6378137.00,6356752.3142), resolution='l', projection='lcc',\
             lat_1=self.minlat, lat_2=self.maxlat, lon_0=lon_centre, lat_0=lat_centre+1)
         m.drawparallels(np.arange(-80.0,80.0,10.0), linewidth=1, dashes=[2,2], labels=[1,1,0,0], fontsize=15)
         m.drawmeridians(np.arange(-170.0,170.0,10.0), linewidth=1, dashes=[2,2], labels=[0,0,1,0], fontsize=15)
     m.drawcoastlines(linewidth=1.0)
     m.drawcountries()
     # m.drawmapboundary(fill_color=[1.0,1.0,1.0])
     m.fillcontinents(lake_color='#99ffff',zorder=0.2)
     # m.drawlsmask(land_color='0.8', ocean_color='#99ffff')
     m.drawmapboundary(fill_color="white")
     cmap = colors.get_colormap('tomo_80_perc_linear_lightness')
     # #
     # evx, evy=m(129., 41.306)
     # plt.plot(evx, evy, 'y*', markersize=20)
     # #
     x, y=m(self.lonArr, self.latArr)
     im=m.pcolormesh(x, y, self.vArr, cmap=cmap, shading='gouraud', vmin=vmin, vmax=vmax)
     try:
         geopolygons.PlotPolygon(inbasemap=m)
     except:
         pass
     try:
         vrange=vmin+np.arange((vmax-vmin)/0.1+1)*0.1
         cb = m.colorbar(im, "bottom", size="3%", pad='2%', ticks=vrange)
     except:
         cb = m.colorbar(im, "bottom", size="3%", pad='2%')
     cb.ax.tick_params(labelsize=15)
     cb.set_label("Input Phase Velocity (km/sec)", fontsize=15, rotation=0)
     plt.show()
     return
Beispiel #10
0
class PoleMapper(object):
    """docstring for PoleMapper"""

    palette = cm.jet

    def __init__(self, blat, strings, gridpts=1000, round=True):
        super(PoleMapper, self).__init__()
        self.blat = blat
        self.gridpts = gridpts
        self.basemap = Basemap(lon_0=180, boundinglat=blat, projection="spstere", round=round)
        self.pole = "Southpole" if blat < 0 else "Northpole"

    def create_map(self, hdata, strings, ax=None, vmin=None, vmax=None):
        mode, chid, dayside = strings
        if not ax:
            fig, ax = plt.subplots()
        self.palette.set_bad(ax.get_axis_bgcolor(), 1.0)
        CS = self.basemap.pcolormesh(
            hdata.xedges, hdata.yedges, hdata.H.T, shading="flat", cmap=self.palette, ax=ax, vmin=vmin, vmax=vmax
        )
        self.basemap.drawparallels(np.arange(-90, -85), latmax=-90, ax=ax, labels=[1, 1, 1, 1])
        self.basemap.drawmeridians(np.arange(0, 360, 30), latmax=-90, ax=ax, labels=[1, 1, 1, 1])
        self.basemap.colorbar(CS, ax=ax)
        ax.set_title(" ".join([self.pole, chid, mode, dayside]))
        plt.savefig("_".join(["southpole", chid, mode, str(self.gridpts), dayside]) + ".png", dpi=300)

    def create_multimap(self, data, strings):
        n = len(data)
        fig, ax = plt.subplots(1, n)
        for i, d in enumerate(data):
            self.create_map(d, strings[i], ax.flatten()[i])
def _vec_plot_on_earth(lons, lats, x_data, y_data, vmin=-4, vmax=12, loc=None, colorbar=False):
    plot_lons, plot_x_data = _extend_data(lons, lats, x_data)
    plot_lons, plot_y_data = _extend_data(lons, lats, y_data)

    lons, lats = np.meshgrid(plot_lons, lats)

    if not loc:
        m = Basemap(projection='cyl', resolution='c',
                    llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180)
    else:
        m = Basemap(projection='cyl', resolution='c', **loc)
    x, y = m(lons, lats)

    mag = np.sqrt(plot_x_data**2 + plot_y_data**2)
    vmin, vmax = mag.min(), mag.max()
    m.contourf(x, y, mag)
    # m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax)
    # m.quiver(x, y, plot_x_data, plot_y_data)
    skip = 1
    m.quiver(x[::skip, ::skip], y[::skip, ::skip],
             plot_x_data[::skip, ::skip], plot_y_data[::skip, ::skip], scale=500)

    m.drawcoastlines()
    m.drawparallels(np.arange(-90., 90., 45.), labels=[1, 0, 0, 0], fontsize=10)
    m.drawmeridians(np.arange(-180., 180., 60.), labels=[0, 0, 0, 1], fontsize=10)

    if colorbar:
        m.colorbar(location='right', pad='7%')
    return m
def _raster_on_earth(lons, lats, data, vmin=None, vmax=None, loc=None, colorbar=True, labels=True):
    if not loc:
        m = Basemap(projection='cyl', resolution='c',
                    llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180)
    else:
        m = Basemap(projection='cyl', resolution='c', **loc)

    if data is not None:
        plot_lons, plot_data = _extend_data(lons, lats, data)
        lons, lats = np.meshgrid(plot_lons, lats)
        x, y = m(lons, lats)
        if vmin:
            m.pcolormesh(x, y, plot_data, vmin=vmin, vmax=vmax)
        else:
            m.pcolormesh(x, y, plot_data)

    m.drawcoastlines()

    if labels:
        p_labels = [0, 1, 0, 0]
        m.drawparallels(np.arange(-90., 90.1, 45.), labels=p_labels, fontsize=10)
        m.drawmeridians(np.arange(-180., 180., 60.), labels=[0, 0, 0, 1], fontsize=10)

    if colorbar and data is not None:
        m.colorbar(location='right', pad='7%')
    return m
Beispiel #13
0
def _fractions_map(data, dom_x, dom_y, title, case_id, plot_dir):
    """
    Plot diagnostic plots of fraction variables using Basemap
    """
    # ---------------------------------------------------------------- #
    # Plot Fractions
    today = date.today().strftime('%Y%m%d')
    file_name = "{}_{}_{}.png".format(title.lower().replace(" ", "_"),
                                      case_id.lower().replace(" ", "_"),
                                      today)
    pfname = os.path.join(plot_dir, file_name)

    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

    dom_x[dom_x < 0] += 360.0

    mask = data <= 0.0
    data = np.ma.array(data, mask=mask)

    cmap = matplotlib.cm.cool
    cmap.set_bad(color=u'w')

    # define projection
    midx = int(dom_x.shape[1]/2)
    midy = int(dom_x.shape[0]/2)
    print midx, midy

    projection = {'projection': 'stere',
                  'lon_0': dom_x[-1, midx],
                  'lat_0': dom_y[midy, midx],
                  'llcrnrlat': dom_y[-1, 0],
                  'urcrnrlat': dom_y[0, -1],
                  'llcrnrlon': dom_x[-1, 0],
                  'urcrnrlon': dom_x[0, -1],
                  'resolution': 'l'}

    log.debug('Projection: %s', projection)

    m = Basemap(**projection)

    m.drawcoastlines()
    m.drawcountries()

    # draw parallels.
    parallels = np.arange(-90., 90, 10.)
    m.drawparallels(parallels, labels=[1, 0, 0, 0])

    # draw meridians
    meridians = np.arange(-180., 180., 10.)
    m.drawmeridians(meridians, labels=[0, 0, 0, 1])

    x, y = m(dom_x, dom_y)  # compute map proj coordinates.
    print 'passed 1'
    cs = m.pcolormesh(x, y, data, cmap=cmap)
    m.colorbar(cs, location='right', pad="5%")
    plt.title(title)
    fig.savefig(pfname)
    # ---------------------------------------------------------------- #
    return pfname
Beispiel #14
0
def stere(data,latitude,longitude,filename):
    """
    :param data: CO浓度数据矩阵
    :param latitude: 纬度
    :param longitude: 经度
    :param filename:
    :return:
    """
    ax = plt.gca()
    fig = plt.figure()
    m = Basemap(width=10000000,height=7500000,
            resolution='l',projection='stere',\
            lat_ts=35,lat_0=35,lon_0=107.)
    nx = int((m.xmax-m.xmin)/5000.)+1
    ny = int((m.ymax-m.ymin)/5000.)+1
    topodat = m.transform_scalar(data,longitude,latitude,nx,ny)
    im = m.imshow(topodat,cm.GMT_haxby,vmin=0,vmax=4e18)
    m.drawcoastlines()
    m.drawcountries()
    m.drawparallels(np.arange(-80.,81.,20.),labels=[1,0,0,0])
    # 画平行的纬度,前一个参数是表示起点,终点,间距的序列,后一个参数是指在哪一个方向显示纬度、经度值
    m.drawmeridians(np.arange(-180.,181.,20.),labels=[0,0,0,1])
    # 画平行的经度
    m.colorbar(im)
    plt.title("CO"+filename[12:14])
    outname = filename+'.png'
    fig.savefig(outname, dpi=fig.dpi)
Beispiel #15
0
def vec_plot_polar(lons, lats, data_x, data_y, pole, ax=None):
    if ax == None:
	ax = plt.gca()
    plot_lons, plot_x_data = extend_data(lons, lats, data_x)
    plot_lons, plot_y_data = extend_data(lons, lats, data_y)

    lons, lats = np.meshgrid(plot_lons, lats)

    if pole == 'N':
	m = Basemap(ax=ax, resolution='c',projection='stere',lat_0=90.,lon_0=0, width=12000000,height=8000000)
    elif pole == 'S':
	m = Basemap(ax=ax, resolution='c',projection='stere',lat_0=-90.,lon_0=0, width=12000000,height=8000000)
    x, y = m(lons, lats)

    mag = np.sqrt(plot_x_data**2 + plot_y_data**2)
    vmin, vmax = mag.min(), mag.max()
    m.contourf(x[:-1,:], y[:-1,:], mag, ax=ax)
    #m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax, ax=ax)
    skip = 5
    m.quiver(x[::5, ::5], y[::5, ::5], plot_x_data[::5, ::5], plot_y_data[::5, ::5], scale=50, ax=ax)

    m.drawcoastlines(ax=ax)
    m.drawparallels(np.arange(-60.,15.,10.), labels=[1, 0, 0, 0], fontsize=10, ax=ax)
    m.drawmeridians(np.arange(-180.,180.,10.), fontsize=10, ax=ax)

    m.colorbar(location='right', pad='5%', ax=ax)
    plt.show()
Beispiel #16
0
def plot_cedata(lats, lons, data, title):
    """
    Plot coefficient of efficiency data.  Lats, lons, and data should have the
    same temporal dimensions.  Lats and lons should denote gridbox edges.
    e.g. data has spatial dimensions of M (lats) x N (lons) then lats and lons
    should have dimensions of M+1 x N+1.

    Parameters
    ----------
    lats: ndarray
        Latitude array (gridbox edges)
    lons: ndarray
        Longitude array (gridbox edges)
    data: ndarray
        CE data
    title: str
        Plot title
    """
    plt.close('all')
    m = Basemap(projection='gall', llcrnrlat=-90, urcrnrlat=90,
                llcrnrlon=0, urcrnrlon=360, resolution='c')
    m.drawcoastlines()
    
    if data.min() < 0:
        color = cm.bwr
    else:
        color = cm.OrRd
        
    m.pcolor(lons, lats, data, latlon=True, cmap=color, vmin=-1, vmax=1)
    m.colorbar()
    plt.title(title)
    plt.show()
Beispiel #17
0
def demo_north_pole():

    r = RPN(path = "/home/huziy/skynet3_rech1/classOff_Andrey/era2/temp_3d")
    t = r.get_first_record_for_name("I0")
    lon, lat = r.get_longitudes_and_latitudes_for_the_last_read_rec()
    r.close()
    nx, ny = lon.shape

    lon_0, lat_0 = lon[nx//2, ny//2], lat[nx//2, ny//2]


    basemap = Basemap(projection = "omerc", lon_1=60, lat_1 = 89.999, lon_2=-30, lat_2=0, no_rot=True,
        lon_0 = lon_0, lat_0 = lat_0,
        llcrnrlon=lon[0, 0], llcrnrlat=lat[0,0],
        urcrnrlon=lon[-1, -1], urcrnrlat=lat[-1, -1]

    )

    x, y = basemap(lon, lat)


    basemap.contourf(x, y, t)
    basemap.drawcoastlines()
    basemap.colorbar()

    #basemap.shadedrelief()
    plt.show()
def draw_map(lat, lng, sic):
    # setup south polar stereographic basemap.
    # The longitude lon_0 is at 6-o'clock, and the
    # latitude circle boundinglat is tangent to the edge
    # of the map at lon_0. Default value of lat_ts
    # (latitude of true scale) is pole.
    m = Basemap(projection='spstere',boundinglat=-50,lon_0=270,resolution='h', round=True)
    # Basemap()
  
    plt.figure()
    for beam in range(8):        
        x1,y1 = m(lng[beam], lat[beam])
        m.hexbin(x1,y1, C=sic[beam],gridsize=len(sic[beam]),cmap=plt.cm.jet)
            
    m.drawcoastlines()
    m.fillcontinents(color='coral',lake_color='aqua')
    # draw parallels and meridians.
    m.drawparallels(np.arange(-80.,81.,20.))
    m.drawmeridians(np.arange(-180.,181.,20.))
    m.drawmapboundary(fill_color='aqua')
    
    m.colorbar(location="bottom",label="SIC") # draw colorbar
    plt.title("North Polar Stereographic Projection")
    plt.gcf().set_size_inches(18,10)
    plt.show()
Beispiel #19
0
def _fractions_map(data, dom_x, dom_y, title, case_id, plot_dir):
    '''
    Plot diagnostic plots of fraction variables using Basemap
    '''
    # ---------------------------------------------------------------- #
    # Plot Fractions
    pfname = _make_filename(title, case_id, plot_dir)

    fig = plt.figure(figsize=(8, 8))
    fig.add_axes([0.1, 0.1, 0.8, 0.8])

    dom_x[dom_x < 0] += 360.0

    mask = data <= 0.0
    data = np.ma.array(data, mask=mask)

    cmap = matplotlib.cm.cool
    cmap.set_bad(color='w')

    # define projection
    midx = int(dom_x.shape[1] / 2)
    midy = int(dom_x.shape[0] / 2)

    projection = {'projection': 'stere',
                  'lon_0': dom_x[-1, midx],
                  'lat_0': dom_y[midy, midx],
                  'llcrnrlat': dom_y[-1, 0],
                  'urcrnrlat': dom_y[0, -1],
                  'llcrnrlon': dom_x[-1, 0],
                  'urcrnrlon': dom_x[0, -1],
                  'resolution': 'l'}

    log.debug('Projection: %s', projection)

    m = Basemap(**projection)

    m.drawcoastlines()
    m.drawcountries()

    # draw parallels.
    parallels = np.arange(-90., 90, 10.)
    m.drawparallels(parallels, labels=[1, 0, 0, 0])

    # draw meridians
    meridians = np.arange(-180., 180., 10.)
    m.drawmeridians(meridians, labels=[0, 0, 0, 1])

    x, y = m(dom_x, dom_y)  # compute map proj coordinates.
    cs = m.pcolormesh(x, y, data, cmap=cmap)
    m.colorbar(cs, location='right', pad='5%')
    plt.title(title)
    fig.savefig(pfname)
    plt.close()
    # ---------------------------------------------------------------- #
    return pfname
Beispiel #20
0
  def drawHk(self, filename="nodet"):
 
     #    print sic
     # setup south polar stereographic basemap.
     if (len(self)!=0):
          m = Basemap(projection='spstere',boundinglat=-50,lon_0=180,resolution='h', round=True)
      
      
          lat = []
          lng = []
          sic = []
          
          for s in self:
              lng.append(s.getLon())
              lat.append(s.getLat())
              sic.append(s.getSic())
          
      
          lng = np.array(lng)
          lat = np.array(lat)
          sic = np.array(sic)
          plt.figure()
     
          x1,y1= m(lng, lat)
     
          print "x, y, sic", x1, y1, sic
          m.hexbin(x1,y1, C=sic, gridsize=len(sic), cmap=plt.cm.jet)
  
     
          m.drawcoastlines()
          m.fillcontinents(lake_color='white')
          # draw parallels and meridians.
          m.drawparallels(np.arange(-80.,81.,20.))
          m.drawmeridians(np.arange(-180.,181.,20.))
          m.drawmapboundary(fill_color='green')
  
      
          m.colorbar(location="right",label="SIC") # draw colorbar
          plt.title("Sea Ice Concentration - South Pole")
          fig = plt.gcf()
          plt.show()
          f_name = "./img/"+filename + "_.png"
          fig.savefig(f_name)
          plt.close()
          
          # Delete auxiliar variables.
          del m
          del lng    
          del lat    
          del sic    
          del x1
          del y1
          
          return f_name
def scatter_subplots(lons1, lats1, data1, s1,
                     lons2, lats2, data2, s2,
                     title1=None, title2=None):
    
    fig = plt.figure()
    
    # first subplot
    ax1 = fig.add_subplot(121)
    m = Basemap(projection='cyl', llcrnrlat=10, urcrnrlat=35,
                    llcrnrlon=65, urcrnrlon=85)
    m.drawcoastlines()
    m.drawcountries()
    
    parallels = np.arange(-90,90,15.)
    m.drawparallels(parallels,labels=[1,0,0,0])
    meridians = np.arange(-180,180,15.)
    m.drawmeridians(meridians,labels=[0,0,0,1])
    
    m.readshapefile(os.path.join('C:\\', 'Users', 'i.pfeil', 'Documents', 
                                 '0_IWMI_DATASETS', 'shapefiles', 'IND_adm', 
                                 'IND_adm2'), 'IN.MH.JN')
    
    if title1:
        plt.title(title1)
        
    sc = m.scatter(lons1, lats1, c=data1, edgecolor='None', marker=',', 
                       s=s1, vmin=0, vmax=1, cmap='RdYlGn')
    m.colorbar(sc, 'right', size='5%', pad='2%')
    
    # second subplot
    ax2 = fig.add_subplot(122, sharex=ax1, sharey=ax1)
    m = Basemap(projection='cyl', llcrnrlat=10, urcrnrlat=35,
                    llcrnrlon=65, urcrnrlon=85)
    m.drawcoastlines()
    m.drawcountries()
    
    parallels = np.arange(-90,90,15.)
    m.drawparallels(parallels,labels=[1,0,0,0])
    meridians = np.arange(-180,180,15.)
    m.drawmeridians(meridians,labels=[0,0,0,1])
    
    m.readshapefile(os.path.join('C:\\', 'Users', 'i.pfeil', 'Documents', 
                                 '0_IWMI_DATASETS', 'shapefiles', 'IND_adm', 
                                 'IND_adm2'), 'IN.MH.JN')
    
    if title2:
        plt.title(title2)
        
    sc = m.scatter(lons2, lats2, c=data2, edgecolor='None', marker=',', 
                       s=s2, vmin=0, vmax=1, cmap='RdYlGn')
    m.colorbar(sc, 'right', size='5%', pad='2%')
    
    plt.show()
    
def hexagon_map(coordinates, temperature, hex_grid_size=(50,50)):
    m = Basemap(projection='tmerc', lat_0=51, lon_0=10, llcrnrlat=47, llcrnrlon=5, urcrnrlat=55, urcrnrlon=16, resolution='i')
    m.drawcoastlines()
    m.drawcountries()
    m.drawmapboundary()
    lats = coordinates[:,0]
    lons = coordinates[:,1]
    x, y  = m(lons, lats)
    m.hexbin(x, y, C = temperature, gridsize=hex_grid_size, linewidth=0.5, edgecolor='k')
    m.colorbar(location='bottom')
    plt.show()
Beispiel #23
0
class GridPlot(Argument, Settings):
    """ROC绘图"""
    parameters = dict()
    # 命令行参数,参考 https://docs.python.org/2/howto/argparse.html
    command_args = [
        [('npy',), {'help': u'指定一个csv2npy后生成的.npy文件', 'type': str, 'nargs': 1}],
        [('-n','--name',), {'help': u'输出结果文件名', 'type': str, 'nargs': 1}],
        [('-t','--title',), {'help': 'plot image title', 'type': str, 'nargs': 1}],
        [('-v','--verbose',), {'help': u'输出详细信息', 'action':"store_true"}]
    ]

    def __init__(self):
        """init"""
        Argument.__init__(self)
        Settings.__init__(self)
        self.parse_args()

    def parse_args(self):
        """parse arguments"""
        if self.args.npy and os.path.isfile(self.args.npy[0]):
            self.parameters['npy'] = self.args.npy[0]
        else:
            print('{} not found!'.format(self.args.npy[0]))
            exit(-1)
        self.parameters['name'] = self.args.name[0] if self.args.name else tf.mktemp(suffix='.png',dir='.')
        self.parameters['title'] = self.args.title[0] if self.args.title else 'Grid Plot'

        if self.args.verbose:
            print("============parameters===========")
            for key in self.parameters:
                print(key,self.parameters[key])
        self.process()

    def process(self):
        """ process """
        ##load data
        data = np.load(self.parameters['npy'])
        ##create basemap
        self.bm = Basemap(projection='cyl',resolution='l',lon_0=120)
        self.bm.drawcoastlines(linewidth=0.25)
        self.bm.drawcountries(linewidth=0.25)
        #self.bm.fillcontinents(color='grey')

        lons,lats = self.bm.makegrid(360,181)
        x,y = self.bm(lons,lats)
        self.bm.contourf(x,y,data)
        ##add colorbar
        self.bm.colorbar(location='bottom',size='5%',label="mm")
        ##add plot title
        plt.title(self.parameters['title'])

        ##save plot
        plt.savefig(self.parameters['name'])
Beispiel #24
0
 def plot(self,key='AOD'):
     """
     Create a plot of a variable over the ORACLES study area. 
     
     Parameters
     ----------
     key : string
     See names for available datasets to plot.
     
     Modification history
     --------------------
     Written: Michael Diamond, 08/16/2016, Seattle, WA
     Modified: Michael Diamond, 08/21/2016
        -Added ORACLES routine flight plan, Walvis Bay (orange), and Ascension Island
     Modified: Michael Diamond, 09/02/2016, Swakopmund, Namibia
         -Updated flight track
     """
     plt.clf()
     size = 16
     font = 'Arial'
     m = Basemap(llcrnrlon=self.lon.min(),llcrnrlat=self.lat.min(),urcrnrlon=self.lon.max(),\
     urcrnrlat=self.lat.max(),projection='merc',resolution='i')
     m.drawparallels(np.arange(-180,180,5),labels=[1,0,0,0],fontsize=size,fontname=font)
     m.drawmeridians(np.arange(0,360,5),labels=[1,1,0,1],fontsize=size,fontname=font)
     m.drawmapboundary(linewidth=1.5)        
     m.drawcoastlines()
     m.drawcountries()
     m.drawmapboundary(fill_color='steelblue')
     m.fillcontinents(color='floralwhite',lake_color='steelblue',zorder=0)
     if key == 'AOD':
         m.pcolormesh(self.lon,self.lat,self.ds['%s' % key],cmap=self.colors['%s' % key],\
         latlon=True,vmin=self.v['%s' % key][0],vmax=self.v['%s' % key][1])
         cbar = m.colorbar()
         cbar.ax.tick_params(labelsize=size-2) 
         cbar.set_label('[%s]' % self.units['%s' % key],fontsize=size,fontname=font)
     elif key == 'ATYP':
         m.pcolormesh(self.lon,self.lat,self.ds['%s' % key],cmap=self.colors['%s' % key],\
         latlon=True,vmin=self.v['%s' % key][0],vmax=self.v['%s' % key][1])
         plt.contourf(np.array(([5,1],[3,2])),cmap=self.colors['%s' % key],levels=[0,1,2,3,4,5])
         cbar = m.colorbar(ticks=[0,1,2,3,4,5])
         cbar.ax.set_yticklabels(['Sea Salt','Sulphate','Organic C','Black C','Dust'])
         cbar.ax.tick_params(labelsize=size-2) 
     else:
         print('Error: Invalid key. Check names for available datasets.')
     m.scatter(14.5247,-22.9390,s=250,c='orange',marker='D',latlon=True)
     m.scatter(-14.3559,-7.9467,s=375,c='c',marker='*',latlon=True)
     m.scatter(-5.7089,-15.9650,s=375,c='chartreuse',marker='*',latlon=True)
     m.plot([14.5247,13,0],[-22.9390,-23,-10],c='w',linewidth=5,linestyle='dashed',latlon=True)
     m.plot([14.5247,13,0],[-22.9390,-23,-10],c='k',linewidth=3,linestyle='dashed',latlon=True)
     plt.title('%s from MSG SEVIRI on %s/%s/%s at %s UTC' % \
     (self.names['%s' % key],self.month,self.day,self.year,self.time),fontsize=size+4,fontname=font)
     plt.show()
Beispiel #25
0
def PlotTomoMap(fname, dlon=0.5, dlat=0.5, title='', datatype='ph', outfname='', browseflag=False, saveflag=True):
    """
    Plot Tomography Map
    longitude latidute ZValue
    """
    if title=='':
        title=fname;
    if outfname=='':
        outfname=fname;
    Inarray=np.loadtxt(fname)
    LonLst=Inarray[:,0]
    LatLst=Inarray[:,1]
    ZValue=Inarray[:,2]
    llcrnrlon=LonLst.min()
    llcrnrlat=LatLst.min()
    urcrnrlon=LonLst.max()
    urcrnrlat=LatLst.max()
    Nlon=int((urcrnrlon-llcrnrlon)/dlon)+1
    Nlat=int((urcrnrlat-llcrnrlat)/dlat)+1
    fig=plt.figure(num=None, figsize=(8, 12), dpi=80, facecolor='w', edgecolor='k')
    m = Basemap(llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlon=urcrnrlon, urcrnrlat=urcrnrlat, \
        rsphere=(6378137.00,6356752.3142), resolution='l', projection='merc')
    
    lon = LonLst
    lat = LatLst
    x,y = m(lon, lat)
    xi = np.linspace(x.min(), x.max(), Nlon)
    yi = np.linspace(y.min(), y.max(), Nlat)
    xi, yi = np.meshgrid(xi, yi)
    
    #-- Interpolating at the points in xi, yi
    zi = griddata(x, y, ZValue, xi, yi)
    # m.pcolormesh(xi, yi, zi, cmap='seismic_r', shading='gouraud')
    cmap=matplotlib.cm.seismic_r
    cmap.set_bad('w',1.)
    m.imshow(zi, cmap=cmap)
    m.drawcoastlines()
    m.colorbar(location='bottom',size='2%')
    # m.fillcontinents()
    # draw parallels
    m.drawparallels(np.arange(-90,90,10),labels=[1,1,0,1])
    # draw meridians
    m.drawmeridians(np.arange(-180,180,10),labels=[1,1,1,0])
    plt.suptitle(title,y=0.9, fontsize=22);
    if browseflag==True:
        plt.draw()
        plt.pause(1) # <-------
        raw_input("<Hit Enter To Close>")
        plt.close('all')
    if saveflag==True:
        fig.savefig(outfname+'.ps', format='ps')
    return 
Beispiel #26
0
def plot_avg_snfall_maps(b: Basemap, xx, yy, hles_snfall, total_snfall,
                         cmap=None, bnorm: BoundaryNorm=None, label=""):
    fig = plt.figure()

    gs = GridSpec(1, 3, wspace=0.01)

    h = hles_snfall.mean(axis=0)
    t = total_snfall.mean(axis=0)



    axes_list = []

    # hles
    ax = fig.add_subplot(gs[0, 0])
    cs = b.contourf(xx, yy, h, bnorm.boundaries, cmap=cmap, norm=bnorm, extend="max")
    ax.set_title("HLES (cm)")
    cb = b.colorbar(cs, location="bottom")
    cb.ax.set_xticklabels(cb.ax.get_xticklabels(), rotation=45)
    axes_list.append(ax)


    # total
    ax = fig.add_subplot(gs[0, 1])
    cs = b.contourf(xx, yy, t, bnorm.boundaries, cmap=cmap, norm=bnorm, extend="max")
    ax.set_title("Snowfall (cm)")
    cb = b.colorbar(cs, location="bottom")
    cb.ax.set_visible(False)
    axes_list.append(ax)


    # hles percentage
    ax = fig.add_subplot(gs[0, 2])
    clevs = np.arange(0, 100, 10)
    cs = b.contourf(xx, yy, h / t * 100,
                    levels=clevs,
                    cmap=get_with_white_added("gist_ncar_r", white_end=0.1,
                                              ncolors_out=len(clevs) - 1))

    ax.set_title("HLES fraction (%)")
    cb = b.colorbar(cs, location="bottom")
    axes_list.append(ax)


    # plot coastlines
    for ax in axes_list:
        b.drawcoastlines(ax=ax, linewidth=0.5)


    fig.savefig(str(img_dir / f"mean_hles_total_snfall_{label}.png"),
                bbox_inches="tight", dpi=250)
    plt.close(fig)
Beispiel #27
0
def station_map(coordinates, temperature):
#    map = Basemap(projection='lcc', lat_0 = 51, lon_0 = 10, resolution = 'i', width = 850000, height = 1000000)
    map = Basemap(projection='tmerc', lat_0=51, lon_0=10, llcrnrlat=47, llcrnrlon=5, urcrnrlat=55, urcrnrlon=16, resolution='i')
    map.drawcoastlines()
    map.drawcountries()
    map.drawmapboundary()
    lats = coordinates[:,0]
    lons = coordinates[:,1]
    x, y  = map(lons, lats)
#    map.hexbin(x,y)
    map.hexbin(x, y, C = temperature, gridsize=(9,9), linewidth=0.5, edgecolor='k')
    map.colorbar(location='bottom')
    plt.show()
def plotmap(data, lat=None, lon=None, cmap='jet'):
    # If data is a DataArray, we can omit the lat, lon arrays and extract
    # from the DataArray's coordinates
    if isinstance(data, xray.DataArray):
        lat, lon = data['lat'], data['lon']

    xi, yi = np.meshgrid(lon, lat)
    plt.figure()
    m = Basemap()
    m.drawcoastlines()
    m.pcolormesh(xi, yi, data, cmap=cmap, latlon=True)
    m.colorbar()
    plt.draw()
def plot(data,title=' ',projection='cyl',file_name=datetime.datetime.now().isoformat(),show=1,cblabel='$\mu g/ m^3$',cmap=plt.cm.CMRmap_r,clevs=np.zeros(1),return_fig=0,dpi=300,lon=0,lat=0,colorbar_format_sci=0,saving_format='svg',scatter_points=0,f_size=20):
    fig=plt.figure(figsize=(20, 12))
    m = fig.add_subplot(1,1,1)
    if projection=='merc':
        m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,\
            llcrnrlon=-180,urcrnrlon=180,lat_ts=20)
    else:
        m = Basemap(projection=projection,lon_0=0)
    m.drawcoastlines()

    if isinstance(lon, int):
        lon=readsav('/nfs/a107/eejvt/IDL_CODE/glon.sav')
    if isinstance(lat, int):
        lat=readsav('/nfs/a107/eejvt/IDL_CODE/glat.sav')

        X,Y=np.meshgrid(lon.glon,lat.glat)
    else:
        if lon.ndim==1:
            X,Y=np.meshgrid(lon,lat)
        else:
            X=np.copy(lon)
            Y=np.copy(lat)
    if type(clevs) is list:
        cs=m.contourf(X,Y,data,clevs,latlon=True,cmap=cmap,norm= colors.BoundaryNorm(clevs, 256))
        if colorbar_format_sci:
            def fmt(x, pos):
                a, b = '{:.1e}'.format(x).split('e')
                b = int(b)
                return r'${} \times 10^{{{}}}$'.format(a, b)
            cb = m.colorbar(cs,"right",format=ticker.FuncFormatter(fmt),ticks=clevs)
        else:
            cb = m.colorbar(cs,format='%.2e',ticks=clevs)
    else:
        cs=m.contourf(X,Y,data,15,latlon=True,cmap=cmap)
        cb = m.colorbar(cs)

    if not isinstance(scatter_points,int):
        m.scatter(scatter_points[:,0],scatter_points[:,100])
    cb.set_label(cblabel,fontsize=f_size)
    cb.ax.tick_params(labelsize=f_size)
    plt.title(title,fontsize=f_size)
    if os.path.isdir("PLOTS/"):
        plt.savefig('PLOTS/'+file_name+'.'+saving_format,format=saving_format,dpi=dpi, bbox_inches='tight')
        plt.savefig('PLOTS/'+file_name+'.svg',format='svg', bbox_inches='tight')
    else:
        plt.savefig(file_name+'.'+saving_format,format=saving_format,dpi=dpi, bbox_inches='tight')
        plt.savefig(file_name+'.svg',format='svg', bbox_inches='tight')
    if show:
        plt.show()
    if return_fig:
        return fig
Beispiel #30
0
def plot_file(filename):
    # Open the file using the NetCDF4 library
    nc = Dataset(filename)

    # analyze_dataset(nc)

    latlon = nc.variables['geospatial_lat_lon_extent']
    # print('geospatial_lat_lon_extent:', latlon)

    # Original example uses Brightness Temperature values, 'CMI'
    # But that's not in our dataset.
    whichvar = 'Rad'
    data = nc.variables[whichvar][:]
    prettyname = nc.variables[whichvar].long_name

    # Show it without basemap:
    # plt.imshow(data, cmap='Greys')
    # plt.show()

    # Create the basemap reference for the Satellite Projection
    bmap = Basemap(projection='geos',

                   # Extents
                   llcrnrlon=latlon.geospatial_westbound_longitude,
                   llcrnrlat=latlon.geospatial_southbound_latitude,
                   urcrnrlon=latlon.geospatial_eastbound_longitude,
                   urcrnrlat=latlon.geospatial_northbound_latitude,

                   # Should these be nadir, or center?
                   lon_0=latlon.geospatial_lon_nadir,
                   lat_0=latlon.geospatial_lat_nadir,
                   satellite_height=35786023.0, ellps='GRS80')

    # Plot GOES-16 Channel using 170 and 378 as the temperature thresholds
    bmap.imshow(data, origin='upper', cmap='Greys')

    # Draw the coastlines, countries, parallels and meridians
    bmap.drawcoastlines(linewidth=0.3, linestyle='solid', color='blue')
    bmap.drawcountries(linewidth=0.3, linestyle='solid', color='blue')

    # These don't seem to do anything
    bmap.drawparallels(np.arange(-90.0, 90.0, 10.0),
                       linewidth=0.1, color='yellow')
    bmap.drawmeridians(np.arange(0.0, 360.0, 10.0),
                       linewidth=0.1, color='yellow')

    # Insert the legend
    bmap.colorbar(location='bottom', label=prettyname)

    # Show the plot
    plt.show()
Beispiel #31
0
### Adjust maximum limits
values = np.arange(-2, 2.1, .2)

### Plot filled contours
cs = m.contourf(lons[:, :],
                lats[:, :],
                np.squeeze(diffsit[:, :]),
                values,
                latlon=True,
                extend='both')

### Set colormap
cs.set_cmap(plt.cm.get_cmap('RdBu'))

### Set colorbar
cbar = m.colorbar(cs, drawedges=True, location='right', pad=0.4)
cbar.set_ticks(np.arange(-2, 3, 1))
cbar.set_ticklabels(map(str, np.arange(-2, 3, 1)))
cbar.set_label(r'\textbf{Difference (m)}')
cbar.ax.tick_params(axis='y', size=.2)

monthtitle = datetime.date(plotyr2, plotmonth, 1).strftime('%B')
fig.subplots_adjust(top=0.89)

plt.annotate(r'\textbf{Sea Ice Thickness -- [July, %s-%s]}' \
            % (plotyr2,plotyr1),xy=(1,1),
             xytext=(0.54,1.06),textcoords='axes fraction',
             fontsize=15,color='w',ha='center')
plt.annotate(r'\textbf{GRAPHIC}: Zachary Labe (@ZLabe)',
             textcoords='axes fraction',
             xy=(0, 0),
    # projection using the limits of the lat/lon data itself:
    # clear graph
    plt.clf()
    m=Basemap(projection='mill',lat_ts=10,llcrnrlon=lon.min(), \
              urcrnrlon=lon.max(),llcrnrlat=lat.min(),urcrnrlat=lat.max(), \
              resolution='c')

    # convert the lat/lon values to x/y projections.

    x, y = m(*np.meshgrid(lon, lat))

    # plot the field using the fast pcolormesh routine
    # set the colormap to jet.

    m.pcolormesh(x, y, data, shading='flat', cmap=plt.cm.jet)
    m.colorbar(location='right')

    # Add a coastline and axis values.

    m.drawcoastlines()
    m.fillcontinents()
    m.drawmapboundary()
    m.drawparallels(np.arange(-90., 120., 30.), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-180., 180., 60.), labels=[0, 0, 0, 1])

    # Add a colorbar and title, and then show the plot.
    plt.title('NWW3 Significant Wave Height from NOMADS on %s' %
              target_date_key)
    plt.savefig(output_file_path)
    print_with_notice("wave map on %s has been generated" %
                      (target_date.strftime('%Y/%m/%d')))
Beispiel #33
0
def processing(path):
    """
    Generates images from NetCDF files
    pathDir: root direcotry with "Data", "Output" and "Scripts" folders
    pathFile: path to NetCDF file to be manipulated
    outFolder: path to directory where the generated images should be saved
    Output: .png image file
    """

    # Getting information from the file name ============================================================
    # Search for the GOES-16 channel in the file name
    INPE_Band_ID = (path[path.find("S10635") + 6:path.find("_")])
    # print(INPE_Band_ID)
    # Get the band number subtracting the value by 332
    Band = int(INPE_Band_ID) - 332

    # Create a GOES-16 Bands string array
    Wavelenghts = [
        '[]', '[0.47 μm]', '[0.64 μm]', '[0.865 μm]', '[1.378 μm]',
        '[1.61 μm]', '[2.25 μm]', '[3.90 μm]', '[6.19 μm]', '[6.95 μm]',
        '[7.34 μm]', '[8.50 μm]', '[9.61 μm]', '[10.35 μm]', '[11.20 μm]',
        '[12.30 μm]', '[13.30 μm]'
    ]
    Band_Wavelenght = Wavelenghts[int(Band)]
    # Search for the Scan start in the file name
    Start = (path[path.find(INPE_Band_ID + "_") + 4:path.find(".nc")])
    # Getting the date from the file name
    year = Start[0:4]
    month = Start[4:6]
    day = Start[6:8]
    date = day + "-" + month + "-" + year
    time = Start[8:10] + ":" + Start[
        10:12] + " UTC"  # Time of the Start of the Scan

    # Get the unit based on the channel. If channels 1 trough 6 is Albedo. If channels 7 to 16 is BT.
    Unit = "Albedo (%)"
    # Choose a title for the plot
    Title = " GOES-16 ABI CMI Band " + str(
        Band) + " " + Band_Wavelenght + " " + Unit + " " + date + " " + time
    # Insert the institution name
    Institution = "CEPAGRI - UNICAMP"
    # Required libraries ================================================================================

    # Open the file using the NetCDF4 library
    nc = Dataset(path)

    # Choose the visualization extent (min lon, min lat, max lon, max lat)
    extent = [-115.98, -55.98, -25.01, 34.98]
    min_lon = extent[0]
    max_lon = extent[2]
    min_lat = extent[1]
    max_lat = extent[3]

    # Get the latitudes
    lats = nc.variables['lat'][:]
    # Get the longitudes
    lons = nc.variables['lon'][:]

    # print (lats)
    # print (lons)

    # latitude lower and upper index
    latli = np.argmin(np.abs(lats - extent[1]))
    latui = np.argmin(np.abs(lats - extent[3]))

    # longitude lower and upper index
    lonli = np.argmin(np.abs(lons - extent[0]))
    lonui = np.argmin(np.abs(lons - extent[2]))

    # Extract the Brightness Temperature / Reflectance values from the NetCDF
    data = nc.variables['Band1'][latli:latui, lonli:lonui]

    # Flip the y axis, divede by 100
    data = (np.flipud(data) / 100)

    # Define the size of the saved picture ==============================================================
    DPI = 150
    ax = plt.figure(figsize=(2000 / float(DPI), 2000 / float(DPI)),
                    frameon=True,
                    dpi=DPI)
    #====================================================================================================

    # Plot the Data =====================================================================================
    # Create the basemap reference for the Rectangular Projection
    bmap = Basemap(llcrnrlon=extent[0],
                   llcrnrlat=extent[1],
                   urcrnrlon=extent[2],
                   urcrnrlat=extent[3],
                   epsg=4326)

    # Draw the countries and Brazilian states shapefiles
    bmap.readshapefile('/Scripts/GEONETCast/Shapefiles/BRA_adm1',
                       'BRA_adm1',
                       linewidth=0.50,
                       color='cyan')
    bmap.readshapefile(
        '/Scripts/GEONETCast/Shapefiles/ne_10m_admin_0_countries',
        'ne_10m_admin_0_countries',
        linewidth=0.50,
        color='cyan')

    # Draw parallels and meridians
    bmap.drawparallels(np.arange(-90.0, 90.0, 5.0),
                       linewidth=0.3,
                       dashes=[4, 4],
                       color='white',
                       labels=[False, False, False, False],
                       fmt='%g',
                       labelstyle="+/-",
                       xoffset=-0.80,
                       yoffset=-1.00,
                       size=7)
    bmap.drawmeridians(np.arange(0.0, 360.0, 5.0),
                       linewidth=0.3,
                       dashes=[4, 4],
                       color='white',
                       labels=[False, False, False, False],
                       fmt='%g',
                       labelstyle="+/-",
                       xoffset=-0.80,
                       yoffset=-1.00,
                       size=7)

    # Converts a CPT file to be used in Python
    cpt = loadCPT(
        '/Scripts/GEONETCast/Colortables/Square Root Visible Enhancement.cpt')
    # Makes a linear interpolation
    cpt_convert = LinearSegmentedColormap('cpt', cpt)
    # Plot the GOES-16 channel with the converted CPT colors (you may alter the min and max to match your preference)
    bmap.imshow(data, origin='upper', cmap=cpt_convert, vmin=0, vmax=100)

    # Insert the colorbar at the bottom
    cb = bmap.colorbar(location='bottom',
                       size='2%',
                       pad='-3.5%',
                       ticks=[20, 40, 60, 80])
    cb.ax.set_xticklabels(['20', '40', '60', '80'])
    cb.outline.set_visible(False)  # Remove the colorbar outline
    cb.ax.tick_params(width=0)  # Remove the colorbar ticks
    cb.ax.xaxis.set_tick_params(
        pad=-14.5)  # Put the colobar labels inside the colorbar
    cb.ax.tick_params(
        axis='x', colors='black',
        labelsize=8)  # Change the color and size of the colorbar labels

    # Add a black rectangle in the bottom to insert the image description
    lon_difference = (extent[2] - extent[0])  # Max Lon - Min Lon
    currentAxis = plt.gca()
    currentAxis.add_patch(
        Rectangle((extent[0], extent[1]),
                  lon_difference,
                  lon_difference * 0.015,
                  alpha=1,
                  zorder=3,
                  facecolor='black'))

    # Add the image description inside the black rectangle
    lat_difference = (extent[3] - extent[1])  # Max lat - Min lat
    plt.text(extent[0],
             extent[1] + lat_difference * 0.003,
             Title,
             horizontalalignment='left',
             color='white',
             size=10)
    plt.text(extent[2],
             extent[1] + lat_difference * 0.003,
             Institution,
             horizontalalignment='right',
             color='yellow',
             size=10)

    # Add logos / images to the plot
    logo_GNC = plt.imread('/Scripts/GEONETCast/Logos/GNC_Logo.png')
    logo_INPE = plt.imread('/Scripts/GEONETCast/Logos/INPE_Logo.png')
    logo_NOAA = plt.imread('/Scripts/GEONETCast/Logos/NOAA_Logo.png')
    logo_GOES = plt.imread('/Scripts/GEONETCast/Logos/GOES_Logo.png')
    logo_cepagri = plt.imread('/Scripts/GEONETCast/Logos/Logo_CEPAGRI.png')

    ax.figimage(logo_GNC, 20, 70, zorder=3, alpha=1, origin='upper')
    ax.figimage(logo_INPE, 90, 70, zorder=3, alpha=1, origin='upper')
    ax.figimage(logo_NOAA, 165, 70, zorder=3, alpha=1, origin='upper')
    ax.figimage(logo_GOES, 228, 70, zorder=3, alpha=1, origin='upper')
    ax.figimage(logo_cepagri, 326, 70, zorder=3, alpha=1, origin='upper')

    # Save the result
    # print('/Scripts/GEONETCast/Output/' + path[12:18] + '/INPE_G16_CH' + str(Band) + '_' + Start + '.png')
    plt.savefig('/Scripts/GEONETCast/Output/' + path[12:18] + '/INPE_G16_CH' +
                str(Band) + '_' + Start + '.png',
                dpi=DPI,
                bbox_inches='tight',
                pad_inches=0)
Beispiel #34
0
#-----------------CALLING FUNCTION 4-----------------
#ASL_highlight, nino_highlight = highlight();
#-----------------END CALLING FUNCTION 4-----------------

#-----------------BEGIN HIGHLIGHT-----------------
#m.contour(x,y,ASL_highlight,1,colors='b')
#m.contour(x,y,nino_highlight,1,colors='r')

m.drawcoastlines(linewidth=1.25)
#m.fillcontinents(color='0.8')
m.drawparallels(np.arange(-80, 81, 20), labels=[1, 1, 0, 0])
m.drawmeridians(np.arange(0, 360, 60), labels=[0, 0, 0, 1])

# add colorbar.
cbar = m.colorbar(cs, pad="15%")
cbar.set_label(cbarunits, rotation=0)

plt.title(str(plottitle) + ' gradient:')  # + str(amundsen_low))
plt.savefig(filename + '_gradient.png')
#plt.show()

# create figure.
fig = plt.figure(figsize=(8, 4.5))
ax = fig.add_axes([0.05, 0.05, 0.9, 0.85])
levels = [
    970, 975, 980, 985, 990, 995, 1000, 1005, 1010, 1015, 1020, 1025, 1030
]
orig_cmap = plt.cm.coolwarm
cs = m.contourf(x, y, clean_data_intercept, 20, cmap=orig_cmap)
#cs = m.contourf(x,y,clean_data_intercept,15)
b_map.drawcoastlines(linewidth=0.1)
b_map.fillcontinents(color='black')
#b_map.drawcountries()

jet = plt.get_cmap('jet')
lonx, laty = b_map(lon, lat)
csOWL = b_map.scatter(lonx,
                      laty,
                      c=z,
                      marker='o',
                      s=0.1,
                      cmap=jet,
                      label='Field sites')

#ax.legend(handles=[cs],bbox_to_anchor=(0.43,0.25), borderaxespad=0.,fontsize=8)
cbar = b_map.colorbar(csOWL, location='right', pad="5%")
#csbb700OWLbar=b_map.colorbar(csbb700OWL,location='right',pad="5%")
cbar.set_label('Coverage probaility density', **csfont)

ax2 = plt.axes([0.01, 0.1, 0.85, 0.37])
ax2.yaxis.tick_right()
weights = np.ones_like(lon) / len(lon)
ax2.hist(lon, bins=100, color='blue', weights=weights)
ax2.tick_params(axis='y',
                direction='in',
                length=3,
                width=1,
                colors='black',
                labelrotation=90)
ax2.tick_params(axis='x',
                direction='in',
    # create Basemap instance.
    m = Basemap(projection='cyl', lat_0=0, lon_0=0)
    m.drawcoastlines(linewidth=1.25)
    m.fillcontinents(color='0.95')
    #m.drawmapboundary(fill_color='0.9')
    # cacluate colorbar ranges
    #bounds_max=float("{0:.0f}".format(np.nanpercentile(Plot_Var, 99.99))) # Upper bound of plotted values to be used for colorbar, which is 99.99th percentile of data, with 0 decimals
    bounds_max=33
    bounds = np.arange(0, bounds_max, bounds_max/33)
    norm = matplotlib.colors.BoundaryNorm(boundaries=bounds, ncolors=256)
    # create a pseudo-color plot over the map
    im1 = m.pcolormesh(Lon_img, Lat_img, Plot_Var, norm=norm, shading='flat', cmap=plt.cm.jet, latlon=True) # Choose colormap: https://matplotlib.org/users/colormaps.html
    m.drawparallels(np.arange(-90.,90.001,30.),labels=[True,False,False,False], linewidth=0.01) # labels = [left,right,top,bottom]
    m.drawmeridians(np.arange(0.,360.,30.),labels=[False,False,False,True], linewidth=0.01) # labels = [left,right,top,bottom]
    # add colorbar
    cbar = m.colorbar(im1,"right", size="3%", pad="2%", extend='max') # extend='both' will extend the colorbar in both sides (upper side and down side)
    cbar.set_label(Var_plot_unit)
    #set title
    ax.set_title(Var_plot_name+', at surface - hist - average of '+start_date_cal_hist+'-'+end_date_cal_hist + ' - ' +str(GCM))
    mng = plt.get_current_fig_manager()
    mng.window.showMaximized() # Maximizes the plot window to save figures in full
    #plt.show()
    fig.savefig(dir_figs+Var_name+'_'+ str(GCM)+'_surface_hist-' +start_date_cal_hist+'-'+end_date_cal_hist + '.png', format='png', dpi=300, transparent=True, bbox_inches='tight')
    plt.close()
    
    print('Model '+str(GCM)+' - hist - processed successfully')
    
#################################################
#### Ploting for all models (with pcolormesh) ###
n_r=4 # Number of rows for subplot
n_c=4 # Number of columns for subplot
Beispiel #37
0
def fr2ghi2png(url,
               colormapPath,
               colormapName,
               dirDest,
               lat_name,
               lon_name,
               data_name,
               geos=False):

    # Dataset is the class behavior to open the file
    # and create an instance of the ncCDF4 class
    nc_fid = netCDF4.Dataset(url, 'r')

    t_coverage = repr(nc_fid.getncattr('time_coverage_start'))
    # print t_coverage

    ds_name = repr(nc_fid.getncattr('dataset_name'))
    # print ds_name

    date = re.search('\'(.*?)\'', t_coverage).group(1)
    print(date)

    channel = re.search('-M\d(.*?)_', ds_name).group(1)
    print(channel)

    yl = date[0:4]
    yy = date[2:4]
    mt = date[5:7]
    dd = date[8:10]
    hh = date[11:13]
    mm = date[14:16]
    ss = date[17:19]

    str_date = str(dd) + '/' + str(mt) + '/' + str(yl) + " " + str(
        hh) + ":" + str(mm)
    date = datetime.datetime.strptime(
        str_date, '%d/%m/%Y %H:%M') - datetime.timedelta(hours=3)
    name = channel + " " + date.strftime('%d-%m-%Y %H:%M')
    filename = channel + "_" + yy + mt + dd + "_" + hh + mm + ss
    # print "name: " + name

    # extract/copy the data
    data = nc_fid.variables[data_name][:]

    if data_name == 'CMI' or data_name == 'Rad':
        # Satellite height
        sat_h = nc_fid.variables[
            'goes_imager_projection'].perspective_point_height
        # Satellite longitude
        sat_lon = nc_fid.variables[
            'goes_imager_projection'].longitude_of_projection_origin
        # Satellite sweep
        sat_sweep = nc_fid.variables['goes_imager_projection'].sweep_angle_axis
        X = nc_fid.variables[lon_name][:]  # longitud, eje X
        Y = nc_fid.variables[lat_name][:]  # latitud, eje Y

        scene_id_val = repr(nc_fid.getncattr('scene_id'))
        scene_id = re.search('\'(.*?)\'', scene_id_val).group(1)

    nc_fid.close()

    print("Realizando pasaje a K en C13 y truncamiento en los otros")

    for d in numpy.nditer(data, op_flags=['readwrite']):
        d = truncUno(d)
    data *= 100

    #######################################
    #######################################

    name = "GHI " + date.strftime('%d-%m-%Y %H:%M')

    nc_fid_ghi = netCDF4.Dataset(url, 'r')

    data = nc_fid_ghi.variables[data_name][:]
    X = nc_fid_ghi.variables[lon_name][:]  # longitud, eje X
    Y = nc_fid_ghi.variables[lat_name][:]  # latitud, eje Y
    nc_fid_ghi.close()

    for d in numpy.nditer(data, op_flags=['readwrite']):
        d = truncUno(d)
    data *= 100

    X *= sat_h
    Y *= sat_h

    vmin = 0.0
    vmax = 1200.0

    ax = Basemap(projection='merc',\
        llcrnrlat=-35.00,urcrnrlat=-30.00,\
        llcrnrlon=-58.77,urcrnrlon=-53.00,\
        resolution='f')
    projection = Proj(proj='geos',
                      h=sat_h,
                      lon_0=sat_lon,
                      sweep=sat_sweep,
                      ellps='WGS84')

    x_mesh, y_mesh = numpy.meshgrid(X, Y)
    lons, lats = projection(x_mesh, y_mesh, inverse=True)
    x, y = ax(lons, lats)

    ax.drawcoastlines(linewidth=0.40)
    ax.drawcountries(linewidth=0.40)
    ax.drawstates(linewidth=0.20)

    rincon_de_artigas_poly(ax)

    par = ax.drawparallels(numpy.arange(-40, -20, 2),
                           labels=[1, 0, 0, 0],
                           linewidth=0.0,
                           fontsize=7,
                           color='white')
    mer = ax.drawmeridians(numpy.arange(-70, -40, 2),
                           labels=[0, 0, 1, 0],
                           linewidth=0.0,
                           fontsize=7,
                           color='white')
    setcolor(par, 'white')
    setcolor(mer, 'white')

    print("Calculando GHI...")

    Isc = 1367.0
    # JPTv1
    a = 0.602
    b = 0.576
    c = -0.341
    d = -13.149

    def FR2GHI(lat, lon, fr):
        Cz, Gamma = cosSolarZenithAngle(lat, lon, date, 0)
        ghi = 0.
        if Cz > 0.:
            Fn = FnFunc(Gamma)
            ghi = Isc * Fn * Cz * (a + b * Cz + c * Cz) + d * fr
            if Isc * Fn * Cz != 0:
                Kt = ghi / (Isc * Fn * Cz)
                Kt = numpy.clip(Kt, 0.09, 0.85)
            ghi = Kt * Isc * Fn * Cz
        return ghi

    FR2GHI_vect = numpy.vectorize(FR2GHI, otypes=[float])

    GHI = FR2GHI_vect(lats, lons, data)

    ticks = [0, 200, 400, 600, 800, 1000, 1200]
    ticksLabels = ticks

    cmap = gmtColormap('irradiancia_v6', colormapPath, 2048)
    cs = ax.pcolormesh(x, y, GHI, vmin=vmin, vmax=vmax, cmap=cmap)

    plt.clim(vmin, vmax)

    # agrego el colorbar
    cbar = ax.colorbar(cs, location='bottom', ticks=ticks)  # , pad='3%'
    cbar.ax.set_xlabel(
        "Irradiancia solar global en plano horizontal ($W/m^2$)",
        fontsize=7,
        color='white')
    cbar.ax.set_xticklabels(ticksLabels, fontsize=7, color='white')

    # agrego el logo en el documento
    logo_bw = plt.imread('/sat/PRS/dev/PRS-sat/PRSgoes/logo_300_bw.png')
    plt.figimage(logo_bw, xo=5, yo=5)

    if not os.path.isdir(dirDest + channel + '/' + yl + '/ghi'):
        os.mkdir(dirDest + channel + "/" + yl + '/ghi')
    # if

    outPath = dirDest + channel + "/" + yl + "/ghi/"

    whitePath = outPath + filename + '_ghi_white.png'  # determino el nombre del archivo a escribir
    outPath = outPath + filename + '_ghi.png'  # determino el nombre del archivo a escribir

    x_coord = 109
    y_coord = -53

    Noche = numpy.sum(data) <= 0.

    if Noche:  # print "es noche"
        plt.annotate("NOCHE", (0, 0), (204, 15),
                     color='white',
                     xycoords='axes fraction',
                     textcoords='offset points',
                     va='top',
                     fontsize=10,
                     family='monospace')

    plt.annotate(name + " UY", (0, 0), (x_coord, y_coord),
                 xycoords='axes fraction',
                 textcoords='offset points',
                 va='top',
                 fontsize=11,
                 family='monospace',
                 color='white')
    plt.savefig(outPath, bbox_inches='tight', dpi=400,
                transparent=True)  # , facecolor='#4F7293'

    cbar.ax.set_xlabel(
        "Irradiancia solar global en plano horizontal ($W/m^2$)",
        fontsize=7,
        color='black')
    cbar.ax.set_xticklabels(ticksLabels, fontsize=7, color='black')

    # WHITE

    setcolor(par, 'black')
    setcolor(mer, 'black')

    logo_color = plt.imread('/sat/PRS/dev/PRS-sat/PRSgoes/logo_300_color.png')
    plt.figimage(logo_color, xo=5, yo=5)

    nota_ghi_w = plt.annotate(name + " UY", (0, 0), (x_coord, y_coord),
                              xycoords='axes fraction',
                              textcoords='offset points',
                              va='top',
                              fontsize=11,
                              family='monospace',
                              color='black')
    plt.savefig(whitePath,
                bbox_inches='tight',
                dpi=400,
                transparent=False,
                facecolor='white')  # , facecolor='#4F7293'

    copyfile(outPath, dirDest + channel + '_ghi.png')
    copyfile(whitePath, dirDest + channel + '_ghi_white.png')

    print("NUBOSIDAD")
    # NUBOSIDAD

    plt.clf()

    ax.drawcoastlines(linewidth=0.40)
    ax.drawcountries(linewidth=0.40)
    ax.drawstates(linewidth=0.20)

    rincon_de_artigas_poly(ax)

    par = ax.drawparallels(numpy.arange(-40, -20, 2),
                           labels=[1, 0, 0, 0],
                           linewidth=0.0,
                           fontsize=7,
                           color='white')
    mer = ax.drawmeridians(numpy.arange(-70, -40, 2),
                           labels=[0, 0, 1, 0],
                           linewidth=0.0,
                           fontsize=7,
                           color='white')
    setcolor(par, 'white')
    setcolor(mer, 'white')

    vmin = 0.0
    vmax = 100.0

    ticks = [0, 20, 40, 60, 80, 100]
    ticksLabels = ticks

    cmap = gmtColormap('nubosidad', colormapPath, 2048)
    cs = ax.pcolormesh(x, y, data, vmin=vmin, vmax=vmax, cmap=cmap)

    plt.clim(vmin, vmax)

    # agrego el colorbar
    cbar = ax.colorbar(cs, location='bottom', ticks=ticks)  # , pad='3%'
    cbar.ax.set_xlabel("Nubosidad (%)", fontsize=7, color='white')
    cbar.ax.set_xticklabels(ticksLabels, fontsize=7, color='white')

    plt.figimage(logo_bw, xo=5, yo=5)

    outPath = dirDest + channel + "/" + yl + "/ghi/"

    outPath = outPath + filename + '_cloud.png'  # determino el nombre del archivo a escribir
    whitePath = outPath + filename + '_cloud_white.png'  # determino el nombre del archivo a escribir

    x_coord = 109
    y_coord = -53

    plt.annotate("C02 " + date.strftime('%d-%m-%Y %H:%M') + " UY", (0, 0),
                 (x_coord, y_coord),
                 xycoords='axes fraction',
                 textcoords='offset points',
                 va='top',
                 fontsize=11,
                 family='monospace',
                 color='white')
    plt.draw()
    plt.savefig(outPath, bbox_inches='tight', dpi=400,
                transparent=True)  # , facecolor='#4F7293'

    # CLOUD WHITE

    setcolor(par, 'black')
    setcolor(mer, 'black')

    logo_color = plt.imread('/sat/PRS/dev/PRS-sat/PRSgoes/logo_300_color.png')
    plt.figimage(logo_color, xo=5, yo=5)

    plt.annotate("C02 " + date.strftime('%d-%m-%Y %H:%M') + " UY", (0, 0),
                 (x_coord, y_coord),
                 xycoords='axes fraction',
                 textcoords='offset points',
                 va='top',
                 fontsize=11,
                 family='monospace',
                 color='black')
    plt.savefig(whitePath,
                bbox_inches='tight',
                dpi=400,
                transparent=False,
                facecolor='white')  # , facecolor='#4F7293'

    copyfile(outPath, dirDest + channel + '_cloud.png')
    copyfile(whitePath, dirDest + channel + '_cloud_white.png')

    plt.close()
def plot_station_bot_sal(df,
                         var="PSAL_ADJUSTED",
                         elev=[0],
                         lons=[0],
                         lats=[0],
                         title=' ',
                         colorunit='Cond.',
                         cmin=33,
                         cmax=35.5,
                         contour=False,
                         save=False,
                         savename="savedFig.png",
                         wd=7,
                         ht=7):
    #not_null = ~df[var].isnull()

    color_var = df.loc[df.groupby('PROFILE_NUMBER').tail(1).index, var].values
    x = df.loc[df.groupby('PROFILE_NUMBER').tail(1).index, 'LONGITUDE'].values
    y = df.loc[df.groupby('PROFILE_NUMBER').tail(1).index, 'LATITUDE'].values

    plt.figure(1, figsize=(wd, ht))

    #m = Basemap(projection='hammer',lon_0=270)
    # plot just upper right quadrant (corners determined from global map).
    # keywords llcrnrx,llcrnry,urcrnrx,urcrnry used to define the lower
    # left and upper right corners in map projection coordinates.
    # llcrnrlat,llcrnrlon,urcrnrlon,urcrnrlat could be used to define
    # lat/lon values of corners - but this won't work in cases such as this
    # where one of the corners does not lie on the earth.
    #m1 = Basemap(projection='ortho',lon_0=-9,lat_0=60,resolution=None)

    #m = Basemap(projection='cyl', llcrnrlon=-120, llcrnrlat=-80, urcrnrlon=55,
    #            urcrnrlat=-30, lat_0 = -74, lon_0 =-43);
    lat0 = -89
    lon0 = 0
    m1 = Basemap(projection='ortho', lat_0=lat0, lon_0=lon0, resolution='i')
    width = m1.urcrnrx - m1.llcrnrx
    height = m1.urcrnry - m1.llcrnry
    m  = Basemap(projection='ortho', lat_0=lat0, lon_0=lon0, resolution='i', llcrnrx=-width*0.30, llcrnry=-0.30*height,\
                 urcrnrx=0.30*width, urcrnry=0.30*height)

    #lat_0 = -60, lon_0 = -20,
    xm, ym = m(x, y)

    m.drawmapboundary()
    m.drawcoastlines()
    m.readshapefile(
        "/media/data/Datasets/Shapefiles/AntarcticGroundingLine/GSHHS_f_L6",
        "GSHHS_f_L6",
        color='m')
    #m.fillcontinents(color='#ddaa66');

    sc = m.scatter(xm, ym, c=color_var, vmin=cmin, vmax=cmax, s=0.3)
    #, cmap='viridis'
    cbar = m.colorbar(sc, pad="10%", location='bottom')
    cbar.set_label(colorunit)
    parallels = np.arange(-80, -50 + 1, 5.)

    if (contour == True):
        lon2, lat2 = np.meshgrid(
            lons, lats)  # get lat/lons of ny by nx evenly space grid.
        xx, yy = m(lon2, lat2)  # compute map proj coordinates.

        levs = np.array([-600, -900, -1500])
        cont = m.contour(xx,
                         yy,
                         elev,
                         levels=levs[::-1],
                         colors='0.5',
                         linestyles='-',
                         linewidths=(0.5, ))  #clevs[::-1], , cmap='rainbow'
        plt.clabel(cont, fmt='%2.1d', colors='0.5', fontsize=8)

    m.drawparallels(parallels, labels=[1, 1, 1, 0])
    meridians = np.arange(-180, 180, 20.)
    m.drawmeridians(meridians, labels=[1, 1, 0, 1])
    plt.title(title, y=1.05)
    plt.tight_layout()
    if (save == True):
        plt.savefig(savename, dpi=150)
    plt.show()
   m.drawcoastlines(color='0.0', linewidth=4.5)
   #m.drawcountries(color='0.', linewidth=4.5)
   m.drawparallels(np.arange(-90.,91.,30.), labels=[1,0,0,1],    dashes=[1,1], linewidth=1.0, color='0.5',fontsize='x-large', fontname='Times')
   m.drawmeridians(np.arange(0., 360., 60.), labels=[1,0,0,1], dashes=[1,1], linewidth=1.0, color='0.5',fontsize='x-large', fontname='Times')

 
   #PLOT ABSOLUTE
   #cs = m.contourf(X2,Y2,mdata,levels,cmap=cmap,extend='both')
   cs = m.contourf(X2,Y2,mdata,levels,cmap=cmap)
   vmin,vmax = (-0.01251*max_val,max_val)


   plt.tight_layout()
   #cbar = m.colorbar(cs,location='bottom',pad='10%',ticks=np.linspace(vmin,vmax,7),format='%.1f')
   ticks = [0.,0.0251*max_val,.1*max_val,.3*max_val,.5*max_val,.7*max_val,.8*max_val,1.*max_val]
   cbar = m.colorbar(cs,location='bottom',pad='10%',ticks=ticks,format='%.1f')
   #cbar.ax.get_yaxis().labelpad = 60
   cbar.ax.get_xaxis().labelpad = 45
   #cbar.ax.set_ylabel('EM (%)', rotation=270)
   cbar.ax.set_xlabel('g N m$^{-2}$ yr$^{-1}$', rotation=0,color='black', size=78, fontname='Times')
   #cbar.ax.set_xlabel('ECM tree basal area (%)', rotation=0,color='black', size=78)
   #no coloredge
   #cbar.solids.set_edgecolor("face")
   cbar.solids.set_edgecolor("black")
   cbar.solids.set_linewidth(6)
   #cbar.set_clim(0.0,100)
   cbar.set_clim(vmin,vmax)
   plt.title(r'Mycorrhizal uptake', fontname='Times', fontsize=92,pad=26)
   cbar.ax.tick_params(labelsize='xx-large')
   #plt.savefig('em_steindinger_tot.pdf',bbox_inches="tight",dpi=300)
   plt.savefig('figures/Nitrogen_fun/NACTIVE.png',bbox_inches="tight")
def draw_map(station_etude,
             latm,
             latM,
             lonm,
             lonM,
             path,
             all_pos,
             hw,
             vn_ITRF,
             ve_ITRF,
             plot_vertical_ITRF,
             incvn_ITRF,
             incve_ITRF,
             incplot_vertical_ITRF,
             plot_GEBCO=False,
             plot_vertical=False,
             plot_topo=True,
             plot_ellipses=True,
             coarse_lines=False,
             legend_arrow_length=("1 cm/yr", 0.01),
             legend_ellipse_size=("2 mm/yr", 0.002),
             legend_position=(0.5, 0.9),
             scale_arrow=15000000,
             scale_ellipse=10000000,
             name_stats=True,
             name_stats_font_size=8,
             name_stats_offset=(0.005, 0.01),
             shorten_oversized_arrows=True,
             exclude_points_out_of_range=True,
             adjust_text=False,
             pixels_hires_backgrnd=2000,
             draw_borders=True,
             full_return=False,
             draw_latlon_lines=True):
    """
    """

    nstation = len(station_etude)
    fig, ax = plt.subplots(figsize=(7, 8))

    if incvn_ITRF is None:
        incvn_ITRF = np.zeros(len(station_etude))
    if incve_ITRF is None:
        incve_ITRF = np.zeros(len(station_etude))
    if incplot_vertical_ITRF is None:
        incplot_vertical_ITRF = np.zeros(len(station_etude))

    if coarse_lines:
        resolution = "l"
    else:
        resolution = "h"
    m = Basemap(projection='merc',
                llcrnrlat=latm,
                urcrnrlat=latM,
                llcrnrlon=lonm,
                urcrnrlon=lonM,
                lat_ts=-20,
                resolution=resolution,
                area_thresh=1,
                epsg=3395)

    if draw_borders:
        m.drawcoastlines(linewidth=0.25)
        m.drawcountries()
        m.drawstates()

    if plot_topo:
        m.arcgisimage(service='World_Shaded_Relief',
                      xpixels=pixels_hires_backgrnd,
                      verbose=True)
    else:
        m.drawmapboundary(fill_color='#97B6E1')
        m.fillcontinents(color='#EFEFDB', lake_color='#97B6E1', zorder=1)
        m.shadedrelief()

    if not plot_GEBCO:
        color1 = 'black'
    else:
        color1 = 'white'
        levels = [-8000, -7000, -6000, -5500, -5000, -4500,
                  -4000]  #Niveaux pour l'echelle de couleur
        gebconc = Dataset(path + 'GEBCO\\GRIDONE_2D.nc')
        #Vecteur longitudes/latitudes
        long_ini = gebconc.variables['lon'][:]
        lats_ini = gebconc.variables['lat'][:]
        (lats_area, longs_area,
         gebco_area) = area(long_ini, lats_ini, gebconc, latm, latM, lonm,
                            lonM, '0-180')  #lat bas,lat haut, long
        (longs, lats, gebco) = split_grid(longs_area, lats_area, gebco_area, 2)
        (longs_gr, lats_gr) = np.meshgrid(longs, lats)
        fond = m.pcolormesh(longs_gr,
                            lats_gr,
                            gebco,
                            shading='flat',
                            cmap=LevelColormap(list(np.asarray(levels) * (1)),
                                               cmap=cm.deep_r),
                            latlon=True)  #ice,deep
        cbar = m.colorbar(location='top', pad=0.5)
        cbar.set_label('Depth [m] ', rotation=0)

    if draw_latlon_lines:
        m.drawparallels(np.arange(latm, latM, 1.),
                        fontsize=10,
                        color=color1,
                        labels=[True, False, False, False],
                        linewidth=0.25,
                        dashes=[10000, 1])  #de -180 a 360 par pas de 5° ;
        m.drawmeridians(np.arange(lonm, lonM, 1.),
                        fontsize=10,
                        color=color1,
                        labels=[False, False, False, True],
                        linewidth=0.25,
                        dashes=[10000, 1])  # Haut / G/D/BAS
        ### Labels
        plt.xlabel('Longitude (°) ', labelpad=25, fontsize=10)
        plt.ylabel('Latitude (°) ', labelpad=40, fontsize=10)
        ax.yaxis.set_label_position("left")

    all_posx_proj = [0] * nstation
    all_posy_proj = [0] * nstation
    for i in range(nstation):
        all_posx_proj[i], all_posy_proj[i] = m(
            all_pos[i][1], all_pos[i][0]
        )  #positions xy des stations converties a la projection de la carte  [m]
        print(i, all_posx_proj[i], all_posy_proj[i])
        m.plot(
            all_posx_proj[i],
            all_posy_proj[i],
            'xkcd:black',
            marker='.',
            linestyle='none',
            markersize=4,
            lw=4,
            zorder=20
        )  #point rouge à la station, zorder indique l'ordre vertical de dessin sur la carte, les nb elevés sont dessinés les plus hauts
#          plt.text(all_posx_proj[i], all_posy_proj[i], station_etude[i], size=10,ha="center", va="center",bbox=dict(boxstyle="round",
#                           ec=(1., 0.5, 0.5),
#                           fc=(1., 0.8, 0.8),
#                           )
#                 )

############### DICO POUR FLECHES DEFINITION
    arrow_prop_dict = dict(arrowstyle='->,head_length=0.8,head_width=0.3',
                           ec='xkcd:black',
                           fc='xkcd:black',
                           linewidth=2)

    arrow_prop_dict_V_up = dict(arrowstyle='->,head_length=0.8,head_width=0.3',
                                ec='xkcd:green',
                                fc='xkcd:green',
                                linewidth=2)

    arrow_prop_dict_V_down = dict(
        arrowstyle='->,head_length=0.8,head_width=0.3',
        ec='xkcd:red orange',
        fc='xkcd:red orange',
        linewidth=2)

    arrow_prop_dict_V_up_short = dict(
        arrowstyle='->,head_length=0.8,head_width=0.3',
        ec='xkcd:green',
        fc='xkcd:green',
        linewidth=2,
        linestyle="--")

    arrow_prop_dict_V_down_short = dict(
        arrowstyle='->,head_length=0.8,head_width=0.3',
        ec='xkcd:red orange',
        fc='xkcd:red orange',
        linewidth=2,
        linestyle="--")

    if not plot_vertical:  #CHAMP VITESSES HORIZONTALES
        for i in range(nstation):

            ######### Exclude point if not in range
            #latm,latM,lonm,lonM
            bool_good_lat = latm < all_pos[i][0] < latM
            bool_good_lon = lonm < all_pos[i][1] < lonM
            if exclude_points_out_of_range and not (bool_good_lat
                                                    and bool_good_lon):
                print("INFO : exclude point because out of range")
                continue

            x_end_arrow_ok = all_posx_proj[i] + np.multiply(
                ve_ITRF[i], scale_arrow)
            y_end_arrow_ok = all_posy_proj[i] + np.multiply(
                vn_ITRF[i], scale_arrow)

            ax.annotate(
                s='',
                xy=(x_end_arrow_ok, y_end_arrow_ok),
                xytext=(all_posx_proj[i], all_posy_proj[i]),
                arrowprops=arrow_prop_dict,
                annotation_clip=True
            )  #xy point arrivee de la fleche, xytext l'origine de la fleche
            a = math.atan(
                (all_posx_proj[i] + np.multiply(ve_ITRF[i], scale_arrow) -
                 all_posy_proj[i]) /
                (all_posy_proj[i] + np.multiply(ve_ITRF[i], scale_arrow) -
                 all_posy_proj[i])
            )  # l'angle d'orientation de l'ellipsoide, avec 0 au nord et +90 a l'ouest

            e = Ellipse(
                xy=(x_end_arrow_ok, y_end_arrow_ok),
                width=np.multiply(2, incve_ITRF[i]) * scale_ellipse,
                height=np.multiply(2, incvn_ITRF[i]) * scale_ellipse,
                angle=a
            )  #multiplication par 2 pour obtenir la largeur et la hauteur de l'ellipse

            # STATION NAME
            if name_stats:
                offset_x_ok, offset_y_ok = utils.axis_data_coords_sys_transform(
                    ax, name_stats_offset[0], name_stats_offset[1])
                plt.text(all_posx_proj[i] + offset_x_ok,
                         all_posy_proj[i] + offset_y_ok,
                         station_etude[i],
                         fontsize=name_stats_font_size)

            # ELIPSES
            if plot_ellipses:
                ax.add_artist(e)
                e.set_clip_box(ax.bbox)
                e.set_edgecolor('none')
                e.set_facecolor('black')
                e.set_alpha(0.3)
                e.set_zorder(1)

    else:  # Champ de vitesses verticales ITRF
        ############### PLOT FLECHES
        Text = []
        for i in range(nstation):

            ######### Exclude point if not in range
            #latm,latM,lonm,lonM
            bool_good_lat = latm < all_pos[i][0] < latM
            bool_good_lon = lonm < all_pos[i][1] < lonM
            if exclude_points_out_of_range and not (bool_good_lat
                                                    and bool_good_lon):
                print("INFO : exclude point because out of range")
                continue

            ######### AJUSTEMENT SI FLECHES TROP GRANDES
            x_end_arrow, y_end_arrow = all_posx_proj[i], all_posy_proj[
                i] + np.multiply(plot_vertical_ITRF[i], scale_arrow)

            x_end_axis_ref, y_end_axis_ref = utils.axis_data_coords_sys_transform(
                ax, x_end_arrow, y_end_arrow, inverse=True)

            if (y_end_axis_ref < 0.) and shorten_oversized_arrows:
                shortened_arrow = True
                x_end_arrow_ok = x_end_arrow
                _, y_end_arrow_ok = utils.axis_data_coords_sys_transform(
                    ax, x_end_axis_ref, 0, inverse=False)
            elif (y_end_axis_ref > 1.) and shorten_oversized_arrows:
                shortened_arrow = True
                x_end_arrow_ok = x_end_arrow
                _, y_end_arrow_ok = utils.axis_data_coords_sys_transform(
                    ax, x_end_axis_ref, 1., inverse=False)
            else:
                shortened_arrow = False
                x_end_arrow_ok = x_end_arrow
                y_end_arrow_ok = y_end_arrow

            ######### FIN AJUSTEMENT SI FLECHES TROP GRANDES

            ### SELECT ARROW PROPERTY DEPENDING ON THE TYPE
            if plot_vertical_ITRF[i] > 0 and not shortened_arrow:
                arrow_prop_dict_V = arrow_prop_dict_V_up
            elif plot_vertical_ITRF[i] > 0 and shortened_arrow:
                arrow_prop_dict_V = arrow_prop_dict_V_up_short
            elif plot_vertical_ITRF[i] <= 0 and not shortened_arrow:
                arrow_prop_dict_V = arrow_prop_dict_V_down
            elif plot_vertical_ITRF[i] <= 0 and shortened_arrow:
                arrow_prop_dict_V = arrow_prop_dict_V_down_short

            ### PLOT
            ax.annotate(s='',
                        xy=(x_end_arrow_ok, y_end_arrow_ok),
                        xytext=(all_posx_proj[i], all_posy_proj[i]),
                        arrowprops=arrow_prop_dict_V,
                        annotation_clip=False)
            #xy point arrivee de la fleche, xytext l'origine de la fleche

            ### STATION NAME
            if name_stats:
                offset_x_ok, offset_y_ok = utils.axis_data_coords_sys_transform(
                    ax, name_stats_offset[0], name_stats_offset[1])

                Text.append(
                    plt.text(all_posx_proj[i] + offset_x_ok,
                             all_posy_proj[i] + offset_y_ok,
                             station_etude[i],
                             fontsize=name_stats_font_size))

            ############### PLOT ELLIPSES
            # angle de l'ellipse dépend de la direction du vecteur vitesse
            a = math.atan(
                (all_posx_proj[i] + np.multiply(
                    plot_vertical_ITRF[i], scale_arrow) - all_posx_proj[i]) /
                (all_posy_proj[i] + np.multiply(
                    plot_vertical_ITRF[i], scale_arrow) - all_posy_proj[i])
            )  # l'angle d'orientation de l'ellipsoide, avec 0 au nord et +90 a l'ouest

            # weird previous xy definition
            # [all_posx_proj[i]+np.multiply(plot_vertical_ITRF[i],0),all_posy_proj[i]+0.85*np.multiply(plot_vertical_ITRF[i],scale_arrow)]

            e = Ellipse(
                xy=(x_end_arrow_ok, y_end_arrow_ok),
                width=np.multiply(2, incplot_vertical_ITRF[i]) * scale_ellipse,
                height=np.multiply(2, incplot_vertical_ITRF[i]) *
                scale_ellipse,
                angle=a
            )  #multiplication par 2 pour obtenir la largeur et la hauteur de l'ellipse
            # ax.plot(all_posx_proj[i]+np.multiply(plot_vertical_ITRF[i],0),all_posy_proj[i]+np.multiply(plot_vertical_ITRF[i],scale_arrow),'xkcd:green',marker='.',linestyle='none',markersize=4,lw=4,zorder=20) #point rouge à la station, zorder indique l'ordre vertical de dessin sur la carte, les nb elevés sont dessinés les plus hauts

            ax.add_artist(e)
            e.set_clip_box(ax.bbox)
            e.set_edgecolor('none')
            e.set_facecolor('black')
            e.set_alpha(0.3)
            e.set_zorder(1)

    ############### LEGENDE
    legend_arrow_length_label = legend_arrow_length[0]
    legend_ellipse_size_label = legend_ellipse_size[0]
    legend_arrow_length_metric = legend_arrow_length[1]
    legend_ellipse_size_metric = legend_ellipse_size[1]
    legend_position_x = legend_position[0]
    legend_position_y = legend_position[1]

    ######## Fleche de Legende
    ### origine de la fleche de legende
    xl, yl = utils.axis_data_coords_sys_transform(ax,
                                                  legend_position_x,
                                                  legend_position_y + 0.02,
                                                  inverse=False)
    ### fin de la fleche de legende
    xe, ye = xl + np.multiply(legend_arrow_length_metric, scale_arrow), yl

    plt.annotate(
        s='', xy=(xe, ye), xytext=(xl, yl), arrowprops=arrow_prop_dict
    )  #xy point arrivee de la fleche, xytext l'origine de la fleche

    props = dict(boxstyle='round', facecolor='black', alpha=0)
    ax.text(legend_position_x,
            legend_position_y + 0.035,
            'Velocity : ' + legend_arrow_length_label,
            transform=ax.transAxes,
            fontsize=11,
            color='black',
            verticalalignment='bottom',
            bbox=props)  # place a text box in upper left in axes coords

    ######## Légende de l'ellipse d'incertitude
    ax.text(legend_position_x,
            legend_position_y,
            '+/- ' + legend_ellipse_size_label + ' (radius)',
            transform=ax.transAxes,
            fontsize=11,
            color='black',
            verticalalignment='top',
            bbox=props)
    ells_legend = Ellipse(xy=[xe, ye],
                          width=np.multiply(
                              2,
                              np.multiply(legend_ellipse_size_metric,
                                          scale_ellipse)),
                          height=np.multiply(
                              2,
                              np.multiply(legend_ellipse_size_metric,
                                          scale_ellipse)),
                          angle=a)

    if plot_ellipses:
        ax.add_artist(ells_legend)
        ells_legend.set_clip_box(ax.bbox)
        ells_legend.set_edgecolor('none')
        ells_legend.set_facecolor('black')
        ells_legend.set_alpha(0.3)
        ells_legend.set_zorder(1)

    ############### FINITION

    for T in Text:  #Put label in front
        T.set_zorder(100)

    if adjust_text:
        from adjustText import adjust_text
        adjust_text(
            Text,
            on_basemap=True)  #arrowprops=dict(arrowstyle='->', color='red')

    plt.tight_layout()

    if full_return:
        return fig, ax, m, Text
    else:
        return fig, ax, m, Text
Beispiel #41
0
delat = lats[1] - lats[0]
lons = (lons - 0.5 * delon).tolist()
lons.append(lons[-1] + delon)
lons = np.array(lons, np.float64)
lats = (lats - 0.5 * delat).tolist()
lats.append(lats[-1] + delat)
lats = np.array(lats, np.float64)
# creat figure, axes instances.
fig = plt.figure()
ax = fig.add_axes([0.05, 0.05, 0.9, 0.9])
# create Basemap instance for Robinson projection.
# coastlines not used, so resolution set to None to skip
# continent processing (this speeds things up a bit)
m = Basemap(projection='robin', lon_0=lons.mean(), resolution=None)
# compute map projection coordinates of grid.
x, y = m(*np.meshgrid(lons, lats))
# draw line around map projection limb.
# color background of map projection region.
# missing values over land will show up this color.
m.drawmapboundary(fill_color='0.3')
# plot sst, then ice with pcolor
im1 = m.pcolor(x, y, sst, shading='flat', cmap=plt.cm.jet)
im2 = m.pcolor(x, y, ice, shading='flat', cmap=plt.cm.gist_gray)
# draw parallels and meridians, but don't bother labelling them.
m.drawparallels(np.arange(-90., 120., 30.))
m.drawmeridians(np.arange(0., 420., 60.))
# add colorbar
cb = m.colorbar(im1, "bottom", size="5%", pad="2%")
# add a title.
ax.set_title('SST and ICE analysis for %s' % date)
plt.savefig('plotsst.png')
Beispiel #42
0
### Plotting with Basemap ###
#############################

m = Basemap(projection='npstere',boundinglat=61.5,lat_0=90,lat_ts=70,lon_0=-35,\
            resolution='l',round=False)
#m.drawcoastlines()
m.fillcontinents(color='grey')  #,lake_color='aqua')
#m.drawparallels(np.arange(-80.,81.,5.))
#m.drawmeridians(np.arange(-180.,181.,20.))
#m.drawmapboundary(fill_color='aqua')

x, y = m(lon1, lat1, inverse=False)  #,indexing='ij')

plt.figure(1)
c2 = m.contourf(x, y, RESr, np.arange(0.0, 0.11, 0.0001))
cb = m.colorbar(ticks=(0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09,
                       0.10, 0.11))
cb.set_label('')
plt.set_cmap('jet')
#cb.set_clim(np.nanmin(RESr),np.nanmax(RESr))
plt.title('ResReal _ ' + str(b[0]) + '-' + str(b[-1] + 1))

m = Basemap(projection='npstere',boundinglat=61.5,lat_0=90,lat_ts=70,lon_0=-35,\
            resolution='l',round=False)
#m.drawcoastlines()
m.fillcontinents(color='grey')  #,lake_color='aqua')

plt.figure(2)
c2 = m.contourf(x, y, RESi, np.arange(0.0, 0.11, 0.0001))
cb = m.colorbar(ticks=(0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09,
                       0.10, 0.11))
cb.set_label('')
Beispiel #43
0
lat	= HEAT_data.variables['lat'][:] 			
temp	= HEAT_data.variables['TEMP'][:]		

HEAT_data.close()

lon, temp	= PeriodicBoundaries(lon, lat, temp)

#-----------------------------------------------------------------------------------------

fig, ax		= subplots()

m = Basemap(projection='spstere',boundinglat=-60,lon_0=180,resolution='i',  area_thresh=0.01) 

m.drawcoastlines(linewidth=0.5)
m.drawcountries()
m.fillcontinents(color='#cc9966',lake_color='#99ffff')
m.drawmapboundary(fill_color='azure')

m.drawparallels(np.arange(-80,81,20),labels=[0,0,0,0])
m.drawmeridians(np.arange(-180,180,30),labels=[1,0,0,1])


x, y	= np.meshgrid(lon, lat)
x, y	= m(x, y)
CS	= m.contourf(x, y, temp, levels = np.arange(-3, 3.01, 0.2), extend = 'both', cmap = 'RdBu_r')
cbar	= m.colorbar(CS, ticks = np.arange(-3, 3.01, 1))
cbar.set_label('Temperature difference ($^{\circ}$C)')

ax.set_title('e) HR-CESM Control minus Mercator')

show()
def uhi_kriging(shpFiles, lonlat, stationName, mLon, mLat, mTem, levels,
                outfilename):

    #绘图参数设置
    isStationInfoOn = False  #站点信息是否标注
    isaxInfoOn = True  # 坐标轴信息是否标注
    cmap = cmaps.amwg256  #BlAqGrYeOrReVi200 #色标选择 http://www.ncl.ucar.edu/Document/Graphics/color_table_gallery.shtml 参考该网址 MPL_YlOrRd  amwg256

    levels = levels
    fbl = 0.05  #克里金插值空间分辨率
    picTitle = 'Temperature'
    zuobiaoSetInter = 0.5  #坐标轴经纬度间隔设置

    # 初始化
    shpFile = shpFiles[0]
    bjshp = shpFiles[1]

    #天津经纬度范围设置
    llat = 38.5
    ulat = 40.3
    llon = 116.7
    ulon = 118.05

    fig = plt.figure(figsize=(6, 6))
    plt.rc('font', size=15, weight='bold')
    ax = fig.add_subplot(111)

    # 底图读取及地图设置
    m=Basemap(llcrnrlon=llon,llcrnrlat=llat,urcrnrlon=ulon,urcrnrlat=ulat,\
        projection='cyl',resolution='c')   # 等距投影
    m.readshapefile(shpFile, 'Name', linewidth=1, color='k')

    # 坐标系经纬度转换
    xllon, yllat = m(llon, llat)
    xulon, yulat = m(ulon, ulat)
    xmLon, ymLat = m(mLon, mLat)

    # meshgrid set the grid range
    gridx = np.arange(xllon, xulon, fbl)
    gridy = np.arange(yllat, yulat, fbl)

    Xlon, Ylat = np.meshgrid(gridx, gridy)

    #插值处理
    OK = OrdinaryKriging(xmLon,
                         ymLat,
                         mTem,
                         variogram_model='linear',
                         verbose=False,
                         enable_plotting=False)
    z, ss = OK.execute('grid', gridx, gridy)

    cf = m.contourf(Xlon, Ylat, z, levels=levels, cmap=cmap)
    m.colorbar(cf,location='right',format='%.1f',size=0.3,\
            ticks=levels) #,label='单位:℃')

    # 添加站名信息
    if isStationInfoOn == True:
        m.scatter(xmLon, ymLat, c='k', s=10, marker='o')
        for i in range(0, len(xmLon)):
            #            pass
            plt.text(xmLon[i],
                     ymLat[i],
                     stationName[i],
                     va='bottom',
                     fontsize=12)
        # plt.text(xmLon[i],ymLat[i],mTem[i],va='top',fontsize=12)

        plt.title(picTitle)

    # 坐标轴标注
    if isaxInfoOn == True:
        lon_label = []
        lat_label = []
        lon_num = np.arange(xllon, xulon, zuobiaoSetInter)
        for lon in lon_num:
            lon_label.append(str(lon) + '°E')

        lat_num = np.arange(yllat, yulat, zuobiaoSetInter)
        for lat in lat_num:
            lat_label.append(str(lat) + '°N')

        plt.yticks(lat_num, lat_label)
        plt.xticks(lon_num, lon_label)

    # 白化
    maskout.shp2clip(cf, ax, bjshp, 0.005588)  #0.005588为gis图周长信息

    # picture introduction
    #    plt.show()
    plt.savefig(r'./results/' + outfilename, dpi=600)
    #图片输出
    '''
Beispiel #45
0
            urcrnrlon=360,
            urcrnrlat=90,
            projection='mill')
lons, lats = np.meshgrid(lon, lat)
x, y = m(lons, lats)

fig1 = plt.figure(figsize=(16, 20))
ax = fig1.add_axes([0.1, 0.1, 0.8, 0.8])
clevs = np.linspace(-240, 240, 21)
CS1 = m.contour(x, y, pre_1997, clevs, linewidths=0.5, colors='k')
CS2 = m.contourf(x, y, pre_1997, clevs, cmap=plt.cm.RdBu_r)
m.drawmapboundary(fill_color='#99ffff')
m.drawcoastlines(linewidth=1.5)
m.drawparallels(np.arange(-90, 90, 20), labels=[1, 1, 0, 0])
m.drawmeridians(np.arange(0., 360., 20.), labels=[0, 0, 0, 1])
cbar = m.colorbar(CS2, location='bottom', pad="5%")
cbar.set_label('mm')
plt.title('Regression Precipitation Anomaly in 1997')
plt.savefig("./1997.png", dpi=500)

fig2 = plt.figure(figsize=(16, 20))
ax = fig2.add_axes([0.1, 0.1, 0.8, 0.8])
clevs = np.linspace(-240, 240, 21)
CS1 = m.contour(x, y, pre_1998, clevs, linewidths=0.5, colors='k')
CS2 = m.contourf(x, y, pre_1998, clevs, cmap=plt.cm.RdBu_r)
m.drawmapboundary(fill_color='#99ffff')
m.drawcoastlines(linewidth=1.5)
m.drawparallels(np.arange(-90, 90, 20), labels=[1, 1, 0, 0])
m.drawmeridians(np.arange(0., 360., 20.), labels=[0, 0, 0, 1])
cbar = m.colorbar(CS2, location='bottom', pad="5%")
cbar.set_label('mm')
def metpyplot(shpFiles, lonlat, mLon, mLat, mTem):
    # 初始化
    #绘图参数设置
    isStationInfoOn = False  #站点信息是否标注
    isaxInfoOn = False  # 坐标轴信息是否标注
    cmap = cmaps.BlAqGrYeOrReVi200  #色标选择 http://www.ncl.ucar.edu/Document/Graphics/color_table_gallery.shtml 参考该网址 MPL_YlOrRd  amwg256
    legendRange = [int(min(mTem)), math.ceil(max(mTem))]
    fbl = 0.05  #克里金插值空间分辨率
    sebiaoNums = 15  #色标个数
    picTitle = 'Temperature'
    zuobiaoSetInter = 0.5  #坐标轴经纬度间隔设置

    #    shpPath=r'./shp/TJ/'
    #    shpName='TJ_all'
    ##    bjName='TJ_bj'
    shpFile = shpFiles[0]
    #    bjshp=shpPath+bjName

    #天津经纬度范围设置
    #    llat=38.5
    #    ulat=40.3
    #    llon=116.7
    #    ulon=118.05
    llon = lonlat[0]
    ulon = lonlat[1]
    llat = lonlat[2]
    ulat = lonlat[3]

    #    fig=plt.figure(figsize=(16,9))
    plt.rc('font', size=15, weight='bold')
    #    ax=fig.add_subplot(111)

    # 底图读取及地图设置
    m=Basemap(llcrnrlon=llon,llcrnrlat=llat,urcrnrlon=ulon,urcrnrlat=ulat,\
        projection='cyl',resolution='c')   # 等距投影
    m.readshapefile(shpFile, 'Name', linewidth=1, color='k')
    # 绘制经纬线
    parallels = np.arange(llat, ulat, 0.5)
    m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)  # 绘制纬线

    meridians = np.arange(llon, ulon, 0.5)
    m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)  # 绘制经线

    # 坐标系经纬度转换
    xllon, yllat = m(llon, llat)
    xulon, yulat = m(ulon, ulat)
    xmLon, ymLat = m(mLon, mLat)

    # meshgrid set the grid range
    gridx = np.arange(xllon, xulon, fbl)
    gridy = np.arange(yllat, yulat, fbl)

    Xlon, Ylat = np.meshgrid(gridx, gridy)

    #插值处理
    #    OK=OrdinaryKriging(xmLon,ymLat,mTem,variogram_model='linear',
    #               verbose=False,enable_plotting=False)
    #    z,ss=OK.execute('grid',gridx,gridy)
    gx, gy, img = interpolate(xmLon, ymLat, mTem, \
                              interp_type='linear', hres=fbl)

    levels = np.linspace(legendRange[0], legendRange[1], sebiaoNums)
    cs = m.contourf(gx, gy, img, levels, cmap=cmap)
    m.colorbar(cs)

    #    cf=m.contourf(Xlon,Ylat,z,levels=levels,cmap=cmap)
    #    m.colorbar(cf,location='right',format='%.1f',size=0.3,\
    #            ticks=np.linspace(legendRange[0],legendRange[1],sebiaoNums),label='单位:℃')
    #
    # 添加站名信息
    if isStationInfoOn == True:
        m.scatter(xmLon, ymLat, c='k', s=10, marker='o')
        for i in range(0, len(xmLon)):
            #            pass
            plt.text(xmLon[i],
                     ymLat[i],
                     stationName[i],
                     va='bottom',
                     fontsize=12)
        # plt.text(xmLon[i],ymLat[i],mTem[i],va='top',fontsize=12)

        plt.title(picTitle)

    # 坐标轴标注
    if isaxInfoOn == True:
        lon_label = []
        lat_label = []
        lon_num = np.arange(xllon, xulon, zuobiaoSetInter)
        for lon in lon_num:
            lon_label.append(str(lon) + '°E')

        lat_num = np.arange(yllat, yulat, zuobiaoSetInter)
        for lat in lat_num:
            lat_label.append(str(lat) + '°N')

        plt.yticks(lat_num, lat_label)
        plt.xticks(lon_num, lon_label)

    # 白化
#    maskout.shp2clip(cf,ax,bjshp,0.005588)  #0.005588为gis图周长信息

# picture introduction
    plt.show()
Beispiel #47
0
                       yy,
                       zz,
                       levels=levels,
                       colors=('k', ),
                       linewidths=(0.1, ))
        plt.clabel(cs, fmt='%1.0f', colors='k', fontsize=3)

        levels = np.concatenate((np.arange(-6, 0,
                                           0.5), np.arange(0.5, 6.1, 0.5)))
        cmap = plt.cm.get_cmap("jet_r")
        cs = m.contourf(xx, yy, zz, cmap=cmap, levels=levels, extend="both")
        cs.cmap.set_over('black')
        cs.cmap.set_under('purple')
        # colorbar for contourfill
        cb = m.colorbar(cs,
                        location='right',
                        ticks=np.arange(-6, 6.1, 1),
                        pad="5%")
        cb.ax.set_title('(%)', fontsize=10)
        #cb.set_label('%')
        ax.set_title("{:s}".format(model_tag))
    elif model_tag in ['kappa']:
        dz = (np.max(zz) - np.min(zz)) / 10
        dz = round_to_1(dz)
        levels = np.arange(np.min(zz), np.max(zz) + dz / 2, dz)
        cmap = plt.cm.get_cmap("jet")
        cs = m.contourf(xx, yy, zz, cmap=cmap, levels=levels, extend="both")
        cs.cmap.set_over('purple')
        cs.cmap.set_under('black')
        # colorbar for contourfill
        cb = m.colorbar(cs, location='right', pad="5%", format="%.2f")
        #cb.set_label('% mean')
Beispiel #48
0
def plot_compare(plot_list, date_time):
    formated_dt = date_time[0:4] + '-' + date_time[4:6] + '-' + date_time[
        6:8] + '_' + date_time[8:10] + ':' + date_time[10:12] + ':00'
    m8_df, m11_df = plot_list
    fig = plt.figure()
    latitude = m8_df['LATITUDE'].values
    longitude = m8_df['LONGITUDE'].values
    FRP = m8_df['FRP'].values

    ax = fig.add_subplot(121)
    m_m8 = Basemap(llcrnrlon=-30,
                   llcrnrlat=-35,
                   urcrnrlon=60,
                   urcrnrlat=40,
                   resolution='i',
                   projection='tmerc',
                   lon_0=15,
                   lat_0=0,
                   ax=ax)
    #m_m8 = Basemap(llcrnrlon=28,llcrnrlat=8,urcrnrlon=32,urcrnrlat=10,
    #                                resolution='i',projection='tmerc',lon_0=30,lat_0=9,ax=ax)
    m_m8.drawcoastlines(linewidth=0.5)
    m_m8.drawmapboundary()
    #m.fillcontinents(lake_color='aqua',zorder=0)
    m_m8.drawparallels(np.arange(-35, 60., 20), labels=[True], fontsize=5)
    m_m8.drawmeridians(np.arange(-40., 100., 20))
    #m_m8.drawcountries(linewidth=0.25)
    x, y = m_m8(longitude, latitude)
    sc = plt.scatter(x,
                     y,
                     c=FRP,
                     s=10,
                     alpha=0.8,
                     cmap='hot',
                     marker=',',
                     zorder=1,
                     norm=mpl.colors.SymLogNorm(linthresh=2, vmin=0,
                                                vmax=1000))
    plt.title('Meteosat-8', fontsize=9)
    cb = m_m8.colorbar(sc, pad=0.001, ticks=[0, 1000])  #location='bottom')
    cb.ax.tick_params(labelsize=8)
    cb.ax.set_yticklabels([])
    #cb.set_ticks([0,200,400,600,800])         # need editting to be more case adaptive range
    #cb.ax.set_ylabel('FRP',fontsize=9)

    latitude = m11_df['LATITUDE'].values
    longitude = m11_df['LONGITUDE'].values
    FRP = m11_df['FRP'].values

    ax = fig.add_subplot(122)
    m_m11 = Basemap(llcrnrlon=-30,
                    llcrnrlat=-35,
                    urcrnrlon=60,
                    urcrnrlat=40,
                    resolution='i',
                    projection='tmerc',
                    lon_0=15,
                    lat_0=0,
                    ax=ax)
    #m_m11 = Basemap(llcrnrlon=28,llcrnrlat=8,urcrnrlon=32,urcrnrlat=10,
    #                                resolution='i',projection='tmerc',lon_0=30,lat_0=9,ax=ax)
    m_m11.drawcoastlines(linewidth=0.5)
    m_m11.drawmapboundary()
    #m.fillcontinents(lake_color='aqua',zorder=0)
    m_m11.drawparallels(np.arange(-35, 60., 20), labels=[True], fontsize=5)
    m_m11.drawmeridians(np.arange(-40., 100., 20), labels=[True])
    #m_m11.drawcountries(linewidth=0.25)
    # m_ice.shadedrelief()
    x, y = m_m11(longitude, latitude)
    sc = plt.scatter(x,
                     y,
                     c=FRP,
                     s=10,
                     alpha=0.8,
                     cmap='hot',
                     marker=',',
                     zorder=1,
                     norm=mpl.colors.SymLogNorm(linthresh=2, vmin=0,
                                                vmax=1000))
    plt.title('Meteosat-11', fontsize=9)
    plt.suptitle('FRP-PIXEL on ' + formated_dt, fontsize=12, y=0.09)
    #fig.subplots_adjust(right=0.8)
    rcParams['figure.subplot.wspace'] = 0.2  # more width between subplots
    #cb_ax = fig.add_axes([0, 800, 0,800])
    cb = m_m11.colorbar(sc, pad=0.001)  #location='bottom')
    cb.ax.tick_params(labelsize=8)
    #cb.ax.set_yticklabels([0,10,50,100,200,500,1000])         # need editting to be more case adaptive range
    cb.ax.set_ylabel('FRP (MW)', fontsize=9)
    #fig.tight_layout()
    plt.savefig('FRP_cluster_' + date_time, dpi=500)
    plt.close()
Beispiel #49
0
latt, lont, MCdivt = pp.grid_for_map(lat, lon, MCdiv)
latt, lont, Trdivt = pp.grid_for_map(lat, lon, Trdiv)
latt, lont, uvdht = pp.grid_for_map(lat, lon, uvdh)
latt, lont, wdht = pp.grid_for_map(lat, lon, wdh)
latt, lont, whbott = pp.grid_for_map(lat, lon, whbot)
latt, lont, whtopt = pp.grid_for_map(lat, lon, whtop)
latt, lont, vertdivt = pp.grid_for_map(lat, lon, vertdiv)
lons, lats = np.meshgrid(lont, latt)
x, y = m(lons, lats)
cmap = plt.cm.RdYlBu
#%%
plt.figure()
m.drawcoastlines()
m.drawcountries()
m.contourf(x, y, np.mean(nett, 0), clev, cmap=cmap, extend='both')
cb = m.colorbar(location='bottom', size='5%', pad='8%')
plt.tight_layout()
plt.figure()
m.drawcoastlines()
m.drawcountries()
m.contourf(x, y, np.mean(Totdivt + det, 0), clev, cmap=cmap, extend='both')
cb = m.colorbar(location='bottom', size='5%', pad='8%')
plt.tight_layout()
m.drawcoastlines()
m.drawcountries()
m.contourf(x,
           y,
           np.mean(Totdivt + vertdivt + det, 0),
           clev,
           cmap=cmap,
           extend='both')
                    llcrnrlon=rlon_0,
                    urcrnrlon=rlon_1,
                    resolution='c')
        m.drawcoastlines()
        m.drawparallels(
            np.arange(-10, 60, 20), labels=[1, 0, 0, 0],
            fontsize=9)  #labels=[left,right,top,bottom] #horizontal line
        m.drawmeridians(
            np.arange(80, 180, 20), labels=[0, 0, 0, 1],
            fontsize=9)  #labels=[left,right,top,bottom] #vertical line

        m.imshow(array, cmap=cmap, vmin=0, vmax=100)  #draw figure
        plt.title(fn_name, fontsize=9)

        cbar = m.colorbar(
            size="5%", pad=0.05,
            extend='max')  #pad=distance, extend='colorbar shape,,'
        cbar.ax.tick_params(labelsize=8)  #labelsize=colorbar font size
        cbar.set_label('Rainfall intensity(mm/hr)', fontsize=8,
                       ha='center')  #ha='label text position'
        #------------------
'''
        n=n+1

        #---PE FILE SUBPLOT---
        plt.subplot(6,2,n) #subplot(y,x,position)

        #---READ PE FILE---BINARY FILE!
        fb_name = 'CMORPH_V1.0_ADJ_8km-30min_'+i+hh
        pe = np.fromfile(pe_path+fb_name, dtype=np.float64).reshape(1649,4948)
Beispiel #51
0
#calculate session#
###################

NDVI = (B04 - B03) / (B04 + B03)
NDVI[NDVI < 0.2] = np.nan
B13[B13 < clearthreshold] = np.nan
#NDVI = np.ma.masked_invalid(np.atleast_2d(NDVI))
NDVI = np.ma.masked_where(np.isnan(NDVI), NDVI)
#NDVI = np.ma.masked_where(np.isnan(B13),NDVI)

print NDVI
###############
#plotting time#
###############

m = Basemap(resolution='l', projection='merc', \
llcrnrlon=90, llcrnrlat=-20, urcrnrlon=149, urcrnrlat=20) #for mercator

#draw map coastline, etc
m.drawcoastlines(linewidth=0.75)
m.drawcountries(linewidth=0.75)

#make our lon and lat 2D
lon1, lat1 = np.meshgrid(lon, lat)

#for NDVI
plt.title('NDVI')
cs = m.pcolormesh(lon1, lat1, np.squeeze(NDVI), cmap='coolwarm', latlon=True)
cbar = m.colorbar(cs, location='bottom', pad="10%")  #add color bar
plt.show()
Beispiel #52
0
              llcrnrlon=lon_min,
              urcrnrlon=lon_max,
              lat_ts=35,
              resolution='c')
# Construct a heatmap
lons = df_age.index.values
lats = df_age.columns.values
x, y = np.meshgrid(lons, lats)
px, py = m5a(x, y)
data_values = df_age.values
masked_data = np.ma.masked_invalid(data_values.T)
cmap = plt.cm.viridis
cmap.set_bad(color="#191919")
# Plot the heatmap
m5a.pcolormesh(px, py, masked_data, cmap=cmap, zorder=5)
m5a.colorbar().set_label("average age")
plt.title("Average age per grid area in Beijing")

# Plot count per grid
plt.subplot(122)
m5b = Basemap(projection='merc',
              llcrnrlat=lat_min,
              urcrnrlat=lat_max,
              llcrnrlon=lon_min,
              urcrnrlon=lon_max,
              lat_ts=35,
              resolution='c')
# Construct a heatmap
data_values = df_cnt.values
masked_data = np.ma.masked_invalid(data_values.T)
cmap = plt.cm.viridis
Beispiel #53
0
START_YEAR = 1950
LAST_YEAR = 2013

n_cities = 500
random_cities = city_means.sample(n_cities).index
year_text = plt.text(-170, 80, str(START_YEAR), fontsize=15)

temp_markers = get_temp_markers(random_cities, START_YEAR)
xs, ys = map(temp_markers['lon'], temp_markers['lat'])
scat = map.scatter(xs,
                   ys,
                   s=temp_markers['size'],
                   c=temp_markers['color'],
                   cmap=cmap,
                   marker='o',
                   alpha=0.3,
                   zorder=10)

ani = animation.FuncAnimation(fig,
                              update,
                              interval=500,
                              frames=LAST_YEAR - START_YEAR + 1)

cbar = map.colorbar(scat, location='bottom')
cbar.set_label(
    '0.0 -- min temperature record for the city   1.0 -- max temperature record for the city'
)
plt.title('Mean year temperatures for {} random cities'.format(n_cities))
plt.show()
ani.save('animation.gif', writer='imagemagick', fps=2)
Beispiel #54
0
m.drawcoastlines()
m.drawstates(), m.drawcountries()
cs = m.contourf(lon2,
                lat2,
                zhmean[3, :, :].T,
                clevs,
                cmap=zhcolor,
                extend='both')
cs2 = m.contour(lonhou.T,
                lathou.T,
                sig_rotation[:, :, 3],
                colors='k',
                linewidths=1.5)

m.drawcounties()
cbar = m.colorbar(cs, size='2%')
cbar.ax.set_ylabel('dBZ', weight='bold', name='Calibri', size=14)
cticks = []
for i in clevs:
    cticks.append(int(i)) if i.is_integer() else cticks.append(i)
    cbar.set_ticks(clevs[::4])
    cbar.set_ticklabels(cticks[::4])
for i in cbar.ax.yaxis.get_ticklabels():
    i.set_family('Calibri')
    i.set_size(14)

x2star, y2star = m(-95.3698, 29.7604)
m.plot(x2star, y2star, 'ro', markersize=7, color='k')
label = 'Houston'
plt.text(x2star + 0.05, y2star + 0.05, label)
Beispiel #55
0
              urcrnrlat=90,
              llcrnrlon=-180,
              urcrnrlon=180,
              resolution='c')
map.drawcoastlines()
map.drawcountries()
map.drawmapboundary()
x, y = map(lon, lat)
cs1 = map.pcolormesh(x, y, am3new1y, cmap=cmap, norm=norm)
#cs1 = map.pcolormesh(x,y,m3newp*10000/gridarea,cmap=plt.cm.Greens,norm=colors.PowerNorm(gamma=1./2.),vmin=0,vmax=9)
#cs1 = map.pcolormesh(x,y,m3newp/m3newa,cmap=plt.cm.gist_earth,vmin=0,vmax=10)
plt.axis('off')

cbar = map.colorbar(cs1,
                    location='bottom',
                    size="5%",
                    pad="2%",
                    ticks=bounds,
                    extend='max')
#cbar.ax.set_xticklabels(['0', '0.01', '0.05','0.1','0.5','1','2','3','4','5','6'])  # horizontal colorbar

cbar.ax.tick_params(labelsize=16)

ax1 = fig.add_subplot(222)
ax1.set_title("Maize ISAM (t grains / ha croparea)", fontsize=20)
map = Basemap(projection='cyl',
              llcrnrlat=-62,
              urcrnrlat=90,
              llcrnrlon=-180,
              urcrnrlon=180,
              resolution='c')
Beispiel #56
0
def test_ocean_plot():
    dirs = "../result_h/test/test_iw/"
    mkdir(dirs)

    start_list_plus_1month = start_list + [20170901]
    for i, start in enumerate(start_list):
        print("*******************  {}/{}  *******************".format(
            i + 1, M))
        month_end = start_list_plus_1month[i + 1]
        month_end = date(month_end // 10000, (month_end % 10000) // 100,
                         (month_end % 10000) % 100) - timedelta(days=1)
        end = start + month_end.day - 1

        try:
            #csv_Helmert_90の当該月のcsvを読み込む
            #hermert_file_name_90 = "../data/csv_Helmert_both_90/Helmert_both_90_" + str(start)[:6] + ".csv"
            #helmert_90_data = pd.read_csv(hermert_file_name_90)
            #csv_Helmert_30の当該月のcsvを読み込む
            hermert_file_name_30 = "../data/csv_Helmert_30/Helmert_30_" + str(
                start)[:6] + ".csv"
            helmert_30_data = pd.read_csv(hermert_file_name_30)
            #木村のcsvの読み込み(90)
            #coeff_file_name_90 = "../data/csv_A_90/ssc_amsr_ads" + str(start)[2:6] + "_90_fin.csv"
            #coeff_90_data = calc_data.get_1month_coeff_data(coeff_file_name_90)
            #木村のcsvの読み込み(30)
            coeff_file_name_30 = "../data/csv_A_30/ssc_amsr_ads" + str(
                start)[2:6] + "_30_fin.csv"
            coeff_30_data = calc_data.get_1month_coeff_data(coeff_file_name_30)
        except:
            continue
        #ocean_90_h_u = helmert_90_data["ocean_u_90"].values
        #ocean_90_h_v = helmert_90_data["ocean_v_90"].values
        #ocean_90_h_speed = np.sqrt(ocean_90_h_u**2 + ocean_90_h_v**2)
        ocean_30_h_u = helmert_30_data["ocean_u"].values
        ocean_30_h_v = helmert_30_data["ocean_v"].values
        ocean_30_h_speed = np.sqrt(ocean_30_h_u**2 + ocean_30_h_v**2)
        #ocean_90_c_u = coeff_90_data["mean_ocean_u"].values
        #ocean_90_c_v = coeff_90_data["mean_ocean_v"].values
        #ocean_90_c_speed = np.sqrt(ocean_90_c_u**2 + ocean_90_c_v**2)
        ocean_30_c_u = coeff_30_data["mean_ocean_u"].values
        ocean_30_c_v = coeff_30_data["mean_ocean_v"].values
        ocean_30_c_speed = np.sqrt(ocean_30_c_u**2 + ocean_30_c_v**2)
        """
		fig, axes = plt.subplots(1, 2)
		ratio_90 = ocean_90_c_speed/ocean_90_h_speed
		ratio_30 = ocean_30_c_speed/ocean_30_h_speed
		axes[0].hist(ratio_30[ocean_idx][~np.isnan(ratio_30[ocean_idx])], range=(0,3), bins=150)
		axes[1].hist(ratio_90[ocean_idx][~np.isnan(ratio_90[ocean_idx])], range=(0,3), bins=150)
		"""
        ratio_w = ocean_30_c_u / ocean_30_h_u

        N_c_h = helmert_30_data["mean_iw_v"].values
        N_c_c = coeff_30_data["mean_ice_v"].values
        N_c_diff = N_c_h - N_c_c
        #plt.hist(N_c_diff[~np.isnan(N_c_diff)], range=(-5,5), bins=11, alpha=0.5)
        #tmp = N_c_diff[~np.isnan(N_c_diff)]
        #print(len(np.where(tmp>0)[0]))

        m = Basemap(lon_0=180,
                    boundinglat=50,
                    resolution='l',
                    projection='npstere')
        m.drawcoastlines(color='0.15')
        m.fillcontinents(color='#555555')
        lon = np.array(latlon_ex.Lon)
        lat = np.array(latlon_ex.Lat)
        x, y = m(lon, lat)
        x1 = np.reshape(x, (145, 145), order='F')
        y1 = np.reshape(y, (145, 145), order='F')
        dx1 = (x1[1, 0] - x1[0, 0]) / 2
        dy1 = (y1[0, 1] - y1[0, 0]) / 2
        x2 = np.linspace(x1[0, 0], x1[144, 0], 145)
        y2 = np.linspace(y1[0, 0], y1[0, 144], 145)
        xx, yy = np.meshgrid(x2, y2)
        xx, yy = xx.T, yy.T
        xx = np.hstack([xx, xx[:, 0].reshape(145, 1)])
        xx_ex = np.vstack([xx, (xx[144, :] + (xx[1, 0] - xx[0, 0]))])
        yy = np.vstack([yy, yy[0, :]])
        yy_ex = np.hstack([(yy[:, 0].reshape(146, 1) + (yy[0, 0] - yy[0, 1])),
                           yy])

        data = np.ma.masked_invalid(N_c_diff)
        data1 = np.reshape(data, (145, 145), order='F')
        m.pcolormesh(xx_ex - dx1,
                     yy_ex + dy1,
                     data1,
                     cmap=plt.cm.jet,
                     vmax=0.5,
                     vmin=-0.5)
        #fig.colorbar(im, ax=ax)
        m.colorbar()

        #plt.hist(N_c_c[~np.isnan(N_c_c)], range=(20,35), bins=16)
        plt.savefig(dirs + "iw_v_" + str(start)[:6] + ".png", dpi=450)
        plt.close()
Beispiel #57
0
              urcrnrlat=latlon[3],
              resolution='i')
x, y = map(lons_prism, lats_prism)
totalprecip = maskoceans(lons_prism, lats_prism, totalprecip)
#map.drawlsmask(land_color=(0, 0, 0, 0), ocean_color='deeppink', lakes=False)
csAVG = map.contourf(x,
                     y,
                     totalprecip,
                     levels,
                     cmap=cmap,
                     norm=matplotlib.colors.BoundaryNorm(levels, cmap.N))
map.drawcoastlines(linewidth=.5)
map.drawstates()
map.drawcountries()

cbar = map.colorbar(csAVG, location='bottom', pad="5%")
cbar.ax.tick_params(labelsize=12)
plt.title('NCAR Ensemble Control', fontsize=18)
#cbar.ax.set_xlabel('Mean Daily Precipitation from Oct. 2015 to Mar. 2016 (mm)', fontsize = 10)

########################   prism   #############################################
ax = fig.add_subplot(232)
map = Basemap(projection='merc',
              llcrnrlon=latlon[0],
              llcrnrlat=latlon[1],
              urcrnrlon=latlon[2],
              urcrnrlat=latlon[3],
              resolution='i')

x, y = map(lons_prism, lats_prism)
precip_tot = maskoceans(lons_prism, lats_prism, precip_tot)
Beispiel #58
0
def run(FILE_NAME):
    GEO_FILE_NAME = 'MYD03.A2002226.0000.005.2009193071127.hdf'
    GEO_FILE_NAME = os.path.join(os.environ['HDFEOS_ZOO_DIR'], GEO_FILE_NAME)
    DATAFIELD_NAME = 'EV_1KM_Emissive'

    if USE_NETCDF4:
        from netCDF4 import Dataset
        nc = Dataset(FILE_NAME)

        # Just read the first level, Band 20.
        # lat/lon resolution.
        data = nc.variables[DATAFIELD_NAME][0, :, :].astype(np.float64)

        # Retrieve the geolocation data from MYD03 product.
        nc_geo = Dataset(GEO_FILE_NAME)
        longitude = nc_geo.variables['Longitude'][:]
        latitude = nc_geo.variables['Latitude'][:]

        # Retrieve attributes.
        units = nc.variables[DATAFIELD_NAME].radiance_units
        long_name = nc.variables[DATAFIELD_NAME].long_name

        # The scale and offset attributes do not have standard names in this
        # case, so we have to apply the scaling equation ourselves.
        scale_factor = nc.variables[DATAFIELD_NAME].radiance_scales[0]
        add_offset = nc.variables[DATAFIELD_NAME].radiance_offsets[0]
        valid_range = nc.variables[DATAFIELD_NAME].valid_range
        _FillValue = nc.variables[DATAFIELD_NAME]._FillValue
        valid_min = valid_range[0]
        valid_max = valid_range[1]

        # Retrieve dimension name.
        dimname = nc.variables[DATAFIELD_NAME].dimensions[0]

    else:
        from pyhdf.SD import SD, SDC
        hdf = SD(FILE_NAME, SDC.READ)

        # Read dataset.
        data3D = hdf.select(DATAFIELD_NAME)
        data = data3D[0, :, :].astype(np.double)

        hdf_geo = SD(GEO_FILE_NAME, SDC.READ)

        # Read geolocation dataset from MOD03 product.
        lat = hdf_geo.select('Latitude')
        latitude = lat[:, :]
        lon = hdf_geo.select('Longitude')
        longitude = lon[:, :]

        # Retrieve attributes.
        attrs = data3D.attributes(full=1)
        lna = attrs["long_name"]
        long_name = lna[0]
        aoa = attrs["radiance_offsets"]
        add_offset = aoa[0][0]
        fva = attrs["_FillValue"]
        _FillValue = fva[0]
        sfa = attrs["radiance_scales"]
        scale_factor = sfa[0][0]
        vra = attrs["valid_range"]
        valid_min = vra[0][0]
        valid_max = vra[0][1]
        ua = attrs["radiance_units"]
        units = ua[0]

        # Retrieve dimension name.
        dim = data3D.dim(0)
        dimname = dim.info()[0]

    invalid = np.logical_or(data > valid_max, data < valid_min)
    invalid = np.logical_or(invalid, data == _FillValue)
    data[invalid] = np.nan
    data = (data - add_offset) * scale_factor
    data = np.ma.masked_array(data, np.isnan(data))

    # The data is close to the equator in Africa, so a global projection is
    # not needed.
    m = Basemap(projection='cyl',
                resolution='l',
                llcrnrlat=-5,
                urcrnrlat=30,
                llcrnrlon=5,
                urcrnrlon=45)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(0, 50, 10), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(0, 50., 10), labels=[0, 0, 0, 1])
    m.pcolormesh(longitude, latitude, data, latlon=True)
    cb = m.colorbar()
    cb.set_label(units, fontsize=8)

    basename = os.path.basename(FILE_NAME)
    plt.title('{0}\n{1}\nat {2}=0'.format(basename,
                                          'Radiance derived from ' + long_name,
                                          dimname),
              fontsize=11)
    fig = plt.gcf()
    # plt.show()
    pngfile = "{0}.py.png".format(basename)
    fig.savefig(pngfile)
Beispiel #59
0
def get_temp(lat, lon, elev):
    day = datetime.date(2020, 2, 1)
    df = spark.createDataFrame(
        [('STATION', day, float(lat), float(lon), float(elev), 1.1)],
        tmax_schema)
    predictions = model.transform(df)
    result = predictions.select("prediction").collect()
    temp = result[0]['prediction']
    return temp


def get_temps(latlonelevs):
    return [get_temp(lat, lon, elev) for lat, lon, elev in latlonelevs]


fig = plt.figure(num=None, figsize=(16, 10))
m = Basemap(projection='cyl', resolution='c', lat_0=0, lon_0=0)
m.drawcoastlines()
lats, lons = np.meshgrid(np.arange(-90, 90, .5), np.arange(-180, 180, .5))
elevs = [
    eg.get_elevations(np.array([lat, lon]).T) for lat, lon in zip(lats, lons)
]
temps = [
    get_temps(np.array([lat, lon, elev]).T)
    for lat, lon, elev in zip(lats, lons, elevs)
]
print(temps)
cs = m.pcolormesh(lons, lats, temps, cmap='jet')
m.colorbar(cs)
plt.title("Eckert IV Projection")
plt.savefig('2a.png')
Beispiel #60
0
ax1 = fig.add_subplot(221)
ax1.set_title("CLM yield difference 2010s (t/ha)",fontsize=18)

map = Basemap(projection ='cyl', llcrnrlat=-65, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c')
x,y = map(lon2,lat2)

map.drawcoastlines()
map.drawcountries()
map.drawmapboundary()
clmhis= ma.masked_where(clmhis<=0.,clmhis)
clmhis1= ma.masked_where(clmhis1<=0.,clmhis1)
cc=clmhis1-clmhis
cc= ma.masked_where(cc==0.,cc)

cs = map.pcolormesh(x,y,cc,cmap=plt.cm.bwr,vmin=-1,vmax=1)
cbar = map.colorbar(cs,location='bottom',size="4%",pad="2%")
cbar.ax.tick_params(labelsize=12) 
plt.axis('off')

ax2 = fig.add_subplot(222)
ax2.set_title("ISAM CWP relative change 2010s (%)",fontsize=18)
map = Basemap(projection ='cyl', llcrnrlat=-65, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c')
map.drawcoastlines()
map.drawcountries()
map.drawmapboundary()
yield_new= ma.masked_where(yield_new<=0.,yield_new)
yield_new1= ma.masked_where(yield_new1<=0.,yield_new1)
cisa=(yield_new1/yield_new1et)-(yield_new/yield_newet)
cisa= ma.masked_where(cisa==0.,cisa)