Example #1
0
def lambert_conformal(request):
    import matplotlib
    from mpl_toolkits.basemap import Basemap
    import numpy as np
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    
    width = float(request.GET.get('width', 6000000))
    height = float(request.GET.get('height', 4500000))
    lat = float(request.GET.get('lat',-7))
    lon = float(request.GET.get('lon',107))
    true_lat1 = float(request.GET.get('true_lat1',5))
    true_lat2 = float(request.GET.get('true_lat2',5))
    
    m = Basemap(width=width,height=height,
            rsphere=(6378137.00,6356752.3142),\
            resolution=None,projection='lcc',\
            lat_1=true_lat1,lat_2=true_lat2,lat_0=lat,lon_0=lon)
    
    fig = Figure()
    canvas = FigureCanvas(fig)
    m.ax = fig.add_axes([0, 0, 1, 1])
    
    m.drawlsmask(land_color='gray',ocean_color='white',lakes=True)
    m.drawparallels(np.arange(-90.,91.,30.), color='black')
    m.drawmeridians(np.arange(-180.,181.,60.), color='black')
    
    x, y = m(lon, lat)
    m.plot(x, y, 'ro')
    
    response = HttpResponse(content_type='image/png')
    canvas.print_figure(response, dpi=100)
    return response
Example #2
0
def show_feature(feature):
    fig, ax = plt.subplots(figsize=(12, 12))
    map = Basemap(projection='merc',
                  llcrnrlat=-80,
                  urcrnrlat=80,
                  llcrnrlon=-180,
                  urcrnrlon=180,
                  resolution='l')

    land_color = 'lightgray'
    water_color = 'lightblue'

    map.fillcontinents(color=land_color, lake_color=water_color)
    map.drawcoastlines()
    map.drawparallels(np.arange(-90., 120., 30.))
    map.drawmeridians(np.arange(0., 420., 60.))
    map.drawmapboundary(fill_color=water_color)
    try:
        ax.set_title(feature['properties']['name'])
    except KeyError:
        pass

    plot_feature(map, feature)

    map.ax = ax

    plt.show()
    return map
Example #3
0
def animator(i):
    print i
    ax.cla()

    # create basemap
    map = Basemap(projection='cyl',
                  llcrnrlat=-90,
                  urcrnrlat=90,
                  llcrnrlon=-180,
                  urcrnrlon=180,
                  resolution='c')
    map.ax = ax
    mcoa = map.drawcoastlines(linewidth=0.25)
    mcou = map.drawcountries(linewidth=0.25)
    #add extra stripe of data to complete sphere

    for site_ref in valid_refs:
        site_group = root_grp.groups[site_ref]
        obs_cut = site_group.variables[species.lower()][i]
        obs_lat = site_group.latitude
        obs_lon = site_group.longitude
        obs_group = site_group.process_group

        if obs_cut != -99999:
            x, y = np.meshgrid(*map(obs_lon, obs_lat))
            map.scatter(x, y, c=obs_cut, s=35, cmap=cmap, norm=cnorm)

    ax.set_title('MONTHLY %s %s %s' % (species, full_dates[i], full_times[i]),
                 fontsize=26)
Example #4
0
def draw_marker_on_map(lat, lon, fname, fmt='png', location_name=' ', gridshape=(1, 1)):
    '''
    Purpose::
        Draw a marker on a map

    Input::
        lat - latitude for plotting a marker
        lon - longitude for plotting a marker
        fname  - a string specifying the filename of the plot
    '''
    fig = plt.figure()
    fig.dpi = 300
    ax = fig.add_subplot(111)

    m = Basemap(projection='cyl', resolution='c', llcrnrlat=lat -
                30, urcrnrlat=lat + 30, llcrnrlon=lon - 60, urcrnrlon=lon + 60)
    m.drawcoastlines(linewidth=1)
    m.drawcountries(linewidth=1)
    m.drawmapboundary(fill_color='aqua')
    m.fillcontinents(color='coral', lake_color='aqua')
    m.ax = ax

    xpt, ypt = m(lon, lat)
    m.plot(xpt, ypt, 'bo')  # plot a blue dot there
    # put some text next to the dot, offset a little bit
    # (the offset is in map projection coordinates)
    plt.text(xpt + 0.5, ypt + 1.5, location_name +
             '\n(lon: %5.1f, lat: %3.1f)' % (lon, lat))

    fig.savefig('%s.%s' % (fname, fmt), bbox_inches='tight', dpi=fig.dpi)
    fig.clf()
def prepare_map0(coordinates, res):
    m = Basemap(llcrnrlon=coordinates[0], llcrnrlat=coordinates[2],
                urcrnrlon=coordinates[1], urcrnrlat=coordinates[3], resolution=res)
    fig = plt.figure()
    ax = plt.subplot(111)
    m.ax = ax
    return fig, m, ax
Example #6
0
def animator(i):
    print i
    ax.cla()
    
    # create basemap
    map = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,llcrnrlon=-180,urcrnrlon=180,resolution='c')
    map.ax = ax
    mcoa = map.drawcoastlines(linewidth=0.25)
    mcou = map.drawcountries(linewidth=0.25)

    obs_cut = obs_data[:,i]
    valid = obs_cut != -99999
    obs_lats_cut = obs_lats[valid]
    obs_lons_cut = obs_lons[valid]
    obs_color_ratios_cut = obs_color_ratios[valid]
        
    for j in range(len(obs_lats_cut)):
        x, y = np.meshgrid(*map(obs_lons_cut[j], obs_lats_cut[j]))
        map.scatter(x, y, c=cm(obs_color_ratios_cut[j]),s=35)
        
    for x in range(len(areas)):
        map.plot([-999],[-999],color=cm(area_color_ratios[x]),marker='o',markersize=9,label=areas[x])
          
    l = plt.legend(prop={'size':9},loc=(0.05,0.02))          
    ax.set_title('HOURLY %s AREAS %s %s'%(species,full_dates[i],full_times[i]),fontsize=26)
Example #7
0
def prepare_map(coordinates,res):
    m = Basemap(projection='merc',llcrnrlon=coordinates[0],llcrnrlat=coordinates[2],urcrnrlon=coordinates[1],urcrnrlat=coordinates[3],  \
            lat_ts=0.5*(coordinates[2]+coordinates[3]),resolution=res)
    fig=plt.figure() 
    ax = plt.subplot(111)
    m.ax=ax
    return fig, m, ax
Example #8
0
def test_plot(request):
    import matplotlib
    from mpl_toolkits.basemap import Basemap
    import numpy as np
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    
    # llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon
    # are the lat/lon values of the lower left and upper right corners
    # of the map.
    # lat_ts is the latitude of true scale.
    # resolution = 'c' means use crude resolution coastlines.
    
#    #mercator
#    m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='c')
    

    m = Basemap(width=36000000,height=27000000,rsphere=(6378137.00,6356752.3142),
                resolution='l',area_thresh=1000.,projection='lcc',
                lat_1=30.,lat_0=0.,lon_0=0.)
    
    fig = Figure()
    canvas = FigureCanvas(fig)
    m.ax = fig.add_axes([0, 0, 1, 1])
    
#    m.bluemarble(scale=0.5)
    m.drawcoastlines()
    m.drawmapboundary(fill_color='aqua') 
    m.fillcontinents(color='coral',lake_color='aqua')
    m.drawparallels(np.arange(-90.,91.,30.))
    m.drawmeridians(np.arange(-180.,181.,60.))
    
    response = HttpResponse(content_type='image/png')
    canvas.print_figure(response, dpi=100)
    return response
Example #9
0
def map_plot(axis, area='EuropeOdyssey00', fill_color='black'):
    if area == 'EuropeOdyssey00':
        m = Basemap(projection='geos',
                    lon_0=0,
                    resolution='l',
                    llcrnrx=-1215000,
                    llcrnry=3585000,
                    urcrnrx=1780000,
                    urcrnry=5273000)
    if area == 'EuropeOdyssey95':
        m = Basemap(projection='geos',
                    lon_0=9.5,
                    resolution='l',
                    llcrnrx=-1250000,
                    llcrnry=3753000,
                    urcrnrx=1365000,
                    urcrnry=5250000)

    m.ax = axis
    m.drawcoastlines()
    m.drawcountries()
    m.drawparallels(np.arange(40, 71, 10), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-20, 61, 10), labels=[0, 0, 0, 1])
    m.drawmapboundary(fill_color=fill_color)
    m.ax.set_axis_bgcolor('black')

    return (m)
def main():

    ncols = 841
    nrows = 681
    ndays = 366

    f = open("modis_climatology_splined.bin", "r")
    data = np.fromfile(f).reshape((ndays,nrows,ncols))
    f.close()

    ncolours = 7
    vmin = 0
    vmax = 6

    cmap = sns.blend_palette(["white", "#1b7837"], ncolours, as_cmap=True)
    sns.set(style="white")

    fig = plt.figure(figsize=(10, 6))
    grid = AxesGrid(fig, [0.05,0.05,0.9,0.9], nrows_ncols=(1,1), axes_pad=0.1,
    		        cbar_mode='single', cbar_pad=0.4, cbar_size="7%",
		            cbar_location='bottom', share_all=True)
	# 111.975 + (841. * 0.05)
    # -44.025 + (681. * 0.05)
    m = Basemap(projection='cyl', llcrnrlon=111.975, llcrnrlat=-44.025, \
                urcrnrlon=154.025, urcrnrlat=-9.974999999999994, resolution='h')


    ax = grid[0]
    m.ax = ax


    shp_info = m.readshapefile('/Users/mdekauwe/research/Drought_linkage/'
                               'Bios2_SWC_1979_2013/'
                               'AUS_shape/STE11aAust',
                               'STE11aAust', drawbounds=True)


    #m.drawrivers(linewidth=0.5, color='k')

    ax.set_xlim(140.5, 154)
    ax.set_ylim(-38, -28)

    #cmap = cmap_discretize(plt.cm.YlGnBu, ncolours)

    m.imshow(data[20,:,:], cmap,
             colors.Normalize(vmin=vmin, vmax=vmax, clip=True),
             origin='upper', interpolation='nearest')


    cbar = colorbar_index(cax=grid.cbar_axes[0], ncolours=ncolours, cmap=cmap,
                          orientation='horizontal', vmin=vmin, vmax=vmax)

    fig.savefig("/Users/mdekauwe/Desktop/LAI_NSW.png", bbox_inches='tight',
                pad_inches=0.1, dpi=300)



    plt.show()
Example #11
0
def make_map(survey, llcrnrlon=12.8, urcrnrlon=17.5, llcrnrlat=66.2, urcrnrlat=69,
             projection='merc', resolution='f', figsize=(6, 6), inset=True):
    if survey == "Soerfjorden":
        mmap = Basemap(llcrnrlon=6.4, urcrnrlon=6.85, llcrnrlat=60, urcrnrlat=60.2, projection=projection,
                       resolution=resolution)
        meridians = np.arange(6.3, 6.7, 0.1)
        parallels = np.arange(60.1, 60.5, 0.1)
    elif survey == "Hardangerfjorden":
        mmap = Basemap(llcrnrlon=5.0, urcrnrlon=6.2, llcrnrlat=60.5, urcrnrlat=61.5, projection=projection,
                       resolution=resolution)
        meridians = np.arange(5.0, 6.7, 0.1)
        parallels = np.arange(60.1, 61.5, 0.1)
    elif survey == "Sognefjorden":
        mmap = Basemap(llcrnrlon=6.0, urcrnrlon=6.85, llcrnrlat=59.7, urcrnrlat=60.2, projection=projection,
                       resolution=resolution)
        meridians = np.arange(6.0, 6.7, 0.1)
        parallels = np.arange(60.1, 60.5, 0.1)
    else:
        mmap = Basemap(llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon,
                       llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat,
                       projection=projection, resolution=resolution)
        meridians = np.arange(llcrnrlon, urcrnrlon + 0.5, 0.5)
        parallels = np.arange(llcrnrlat, urcrnrlat + 0.5, 0.5)

    fig, ax = plt.subplots(figsize=figsize)
    mmap.drawstates()
    mmap.drawcoastlines()
    mmap.fillcontinents(color='0.85')

    mmap.drawparallels(parallels, linewidth=0, labels=[1, 0, 0, 0],fontsize=9)
    mmap.drawmeridians(meridians, linewidth=0, labels=[0, 0, 0, 1],fontsize=9, rotation=45)
    mmap.ax = ax

    if inset:
        axins = inset_axes(mmap.ax, width="40%", height="40%", loc=4)
      #  axins.set_xlim(-40, 60) # longitude boundaries of inset map
      #  axins.set_ylim(30, 85) #
        
        # Global inset map.
        if survey == "Soerfjorden":
            inmap = Basemap(llcrnrlon=4.0, urcrnrlon=8, llcrnrlat=59, urcrnrlat=62, projection=projection,
                           resolution=resolution, ax=axins, anchor='NE')
        elif survey == "MON":
            inmap = Basemap(llcrnrlon=4, urcrnrlon=30,
                       llcrnrlat=60, urcrnrlat=72,
                       projection=projection, ax=axins, resolution='i')
        else:
            inmap = Basemap(lon_0=np.mean(mmap.boundarylons),
                        lat_0=np.mean(mmap.boundarylats),
                        projection='ortho', ax=axins, anchor='NE')
      
        inmap.drawcountries(color='white')
        inmap.fillcontinents(color='gray')
        bx, by = inmap(mmap.boundarylons, mmap.boundarylats)
        xy = list(zip(bx, by))
        mapboundary = Polygon(xy, edgecolor='r', linewidth=1, fill=False)
        inmap.ax.add_patch(mapboundary)
    return fig, mmap
def plot_eq_displacements(LLD_FILE, LEVELS, save_file):
    # Read displacement data
    disp_data = np.genfromtxt(LLD_FILE, dtype=[('lat','f8'),('lon','f8'), ('z','f8')],skip_header=3)

    # Data ranges
    lon_min,lon_max = disp_data['lon'].min(),disp_data['lon'].max()
    lat_min,lat_max = disp_data['lat'].min(),disp_data['lat'].max()
    mean_lat = 0.5*(lat_min + lat_max)
    mean_lon = 0.5*(lon_min + lon_max)
    lon_range = lon_max - lon_min
    lat_range = lat_max - lat_min
    z_min,z_max = disp_data['z'].min(),disp_data['z'].max()
    z_lim = max(np.abs(z_min),np.abs(z_max))
    cmap = plt.get_cmap('seismic')
    norm = mcolor.Normalize(vmin=-z_lim, vmax=z_lim)
    interp = 'cubic'
    landcolor = '#FFFFCC'
    framelabelfont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=14)

    # Initialize the frame and axes
    fig = plt.figure()
    
    m = Basemap(projection='cyl',llcrnrlat=lat_min, urcrnrlat=lat_max,
                llcrnrlon=lon_min, urcrnrlon=lon_max, lat_0=mean_lat, lon_0=mean_lon, resolution='h')
    m.ax = fig.add_subplot(111)
    
    m.drawmeridians(np.linspace(lon_min,lon_max,num=5.0),labels=[0,0,0,1], linewidth=0)
    m.drawparallels(np.linspace(lat_min,lat_max,num=5.0),labels=[1,0,0,0], linewidth=0)
    m.drawcoastlines(linewidth=0.5)
    m.fillcontinents(color=landcolor, zorder=0)

    # Colorbar
    divider = make_axes_locatable(m.ax)
    cbar_ax = divider.append_axes("right", size="5%",pad=0.05)
    plt.figtext(0.96, 0.7, r'displacement $[m]$', rotation='vertical', fontproperties=framelabelfont)
    cb = mcolorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=norm)

    # Reshape into matrices
    Ncols = len(np.unique(disp_data['lon']))
    Nrows = len(np.unique(disp_data['lat']))
    
    X = disp_data['lon'].reshape(Nrows, Ncols)
    Y = disp_data['lat'].reshape(Nrows, Ncols)
    Z = disp_data['z'].reshape(Nrows, Ncols)
    
    # Masked array via conditional, don't color the land unless it has water on it
    zero_below = int(len(LEVELS)/2)-1
    zero_above = zero_below+1
    masked_data = np.ma.masked_where(np.logical_and(np.array(Z <= LEVELS[zero_above]),np.array(Z >= LEVELS[zero_below])), Z)
    
    # Set masked pixels to the land color
    cmap.set_bad(landcolor, 0.0)  # set alpha=0.0 for transparent
    
    # Plot the contours
    m.contourf(X, Y, masked_data, LEVELS, cmap=cmap, norm=norm, extend='both', zorder=1)

    plt.savefig(save_file,dpi=100)
    print("Saved to "+save_file)
Example #13
0
def prepare_map0(coordinates, res):
    m = Basemap(llcrnrlon=coordinates[0],
                llcrnrlat=coordinates[2],
                urcrnrlon=coordinates[1],
                urcrnrlat=coordinates[3],
                resolution=res)
    fig = plt.figure()
    ax = plt.subplot(111)
    m.ax = ax
    return fig, m, ax
def bathy_topo_map(LLD_FILE, save_file):
    # Read bathymetry/topography data
    data = np.genfromtxt(LLD_FILE, dtype=[('lat','f8'),('lon','f8'), ('z','f8')],skip_header=3)

    # Data ranges
    lon_min,lon_max = data['lon'].min(),data['lon'].max()
    lat_min,lat_max = data['lat'].min(),data['lat'].max()
    mean_lat = 0.5*(lat_min + lat_max)
    mean_lon = 0.5*(lon_min + lon_max)
    lon_range = lon_max - lon_min
    lat_range = lat_max - lat_min
    cmap = plt.get_cmap('terrain')
    interp = 'none'
    framelabelfont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=14)
    
    # Reshape into matrices
    Ncols = len(np.unique(data['lon']))
    Nrows = len(np.unique(data['lat']))
    
    X = data['lon'].reshape(Nrows, Ncols)
    Y = data['lat'].reshape(Nrows, Ncols)
    Z = data['z'].reshape(Nrows, Ncols)
        
    # catch any nan values
    masked_data = np.ma.masked_invalid(Z)
    cmap.set_bad('red')
    
    # Color limits
    z_min,z_max = masked_data.min(),masked_data.max()
    z_lim = max(np.abs(z_min),np.abs(z_max))
    norm = mcolor.Normalize(vmin=-z_lim, vmax=z_lim)

    # Initialize the frame and axes
    fig = plt.figure()
    
    m = Basemap(projection='cyl',llcrnrlat=lat_min, urcrnrlat=lat_max,
                llcrnrlon=lon_min, urcrnrlon=lon_max, lat_0=mean_lat, lon_0=mean_lon, resolution='h')
    m.ax = fig.add_subplot(111)
    
    m.drawmeridians(np.linspace(lon_min,lon_max,num=5.0),labels=[0,0,0,1], linewidth=0)
    m.drawparallels(np.linspace(lat_min,lat_max,num=5.0),labels=[1,0,0,0], linewidth=0)
    m.drawcoastlines(linewidth=0.5)

    # Colorbar
    divider = make_axes_locatable(m.ax)
    cbar_ax = divider.append_axes("right", size="5%",pad=0.05)
    plt.figtext(0.96, 0.7, r'elevation $[m]$', rotation='vertical', fontproperties=framelabelfont)
    cb = mcolorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=norm)    
        
    # Plot the contours
    #m.contourf(X, Y, masked_data, 100, cmap=cmap, norm=norm, extend='both', zorder=1)
    m.ax.imshow(masked_data,cmap=cmap,origin='lower',norm=norm,extent=[lon_min,lon_max,lat_max,lat_min],interpolation=interp)

    plt.savefig(save_file,dpi=100)
    print("Saved to "+save_file)
def make_map(llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat, image):
    fig, ax = plt.subplots()
    m = Basemap(llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon,
                llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat,
                resolution='c', projection='merc',
                lon_0=(urcrnrlon + llcrnrlon) / 2,
                lat_0=(urcrnrlat + llcrnrlat) / 2,
                lat_ts=-23.5)
    m.ax = ax
    m.imshow(plt.imread(image), origin='upper', zorder=1)
    return fig, ax, m
Example #16
0
def make_map():
    fig, ax = plt.subplots()
    m = Basemap(projection='merc',
                llcrnrlat=-35,
                urcrnrlat=7,
                llcrnrlon=-77,
                urcrnrlon=-32,
                resolution='i')
    m.ax = ax
    m.fillcontinents()
    return fig, m
def prepare_map(coordinates, res):
    m = Basemap(projection='merc',
                llcrnrlon=coordinates[0],
                llcrnrlat=coordinates[2],
                urcrnrlon=coordinates[1],
                urcrnrlat=coordinates[3],
                lat_ts=0.5 * (coordinates[2] + coordinates[3]),
                resolution=res)
    fig = plt.figure()
    ax = plt.subplot(111)
    m.ax = ax
    return fig, m, ax
Example #18
0
def create_projected_fig(lonmin, latmin, lonmax, latmax, projection, height, width):
    from mpl_toolkits.basemap import Basemap
    from matplotlib.figure import Figure
    fig = Figure(dpi=80, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height)
    fig.set_figwidth(width)
    m = Basemap(llcrnrlon=lonmin, llcrnrlat=latmin,
            urcrnrlon=lonmax, urcrnrlat=latmax, projection=projection,
            resolution=None,
            lat_ts = 0.0,
            suppress_ticks=True)
    m.ax = fig.add_axes([0, 0, 1, 1], xticks=[], yticks=[])
    return fig, m
def make_map(llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat, image):
    fig, ax = plt.subplots()
    m = Basemap(llcrnrlon=llcrnrlon,
                urcrnrlon=urcrnrlon,
                llcrnrlat=llcrnrlat,
                urcrnrlat=urcrnrlat,
                resolution='c',
                projection='merc',
                lon_0=(urcrnrlon + llcrnrlon) / 2,
                lat_0=(urcrnrlat + llcrnrlat) / 2,
                lat_ts=-23.5)
    m.ax = ax
    m.imshow(plt.imread(image), origin='upper', zorder=1)
    return fig, ax, m
Example #20
0
def drawstates():
    shapefile = '/home/daniel/Desktop/tcc/shapeSP/shapeestado'
    m = Basemap(projection='merc',
                llcrnrlat=-40,
                urcrnrlat=5,
                llcrnrlon=-80,
                urcrnrlon=-20,
                resolution='l')
    m.fillcontinents()
    m.drawcountries()
    shp = m.readshapefile(shapefile, 'states', drawbounds=True)
    for info, shape in zip(m.states_info, m.states):
        x, y = zip(*shape)
        ax1f1.plot(x, y, marker=None, color='m')
    m.ax = ax1f1
Example #21
0
	def xyPlotCatsMap(self, doShow=True, doSave=False, saveName='catalogPlot.png', epicenter=None, legendLoc='upper left'):
		
		if epicenter==None: epicenter=[self.tLon, self.tLat]
		fcat=[]
		scat=[]
		for rw in self.shockCat:
			scat+=[rw[0:4]]
		for rw in self.fullCat:
			if rw not in scat: fcat+=[rw]
		#return [scat, fcat]
	
		f0=plt.figure(0)	
		plt.clf()
		#		
		#set up map:
		llr=self.getLatLonRange()	# latLonRange
		cntr=[float(llr[0][0])+(llr[1][0]-float(llr[0][0]))/2.0, float(llr[0][1])+(llr[1][1]-float(llr[0][1]))/2.0]
		catmap=Basemap(llcrnrlon=llr[0][1], llcrnrlat=llr[0][0], urcrnrlon=llr[1][1], urcrnrlat=llr[1][0], resolution ='l', projection='tmerc', lon_0=cntr[1], lat_0=cntr[0])
		canvas=FigureCanvas(f0)
		catmap.ax=f0.add_axes([0,0,1,1])
		f0.set_figsize_inches((8/catmap.aspect,8.))
		#
		catmap.drawcoastlines(color='gray')
		catmap.drawcountries(color='gray')
		catmap.fillcontinents(color='beige')
		xfull, yfull=catmap(list(map(operator.itemgetter(2), fcat)), list(map(operator.itemgetter(1), fcat)))
		xshock, yshock=catmap(list(map(operator.itemgetter(2), scat)), list(map(operator.itemgetter(1), scat)))
		epx, epy=catmap(epicenter[0], epicenter[1])
		catmap.plot(xfull, yfull, 'g+', label='Full Catalog')
		catmap.plot(xshock, yshock, 'b.', label='Aftershock zone')
		catmap.plot(epx, epy, 'ro')
		
		canvas.print_figure(saveName)
		
		#
		#ax=plt.gca()
		el = Ellipse((self.tLon, self.tLat), 2.0*self.tA, 2.0*self.tB, -self.tTheta, facecolor='b', alpha=0.4)
		#catmap.ax.add_artist(el)
		#ax.add_artist(el)
		#
		#plt.plot(map(operator.itemgetter(2), self.fullCat), map(operator.itemgetter(1), self.fullCat), '+')
		#plt.plot(map(operator.itemgetter(2), self.shockCat), map(operator.itemgetter(1), self.shockCat), '.')
		#plt.plot(map(operator.itemgetter(2), fcat), map(operator.itemgetter(1), fcat), '+', label='Full Catalog')
		#plt.plot(map(operator.itemgetter(2), scat), map(operator.itemgetter(1), scat), '.', label='Aftershock zone')
		#plt.plot([epicenter[0]], [epicenter[1]], 'ro', label='epicenter')
		plt.legend(loc=legendLoc, numpoints=1)
		if doSave: plt.savefig(saveName)
		if doShow: plt.show()
Example #22
0
def build_map(show, proj, minLat, maxLat, minLon, maxLon, res, fig, ax, pos_num, labels_in):
    t0 = time.time()
    if proj in ['cyl', 'merc', 'mill', 'cea', 'gall', 'lcc']:
        _map = Basemap(projection=proj, lat_0 = (minLat+maxLat)*.5, lon_0 = (minLon+maxLon)*.5,
            resolution = res, area_thresh = 1,
            llcrnrlon=(minLon)*1, llcrnrlat=(minLat)*1,
            urcrnrlon=(maxLon)*1, urcrnrlat=(maxLat)*1)
    if proj in ['stere']:
        _map = Basemap(projection=proj, lat_0 = (minLat+maxLat)*.5, lon_0 = (minLon+maxLon)*.5,
            resolution = res, area_thresh = 1,
            llcrnrlon=(minLon)-30, llcrnrlat=(minLat)*1,
            urcrnrlon=(maxLon)*1, urcrnrlat=(maxLat)*1)
    if proj in ['ortho', 'geos', 'nsper']:
        _map = Basemap(projection=proj, lat_0 = (minLat+maxLat)*.5, lon_0 = (minLon+maxLon)*.5,
            resolution = res, area_thresh = 1,
            llcrnry=minLat*1,urcrnry=maxLat*1)#, llcrnrx=minLon*1, urcrnrx=maxLon*1, )
    else: 
        _map = Basemap(projection=proj, lat_0 = (minLat+maxLat)*.5, lon_0 = (minLon+maxLon)*.5,
            resolution = res, area_thresh = 1, llcrnrlon=(minLon)*1, llcrnrlat=(minLat)*1,
            urcrnrlon=(maxLon)*1, urcrnrlat=(maxLat)*1, rsphere=(6378137.00,6356752.3142))

    t1 = time.time()
#     print(1, t1-t0)
    if show == 'y':
        t0 = time.time()
        _map.ax = ax
        t1 = time.time()
        _map.drawcoastlines(color='k')
        _map.drawcountries()
        _map.fillcontinents(lake_color='b',color = 'gray')
        _map.drawmapboundary(linewidth=2)
        
        # labels = [left,right,top,bottom]
        lbls = []
        for label in ['l','r','t','b']:
            if label in labels_in:
                lbls.append(1)
            else:
                lbls.append(0)
            
        _map.drawmeridians(np.arange(0, 360, 30), labels=lbls)
        _map.drawparallels(np.arange(-90, 90, 30), labels=lbls)    
        t2 = time.time()
        print(t2-t1)
#     plt.savefig('/static/temp_map.png', dpi=200)
    return _map, fig, ax
Example #23
0
def animator(i):
    print i
    ax.cla()
    
    data = var[i,:,:]
    
    # create basemap
    map = Basemap(projection='cyl',llcrnrlat=lat_e[0],urcrnrlat=lat_e[-1],llcrnrlon=lon_e[0],urcrnrlon=lon_e[-1],resolution='c')
    # make sure map is associated with ax, not axlogo2
    map.ax = ax
    mcoa = map.drawcoastlines(linewidth=0.25)
    mcou = map.drawcountries(linewidth=0.25)
    #add extra stripe of data to complete sphere
    #contour plot data
    pl = map.pcolor(LON,LAT,data, cmap=cmap, norm=cnorm)
    #pl = map.contourf(LON,LAT,data, cmap=cmap, norm=cnorm,antialiased=True)
    ax.set_title('%s %s %s'%(model+add,date[i],time[i]),fontsize=26)
Example #24
0
def mercator(request):
    import matplotlib
    from mpl_toolkits.basemap import Basemap
    import numpy as np
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    
    upper_lat = float(request.GET.get('upper_lat', 20))
    upper_lon = float(request.GET.get('upper_lon', 145))
    lower_lat = float(request.GET.get('lower_lat',-20))
    lower_lon = float(request.GET.get('lower_lon',90))
    true_lat = float(request.GET.get('true_lat',5))
    
    draw_ref_point = False
    try:
        ref_lat = float(request.GET.get('ref_lat'))
        ref_lon = float(request.GET.get('ref_lon'))
        draw_ref_point = True
    except:
        pass
    
    m = Basemap(projection='merc',llcrnrlat=lower_lat,urcrnrlat=upper_lat,
                llcrnrlon=lower_lon,urcrnrlon=upper_lon,lat_ts=true_lat,
                resolution=None)
    
    fig = Figure()
    canvas = FigureCanvas(fig)
    m.ax = fig.add_axes([0, 0, 1, 1])
    
#    m.drawcoastlines()
#    m.drawmapboundary(fill_color='aqua') 
#    m.fillcontinents(color='coral',lake_color='aqua')
#    m.etopo()
    m.drawlsmask(land_color='gray',ocean_color='white',lakes=True)
    m.drawparallels(np.arange(-90.,91.,30.), color='black')
    m.drawmeridians(np.arange(-180.,181.,60.), color='black')
    
    if draw_ref_point:
        x, y = m(ref_lon, ref_lat)
        m.plot(x, y, 'ro')
    
    response = HttpResponse(content_type='image/png')
    canvas.print_figure(response, dpi=100)
    return response
Example #25
0
def prepare_map(coordinates, res='i', proj='merc'):
    """Return a fig, m and ax objects
    given a set of coordinates defining a bounding box
    :param coordinates: list of coordinates (lonmin, lonmax, latmin, latmax)
    :param res: resolution in the projection ; 'i' by default (intermediate)
    :return: fig
    :type fig: Figure object
    :return m
    :type m: Basemap object
    :return ax
    :type ax: AxesSubplot object
    """
    m = Basemap(projection=proj,
                llcrnrlon=coordinates[0], llcrnrlat=coordinates[2],
                urcrnrlon=coordinates[1], urcrnrlat=coordinates[3],
                lat_ts=0.5 * (coordinates[2] + coordinates[3]), resolution=res)

    fig = plt.figure()
    ax = plt.subplot(111)
    m.ax = ax
    return fig, m, ax
Example #26
0
def draw_marker_on_map(lat, lon, fname, fmt='png', location_name=' ', gridshape=(1, 1)):
    '''Draw a marker on a map.

    :param lat: Latitude for plotting a marker.
    :type lat: :class:`float`

    :param lon: Longitude for plotting a marker.
    :type lon: :class:`float`

    :param fname: The filename of the plot.
    :type fname: :class:`string`

    :param fmt: (Optional) Filetype for the output.
    :type fmt: :class:`string`

    :param location_name: (Optional) A label for the map marker.
    :type location_name: :class:`string`

    '''
    fig = plt.figure()
    fig.dpi = 300
    ax = fig.add_subplot(111)

    m = Basemap(projection='cyl', resolution='c', llcrnrlat=lat -
                30, urcrnrlat=lat + 30, llcrnrlon=lon - 60, urcrnrlon=lon + 60)
    m.drawcoastlines(linewidth=1)
    m.drawcountries(linewidth=1)
    m.drawmapboundary(fill_color='aqua')
    m.fillcontinents(color='coral', lake_color='aqua')
    m.ax = ax

    xpt, ypt = m(lon, lat)
    m.plot(xpt, ypt, 'bo')  # plot a blue dot there
    # put some text next to the dot, offset a little bit
    # (the offset is in map projection coordinates)
    plt.text(xpt + 0.5, ypt + 1.5, location_name +
             '\n(lon: %5.1f, lat: %3.1f)' % (lon, lat))

    fig.savefig('%s.%s' % (fname, fmt), bbox_inches='tight', dpi=fig.dpi)
    fig.clf()
Example #27
0
def show_feature_centered(feature, resolution='l'):
    fig, ax = plt.subplots(figsize=(12, 12))
    cx, cy = geojson_util.centroid_of_feature(feature)

    # Calculate a good bounding box and pad it.
    minlat, minlon, maxlat, maxlon = geojson_util.bbox_of_feature(feature)
    latext = maxlat - minlat
    lonext = maxlon - minlon

    map = Basemap(projection='aea',
                  llcrnrlon=minlon - 0.5 * lonext,
                  llcrnrlat=minlat - 0.5 * latext,
                  urcrnrlon=maxlon + 0.5 * lonext,
                  urcrnrlat=maxlat + 0.5 * latext,
                  resolution=resolution,
                  lat_1=40.,
                  lat_2=60,
                  lon_0=cx,
                  lat_0=cy)

    land_color = 'lightgray'
    water_color = 'lightblue'

    map.fillcontinents(color=land_color, lake_color=water_color)
    map.drawcoastlines()
    map.drawparallels(np.arange(-90., 120., 30.))
    map.drawmeridians(np.arange(0., 420., 60.))
    map.drawmapboundary(fill_color=water_color)
    try:
        ax.set_title(feature['properties']['name'])
    except KeyError:
        pass

    plot_feature(map, feature)

    map.ax = ax

    plt.show()
    return map
Example #28
0
def animator(i):
    print i
    ax.cla()

    data = var[i, :, :]

    # create basemap
    map = Basemap(projection='cyl',
                  llcrnrlat=lat_e[0],
                  urcrnrlat=lat_e[-1],
                  llcrnrlon=lon_e[0],
                  urcrnrlon=lon_e[-1],
                  resolution='c')
    # make sure map is associated with ax, not axlogo2
    map.ax = ax
    mcoa = map.drawcoastlines(linewidth=0.25)
    mcou = map.drawcountries(linewidth=0.25)
    #add extra stripe of data to complete sphere
    #contour plot data
    pl = map.pcolor(LON, LAT, data, cmap=cmap, norm=cnorm)
    #pl = map.contourf(LON,LAT,data, cmap=cmap, norm=cnorm,antialiased=True)
    ax.set_title('%s %s %s' % (model + add, date[i], time[i]), fontsize=26)
def animator(i):
    print i
    ax.cla()
    
    # create basemap
    map = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,llcrnrlon=-180,urcrnrlon=180,resolution='c')
    map.ax = ax
    mcoa = map.drawcoastlines(linewidth=0.25)
    mcou = map.drawcountries(linewidth=0.25)
    #add extra stripe of data to complete sphere
    
    for site_ref in valid_refs:
        site_group = root_grp.groups[site_ref]
        obs_cut = site_group.variables[species.lower()][i]
        obs_lat = site_group.latitude
        obs_lon = site_group.longitude
        obs_group = site_group.process_group
        
        if obs_cut != -99999:        
            x, y = np.meshgrid(*map(obs_lon, obs_lat))
            map.scatter(x, y, c=obs_cut,s=35,cmap=cmap, norm=cnorm)

    ax.set_title('MONTHLY %s %s %s'%(species,full_dates[i],full_times[i]),fontsize=26)
Example #30
0
def show_feature(feature):
    fig, ax = plt.subplots(figsize=(12,12))
    map = Basemap(projection='merc', llcrnrlat=-80, urcrnrlat=80,
                llcrnrlon=-180, urcrnrlon=180, resolution='l')

    land_color = 'lightgray'
    water_color = 'lightblue'

    map.fillcontinents(color=land_color, lake_color=water_color)
    map.drawcoastlines()
    map.drawparallels(np.arange(-90.,120.,30.))
    map.drawmeridians(np.arange(0.,420.,60.))
    map.drawmapboundary(fill_color=water_color)
    try:
        ax.set_title(feature['properties']['name'])
    except KeyError:
        pass

    plot_feature(map, feature)

    map.ax = ax

    plt.show()
    return map
Example #31
0
def show_feature_centered(feature, resolution='l'):
    fig, ax = plt.subplots(figsize=(12,12))
    cx, cy = geojson_util.centroid_of_feature(feature)

    # Calculate a good bounding box and pad it.
    minlat, minlon, maxlat, maxlon = geojson_util.bbox_of_feature(feature)
    latext = maxlat - minlat
    lonext = maxlon - minlon

    map = Basemap(projection='aea',
            llcrnrlon = minlon - 0.5*lonext,
            llcrnrlat = minlat - 0.5*latext,
            urcrnrlon = maxlon + 0.5*lonext,
            urcrnrlat = maxlat + 0.5*latext,
            resolution=resolution,
            lat_1=40.,lat_2=60,lon_0=cx,lat_0=cy)

    land_color = 'lightgray'
    water_color = 'lightblue'

    map.fillcontinents(color=land_color, lake_color=water_color)
    map.drawcoastlines()
    map.drawparallels(np.arange(-90.,120.,30.))
    map.drawmeridians(np.arange(0.,420.,60.))
    map.drawmapboundary(fill_color=water_color)
    try:
        ax.set_title(feature['properties']['name'])
    except KeyError:
        pass

    plot_feature(map, feature)

    map.ax = ax

    plt.show()
    return map
Example #32
0
    col = bmap.imshow(masked_ndvi, origin='upper', norm=the_norm, cmap=cmap)
    cax, kw = matplotlib.colorbar.make_axes(ax,
                                            location='bottom',
                                            pad=0.05,
                                            shrink=0.7)
    out = fig.colorbar(col, cax=cax, extend='both', **kw)
    out.set_label('ndvi', size=20)
    ax.set_title('modis ndvi vancouver', size=25)
    print(kw)

# ### can save some time by reusing the bmap instance with a new axis

# In[26]:

fig, ax = plt.subplots(1, 1, figsize=(12, 12))
bmap.ax = ax
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    col = bmap.imshow(masked_ndvi, origin='upper', norm=the_norm, cmap=cmap)
    cax, kw = matplotlib.colorbar.make_axes(ax,
                                            location='bottom',
                                            pad=0.05,
                                            shrink=0.7)
    out = fig.colorbar(col, cax=cax, extend='both', **kw)
    out.set_label('ndvi', size=20)
    ax.set_title('modis ndvi vancouver -- replot me   ', size=25)
    print(kw)
bmap.drawcoastlines(linewidth=1.5, linestyle='solid', color='k')

# In[ ]:
def make_map_animation(sim_data, FPS, DPI, T_MIN, T_MAX, T_STEP, N_STEP, save_file):
    # Get ranges
    lon_min,lon_max = sim_data['lon'].min(),sim_data['lon'].max()
    lat_min,lat_max = sim_data['lat'].min(),sim_data['lat'].max()
    mean_lat = 0.5*(lat_min + lat_max)
    mean_lon = 0.5*(lon_min + lon_max)
    lon_range = lon_max - lon_min
    lat_range = lat_max - lat_min
    z_min,z_max = sim_data['z'].min(),sim_data['z'].max()
    cmap = plt.get_cmap('Blues_r')
    norm = mcolor.Normalize(vmin=z_min/60, vmax=-z_min/60)
    interp = 'none'
    landcolor = '#FFFFCC'
    framelabelfont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=14)
    
    # Split the data up into arrays for each time step
    split_data = np.split(sim_data, np.unique(sim_data['time']).shape[0])
    
    # Initialize movie writing stuff
    FFMpegWriter = manimation.writers['ffmpeg']
    metadata = dict(title='TsunamiSquares', artist='Matplotlib',
                    comment='Bump in the middle, with accelerations.')
    writer = FFMpegWriter(fps=FPS, metadata=metadata)
    
    # Initialize the frame and axes
    fig = plt.figure()

    m = Basemap(projection='cyl',llcrnrlat=lat_min, urcrnrlat=lat_max,
            llcrnrlon=lon_min, urcrnrlon=lon_max, lat_0=mean_lat, lon_0=mean_lon, resolution='h')
    m.ax = fig.add_subplot(111)

    m.drawmeridians(np.linspace(lon_min,lon_max,num=5.0),labels=[0,0,0,1], linewidth=0)
    m.drawparallels(np.linspace(lat_min,lat_max,num=5.0),labels=[1,0,0,0], linewidth=0)
    m.drawcoastlines(linewidth=0.5)
    #m.drawcountries()
    #m.drawstates()
    #m.fillcontinents(color=landcolor)
    #m.shadedrelief()
    
    # Colorbar
    divider = make_axes_locatable(m.ax)
    cbar_ax = divider.append_axes("right", size="5%",pad=0.05)
    plt.figtext(0.95, 0.7, r'water altitude $[m]$', rotation='vertical', fontproperties=framelabelfont)
    cb = mcolorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=norm)
    
    # Increment the time from T_MIN
    TIME = T_MIN
    
    first_step = sim_data[ sim_data['time'] == T_MIN ]
    Ncols = len(np.unique(first_step['lon']))
    
    surface = None
    with writer.saving(fig, save_file, DPI):
        for index in range(int(N_STEP)):
            # Get the subset of data corresponding to current time
            this_step = split_data[index]
            time = this_step['time'][0]
                    
            print "step: "+str(index)+"  time: "+str(time)+" num_points: "+str(len(this_step))
            assert len(this_step) > 0
                
            X = this_step['lon'].reshape(-1, Ncols)
            Y = this_step['lat'].reshape(-1, Ncols)
            Z = this_step['z'].reshape(-1, Ncols)
            ALT = this_step['alt'].reshape(-1, Ncols)
            
            # Masked array via conditional, don't color the land unless it has water on it
            masked_data = np.ma.masked_where(np.logical_and(np.array(Z == 0.0),np.array(ALT >= 0.0)), Z)
            
            # Set masked pixels to the land color
            cmap.set_bad(landcolor, 1.0)  # set alpha=0.0 for transparent
            
            # Plot the surface for this time step
            if surface is None:
                surface = m.ax.imshow(masked_data,cmap=cmap,origin='lower',norm=norm,extent=[lon_min,lon_max,lat_max,lat_min],interpolation=interp)
            else:
                surface.set_data(masked_data)
                
            # Text box with the time
            plt.figtext(0.129, 0.82, 'Time: {:02d}:{:02d}'.format(int(time)/60, int(time)%60), bbox={'facecolor':'yellow', 'pad':5})
                
            writer.grab_frame()
        
            TIME +=T_STEP
Example #34
0
def iieval_plot(outDIR,flag_svplt,\
                available_models,\
                era5,multimodel,lat,lon):

    #==============================================================================
    #DEFINE PLOT SETTINGS
    #==============================================================================

    # list of figure panel ids
    letters = ['a', 'b', 'c',\
               'd', 'e', 'f',\
               'g', 'h', 'i',\
               'j', 'k', 'l',\
               'm', 'n', 'o']

    # font settings
    title_font = 13
    cbtitle_font = 13
    tick_font = 11
    arrow_font = 13

    # continent fill
    col_cont = 'white'

    # ocean fill
    col_ocean = 'whitesmoke'

    # zero change color
    col_zero = 'gray'

    # list of ice index titles
    ice_titles = ['Ice onset', 'Ice break-up', 'Ice duration']

    # list of model titles
    model_titles = ['CLM4.5', 'ALBM', 'SIMSTRAT-UoG', 'VIC-LAKE', 'LAKE']

    #========== COLORBAR ==========#

    # identify colors
    cmap_whole = plt.cm.get_cmap('RdBu_r')
    cmap55 = cmap_whole(0.01)
    cmap50 = cmap_whole(0.05)  #blue
    cmap45 = cmap_whole(0.1)
    cmap40 = cmap_whole(0.15)
    cmap35 = cmap_whole(0.2)
    cmap30 = cmap_whole(0.25)
    cmap25 = cmap_whole(0.3)
    cmap20 = cmap_whole(0.325)
    cmap10 = cmap_whole(0.4)
    cmap5 = cmap_whole(0.475)
    cmap0 = col_zero
    cmap_5 = cmap_whole(0.525)
    cmap_10 = cmap_whole(0.6)
    cmap_20 = cmap_whole(0.625)
    cmap_25 = cmap_whole(0.7)
    cmap_30 = cmap_whole(0.75)
    cmap_35 = cmap_whole(0.8)
    cmap_40 = cmap_whole(0.85)
    cmap_45 = cmap_whole(0.9)
    cmap_50 = cmap_whole(0.95)  #red
    cmap_55 = cmap_whole(0.99)

    # declare list of colors for discrete colormap of colorbar
    cmap = mpl.colors.ListedColormap([
        cmap_50, cmap_40, cmap_35, cmap_30, cmap_20, cmap_5, cmap0, cmap5,
        cmap20, cmap30, cmap35, cmap40, cmap50
    ],
                                     N=13)

    # set color of over/under arrows in colorbar
    cmap.set_over(cmap55)
    cmap.set_under(cmap_55)

    # colorbar args
    values = [-30, -25, -20, -15, -10, -5, 5, 10, 15, 20, 25, 30]
    tick_locs = [-30, -25, -20, -15, -10, 0, 10, 15, 20, 25, 30]
    norm = mpl.colors.BoundaryNorm(values, cmap.N)

    # bbox (arrow plot relative to this axis)
    cb_x0 = 0.2275
    cb_y0 = 0.22
    cb_xlen = 0.55
    cb_ylen = 0.01

    # colorbar label
    cblabel = 'Bias in ice onset, break-up or duration (days)'

    #========== ARROWS ==========#

    # blue arrow label
    bluelabel = 'Later date (panels a,b) or longer duration (panel c)'
    x0_bluelab = 0.825
    y0_bluelab = -2.7

    # blue arrow
    x0_bluearr = 0.505
    y0_bluearr = -3.3
    xlen_bluearr = 0.7
    ylen_bluearr = 0

    # red arrow label
    redlabel = 'Earlier date (panels a,b) or shorter duration (panel c)'
    x0_redlab = 0.175
    y0_redlab = -2.7

    # red arrow
    x0_redarr = 0.495
    y0_redarr = -3.3
    xlen_redarr = -0.7
    ylen_redarr = 0

    # general
    arrow_width = 0.25
    arrow_linew = 0.1
    arrow_headwidth = 0.5
    arrow_headlength = 0.06

    #========== SUBPLOTS ==========#

    left_border = 0.15
    right_border = 0.85
    bottom_border = 0.25
    top_border = 0.925
    width_space = 0.05
    height_space = 0.05

    #==============================================================================
    #PLOT TEST HIST
    #==============================================================================

    # second; plot hist with 5th to 95th % on xaxis per model
    sets = {}
    sets['clm45'] = multimodel[0:3]
    sets['albm'] = multimodel[3:6]
    sets['simstrat-uog'] = multimodel[6:9]
    sets['vic-lake'] = multimodel[9:11]
    sets['lakemod'] = multimodel[12:14]

    mins = {}
    maxs = {}
    for mod in available_models:
        mins[mod] = []
        maxs[mod] = []
        for array in sets[mod]:
            data = array.flatten()
            data = sorted(data[np.logical_not(np.isnan(data))])
            pcts = np.percentile(data, q=[5, 95])
            data_min = pcts[0]
            data_max = pcts[1]
            mins[mod].append(data_min)
            maxs[mod].append(data_max)

    f, axes = plt.subplots(len(available_models),
                           3,
                           figsize=(12, 4 * len(available_models)))
    count = 0

    for mod, ax in zip(multimodel, axes.flatten()):

        count += 1

        data = mod.flatten()
        data = sorted(data[np.logical_not(np.isnan(data))])

        if count <= 3:
            setmin = np.min(mins['clm45'])
            setmax = np.max(maxs['clm45'])

        if count >= 4 and count <= 6:
            setmin = np.min(mins['simstrat-uog'])
            setmax = np.max(maxs['simstrat-uog'])

        if count >= 7 and count <= 9:
            setmin = np.min(mins['vic-lake'])
            setmax = np.max(maxs['vic-lake'])

        if count >= 10 and count <= 12:
            setmin = np.min(mins['lakemod'])
            setmax = np.max(maxs['lakemod'])

        ax.hist(data, range=(setmin, setmax), rwidth=0.75)
        ax.yaxis.set_label_position('right')
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.set_title(letters[count - 1],
                     loc='left',
                     pad=10,
                     fontsize=title_font,
                     fontweight='bold')

        if count <= 3:
            ax.set_title(ice_titles[count - 1],
                         loc='center',
                         pad=10,
                         fontsize=title_font)
        if count == 3:
            ax.set_ylabel(model_titles[0], fontsize=title_font, rotation=-90)
        if count == 6:
            ax.set_ylabel(model_titles[1], fontsize=title_font, rotation=-90)
        if count == 9:
            ax.set_ylabel(model_titles[2], fontsize=title_font, rotation=-90)
        if count == 12:
            ax.set_ylabel(model_titles[3], fontsize=title_font, rotation=-90)
        if count == 15:
            ax.set_ylabel(model_titles[4], fontsize=title_font, rotation=-90)

    f.text(0.5,
           -0.01,
           '5th to 95th percentile in bias per model (days)',
           ha='center',
           fontsize=title_font)
    f.text(-0.02,
           0.5,
           'Grid cells [-]',
           va='center',
           rotation='vertical',
           fontsize=title_font)

    plt.tight_layout()
    plt.show()

    # save figure
    if flag_svplt == 0:
        None
    elif flag_svplt == 1:
        f.savefig(outDIR + '/si_f28.png', bbox_inches='tight', dpi=500)

    #==============================================================================
    #PLOT MAIN FIG
    #==============================================================================

    lon, lat = np.meshgrid(lon, lat)

    f, axes = plt.subplots(int(len(multimodel) / 3), 3, figsize=(15, 25))

    count = 0

    for mod, ax in zip(multimodel, axes.flatten()):

        count += 1

        m = Basemap(projection='npaeqd',round=True,boundinglat=20,\
                    lat_0=80,lon_0=0,resolution='l')
        m.ax = ax
        m.drawcoastlines(linewidth=0.05)
        m.drawmapboundary(linewidth=0.15, fill_color=col_ocean)
        m.fillcontinents(color=col_cont)
        m.pcolormesh(lon,
                     lat,
                     mod,
                     latlon=True,
                     cmap=cmap,
                     norm=norm,
                     vmax=30,
                     vmin=-30,
                     zorder=3)
        ax.set_title(letters[count - 1],
                     loc='left',
                     fontsize=title_font,
                     fontweight='bold')
        if count <= 3:
            ax.set_title(ice_titles[count - 1],
                         loc='center',
                         pad=10,
                         fontsize=title_font)
        if count == 1:
            ax.set_ylabel(model_titles[0], fontsize=title_font, labelpad=15)
        if count == 4:
            ax.set_ylabel(model_titles[1], fontsize=title_font, labelpad=15)
        if count == 7:
            ax.set_ylabel(model_titles[2], fontsize=title_font, labelpad=15)
        if count == 10:
            ax.set_ylabel(model_titles[3], fontsize=title_font, labelpad=15)
        if count == 13:
            ax.set_ylabel(model_titles[4], fontsize=title_font, labelpad=15)

    cbax = f.add_axes([cb_x0, cb_y0, cb_xlen, cb_ylen])
    cb = mpl.colorbar.ColorbarBase(ax=cbax,
                                   cmap=cmap,
                                   norm=norm,
                                   spacing='proportional',
                                   orientation='horizontal',
                                   extend='both',
                                   ticks=tick_locs)
    cb.set_label(cblabel, size=cbtitle_font)
    cb.ax.xaxis.set_label_position('top')
    cb.ax.tick_params(labelcolor='0.2',labelsize=tick_font,color='0.2',\
                      length=2.5,width=0.35,direction='out')
    cb.ax.set_xticklabels([r'$\leq$-30','-25','-20','-15','-10',\
                           '0','10','15','20','25',r'30$\leq$'])
    cb.outline.set_edgecolor('0.2')
    cb.outline.set_linewidth(0.4)

    # arrow setup
    plt.text(x0_bluelab,
             y0_bluelab,
             bluelabel,
             size=arrow_font,
             ha='center',
             va='center')
    plt.text(x0_redlab,
             y0_redlab,
             redlabel,
             size=arrow_font,
             ha='center',
             va='center')
    plt.arrow(x0_bluearr, y0_bluearr, xlen_bluearr, ylen_bluearr, width=arrow_width, linewidth=arrow_linew,\
              shape='right', head_width=arrow_headwidth, head_length=arrow_headlength,\
              facecolor=cmap40, edgecolor='k', clip_on=False)
    plt.arrow(x0_redarr, y0_redarr, xlen_redarr, ylen_redarr, width=arrow_width, linewidth=arrow_linew,\
              shape='left', head_width=arrow_headwidth, head_length=arrow_headlength,\
              facecolor=cmap_40, edgecolor='k', clip_on=False)

    plt.subplots_adjust(left=left_border, right=right_border, bottom=bottom_border, top=top_border,\
                        wspace=width_space, hspace=height_space)
    plt.show()

    # save figure
    if flag_svplt == 0:
        None
    elif flag_svplt == 1:
        f.savefig(outDIR + '/si_f27.png', bbox_inches='tight', dpi=500)
Example #35
0
def bathy_topo_map(LLD_FILE):

    save_file = os.path.splitext(LLD_FILE)[0] + '_bathymap.png'
    extension = os.path.splitext(LLD_FILE)[1]

    # Read bathymetry/topography data
    if extension == ".txt":
        data = np.genfromtxt(LLD_FILE,
                             dtype=[('lat', 'f8'), ('lon', 'f8'), ('z', 'f8')],
                             skip_header=6)

        # Reshape into matrices
        Ncols = len(np.unique(data['lon']))
        Nrows = len(np.unique(data['lat']))

        X = data['lon'].reshape(Nrows, Ncols)
        Y = data['lat'].reshape(Nrows, Ncols)
        Z = data['z'].reshape(Nrows, Ncols)

        # Data ranges
        lon_min, lon_max = data['lon'].min(), data['lon'].max()
        lat_min, lat_max = data['lat'].min(), data['lat'].max()

    elif extension == ".nc":
        data = Dataset(LLD_FILE, 'r')

        # Reshape into matrices
        Ncols = len(data['longitude'][:])
        Nrows = len(data['latitude'][:])

        X, Y = np.meshgrid(data['longitude'][:], data['latitude'][:])
        Z = data['altitude'][::]

        # Data ranges
        lon_min, lon_max = data['longitude'][:].min(
        ), data['longitude'][:].max()
        lat_min, lat_max = data['latitude'][:].min(), data['latitude'][:].max()

    else:
        raise BaseException("Bathymetry file is an unsupported file type")

    mean_lat = 0.5 * (lat_min + lat_max)
    mean_lon = 0.5 * (lon_min + lon_max)
    lon_range = lon_max - lon_min
    lat_range = lat_max - lat_min
    cmap = plt.get_cmap('terrain')
    interp = 'nearest'
    framelabelfont = mfont.FontProperties(family='Arial',
                                          style='normal',
                                          variant='normal',
                                          size=14)

    # catch any nan values
    masked_data = np.ma.masked_invalid(Z)
    cmap.set_bad('red')

    # Color limits
    z_min, z_max = masked_data.min(), masked_data.max()
    z_lim = max(np.abs(z_min), np.abs(z_max))
    norm = mcolor.Normalize(vmin=-z_lim, vmax=z_lim)

    # Initialize the frame and axes
    fig = plt.figure()

    m = Basemap(projection='cyl',
                llcrnrlat=lat_min,
                urcrnrlat=lat_max,
                llcrnrlon=lon_min,
                urcrnrlon=lon_max,
                lat_0=mean_lat,
                lon_0=mean_lon,
                resolution='h')
    m.ax = fig.add_subplot(111)

    m.drawmeridians(np.linspace(lon_min, lon_max, num=5.0),
                    labels=[0, 0, 0, 1],
                    linewidth=0)
    m.drawparallels(np.linspace(lat_min, lat_max, num=5.0),
                    labels=[1, 0, 0, 0],
                    linewidth=0)
    m.drawcoastlines(linewidth=0.5)

    # Colorbar
    divider = make_axes_locatable(m.ax)
    cbar_ax = divider.append_axes("right", size="5%", pad=0.05)
    plt.figtext(0.96,
                0.7,
                r'elevation $[m]$',
                rotation='vertical',
                fontproperties=framelabelfont)
    cb = mcolorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=norm)

    # Plot the contours
    #m.contourf(X, Y, masked_data, 100, cmap=cmap, norm=norm, extend='both', zorder=1)
    m.ax.imshow(masked_data,
                cmap=cmap,
                origin='lower',
                norm=norm,
                extent=[lon_min, lon_max, lat_min, lat_max],
                interpolation=interp)

    plt.savefig(save_file, dpi=100)
    print("Saved to " + save_file)
Example #36
0
def plot_eq_disps_horiz(disp_file):
    # Read displacement data
    disp_data = np.genfromtxt(disp_file,
                              dtype=[('lon', 'f8'), ('lat', 'f8'), ('z', 'f8'),
                                     ('eU', 'f8'), ('nV', 'f8')])

    save_file_prefix = os.path.splitext(disp_file)[0] + "_disp"

    # Data ranges
    lon_min, lon_max = disp_data['lon'].min(), disp_data['lon'].max()
    lat_min, lat_max = disp_data['lat'].min(), disp_data['lat'].max()
    mean_lat = 0.5 * (lat_min + lat_max)
    mean_lon = 0.5 * (lon_min + lon_max)
    lon_range = lon_max - lon_min
    lat_range = lat_max - lat_min

    # Reshape into matrices
    Ncols = len(np.unique(disp_data['lon']))
    Nrows = len(np.unique(disp_data['lat']))
    X = disp_data['lon'].reshape(Nrows, Ncols)
    Y = disp_data['lat'].reshape(Nrows, Ncols)
    Z = disp_data['z'].reshape(Nrows, Ncols)
    eU = disp_data['eU'].reshape(Nrows, Ncols)
    nV = disp_data['nV'].reshape(Nrows, Ncols)

    cmap = plt.get_cmap('seismic')

    z_min, z_max = disp_data['z'].min(), disp_data['z'].max()
    z_lim = max(np.abs(z_min), np.abs(z_max))
    normz = mcolor.Normalize(vmin=-z_lim, vmax=z_lim)
    #LEVELSz = np.concatenate((-1*np.logspace(-3, np.log10(z_lim), 6)[::-1], np.logspace(-3, np.log10(z_lim), 6)))
    LEVELSz = np.concatenate(
        (-1 * np.linspace(0.01, z_lim, 6)[::-1], np.linspace(0.01, z_lim, 6)))

    e_min, e_max = disp_data['eU'].min(), disp_data['eU'].max()
    e_lim = max(np.abs(e_min), np.abs(e_max))
    norme = mcolor.Normalize(vmin=-e_lim, vmax=e_lim)
    #LEVELSe = np.concatenate((-1*np.logspace(-3, np.log10(e_lim), 6)[::-1], np.logspace(-3, np.log10(e_lim), 6)))
    LEVELSe = np.concatenate(
        (-1 * np.linspace(0.01, e_lim, 6)[::-1], np.linspace(0.01, e_lim, 6)))

    n_min, n_max = disp_data['nV'].min(), disp_data['nV'].max()
    n_lim = max(np.abs(n_min), np.abs(n_max))
    normn = mcolor.Normalize(vmin=-n_lim, vmax=n_lim)
    #LEVELSn = np.concatenate((-1*np.logspace(-3, np.log10(n_lim), 6)[::-1], np.logspace(-3, np.log10(n_lim), 6)))
    LEVELSn = np.concatenate(
        (-1 * np.linspace(0.01, n_lim, 6)[::-1], np.linspace(0.01, n_lim, 6)))

    interp = 'cubic'
    landcolor = '#FFFFCC'
    framelabelfont = mfont.FontProperties(family='Arial',
                                          style='normal',
                                          variant='normal',
                                          size=14)

    # Initialize the frame and axes
    fig = plt.figure(0)
    m = Basemap(projection='cyl',
                llcrnrlat=lat_min,
                urcrnrlat=lat_max,
                llcrnrlon=lon_min,
                urcrnrlon=lon_max,
                lat_0=mean_lat,
                lon_0=mean_lon,
                resolution='h')
    m.ax = fig.add_subplot(111)
    m.drawmeridians(np.linspace(lon_min, lon_max, num=5.0),
                    labels=[0, 0, 0, 1],
                    linewidth=0)
    m.drawparallels(np.linspace(lat_min, lat_max, num=5.0),
                    labels=[1, 0, 0, 0],
                    linewidth=0)
    m.drawcoastlines(linewidth=0.5)
    m.fillcontinents(color=landcolor, zorder=0)

    # Colorbar
    divider = make_axes_locatable(m.ax)
    cbar_ax = divider.append_axes("right", size="5%", pad=0.05)
    plt.figtext(0.96,
                0.7,
                r'Vertical disp $[m]$',
                rotation='vertical',
                fontproperties=framelabelfont)
    cbz = mcolorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=normz)

    # Masked array via conditional, don't color the land unless it has water on it
    zero_below = int(len(LEVELSz) / 2) - 1
    zero_above = zero_below + 1
    masked_data = np.ma.masked_where(
        np.logical_and(np.array(Z <= LEVELSz[zero_above]),
                       np.array(Z >= LEVELSz[zero_below])), Z)

    # Set masked pixels to the land color
    cmap.set_bad(landcolor, 0.0)  # set alpha=0.0 for transparent

    # Plot the contours
    m.contourf(X,
               Y,
               masked_data,
               LEVELSz,
               cmap=cmap,
               norm=normz,
               extend='both',
               zorder=1)

    plt.savefig(save_file_prefix + '_z.png', dpi=100)

    # Initialize the frame and axes
    fig = plt.figure(1)
    m = Basemap(projection='cyl',
                llcrnrlat=lat_min,
                urcrnrlat=lat_max,
                llcrnrlon=lon_min,
                urcrnrlon=lon_max,
                lat_0=mean_lat,
                lon_0=mean_lon,
                resolution='h')
    m.ax = fig.add_subplot(111)
    m.drawmeridians(np.linspace(lon_min, lon_max, num=5.0),
                    labels=[0, 0, 0, 1],
                    linewidth=0)
    m.drawparallels(np.linspace(lat_min, lat_max, num=5.0),
                    labels=[1, 0, 0, 0],
                    linewidth=0)
    m.drawcoastlines(linewidth=0.5)
    m.fillcontinents(color=landcolor, zorder=0)

    # Colorbar
    divider = make_axes_locatable(m.ax)
    cbar_ax = divider.append_axes("right", size="5%", pad=0.05)
    plt.figtext(0.96,
                0.7,
                r'East disp $[m]$',
                rotation='vertical',
                fontproperties=framelabelfont)
    cbe = mcolorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=norme)

    # Masked array via conditional, don't color the land unless it has water on it
    zero_below = int(len(LEVELSe) / 2) - 1
    zero_above = zero_below + 1
    masked_data = np.ma.masked_where(
        np.logical_and(np.array(eU <= LEVELSe[zero_above]),
                       np.array(eU >= LEVELSe[zero_below])), eU)

    # Set masked pixels to the land color
    cmap.set_bad(landcolor, 0.0)  # set alpha=0.0 for transparent

    # Plot the contours
    m.contourf(X,
               Y,
               masked_data,
               LEVELSe,
               cmap=cmap,
               norm=norme,
               extend='both',
               zorder=1)

    plt.savefig(save_file_prefix + '_e.png', dpi=100)

    # Initialize the frame and axes
    fig = plt.figure(2)
    m = Basemap(projection='cyl',
                llcrnrlat=lat_min,
                urcrnrlat=lat_max,
                llcrnrlon=lon_min,
                urcrnrlon=lon_max,
                lat_0=mean_lat,
                lon_0=mean_lon,
                resolution='h')
    m.ax = fig.add_subplot(111)
    m.drawmeridians(np.linspace(lon_min, lon_max, num=5.0),
                    labels=[0, 0, 0, 1],
                    linewidth=0)
    m.drawparallels(np.linspace(lat_min, lat_max, num=5.0),
                    labels=[1, 0, 0, 0],
                    linewidth=0)
    m.drawcoastlines(linewidth=0.5)
    m.fillcontinents(color=landcolor, zorder=0)

    # Colorbar
    divider = make_axes_locatable(m.ax)
    cbar_ax = divider.append_axes("right", size="5%", pad=0.05)
    plt.figtext(0.96,
                0.7,
                r'North disp $[m]$',
                rotation='vertical',
                fontproperties=framelabelfont)
    cbn = mcolorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=normn)

    # Masked array via conditional, don't color the land unless it has water on it
    zero_below = int(len(LEVELSn) / 2) - 1
    zero_above = zero_below + 1
    masked_data = np.ma.masked_where(
        np.logical_and(np.array(nV <= LEVELSn[zero_above]),
                       np.array(nV >= LEVELSn[zero_below])), nV)

    # Set masked pixels to the land color
    cmap.set_bad(landcolor, 0.0)  # set alpha=0.0 for transparent

    # Plot the contours
    m.contourf(X,
               Y,
               masked_data,
               LEVELSn,
               cmap=cmap,
               norm=normn,
               extend='both',
               zorder=1)

    plt.savefig(save_file_prefix + '_n.png', dpi=100)

    print("Saved to " + save_file)
Example #37
0
def plot_anomaly_points():
    dirs = "../result_h/A/anomaly_ic0/"
    mkdir(dirs)

    start_list.pop()
    for i, start in enumerate(start_list):
        print("******************  {}/{}  *******************".format(
            i + 1, M - 1))
        helmert_30_30_fname = "../data/csv_Helmert_both_30/Helmert_both_30_" + str(
            start)[:6] + ".csv"
        data_30 = pd.read_csv(helmert_30_30_fname)
        helmert_30_90_fname = "../data/csv_Helmert_ocean_90/Helmert_30_90_" + str(
            start)[:6] + ".csv"
        data_90 = pd.read_csv(helmert_30_90_fname)

        #anomaly_30 = data_30.loc[((data_30.A>=0.005)&(data_30.ic0_30>=97)), "A"]
        #anomaly_90 = data_90.loc[((data_90.A_30_90>=0.005)&(data_90.ic0_30>=97)), "A_30_90"]
        anomaly_bool_30 = (data_30.A >= 0.005) & (data_30.ic0_30 >= 97)
        data_30["anomaly"] = data_30.epsilon2[anomaly_bool_30]
        anomaly_bool_90 = (data_90.A_30_90 >= 0.005) & (data_90.ic0_30 >= 97)
        data_90["anomaly"] = data_90.epsilon2_30_90[anomaly_bool_90]

        fig, axes = plt.subplots(1, 2)
        data_list = [
            np.array(data_30["anomaly"]),
            np.array(data_90["anomaly"])
        ]
        for j in range(2):
            ax = axes[j]
            m = Basemap(lon_0=180,
                        boundinglat=50,
                        resolution='l',
                        projection='npstere')
            m.ax = ax
            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(data_list[j])
            data1 = np.reshape(data, (145, 145), order='F')
            im = m.pcolormesh(xx_ex - dx1,
                              yy_ex + dy1,
                              data1,
                              cmap=plt.cm.jet,
                              vmax=1,
                              vmin=0)
            fig.colorbar(im, ax=ax)
            #m.colorbar(location='bottom')
        save_name = dirs + str(start)[:6] + ".png"
        print(save_name)
        plt.savefig(save_name, dpi=500)
        plt.close()
Example #38
0
def draw_contour_map(dataset, lats, lons, fname, fmt='png', gridshape=(1, 1),
                     clabel='', ptitle='', subtitles=None, cmap=None,
                     clevs=None, nlevs=10, parallels=None, meridians=None,
                     extend='neither', aspect=8.5 / 2.5):
    ''' Draw a multiple panel contour map plot.

    :param dataset: 3D array of data to be plotted with shape (nT, nLat, nLon).
    :type dataset: :class:`numpy.ndarray`

    :param lats: Array of latitudes values.
    :type lats: :class:`numpy.ndarray`

    :param lons: Array of longitudes
    :type lons: :class:`numpy.ndarray`

    :param fname: The filename of the plot.
    :type fname: :mod:`string`

    :param fmt: (Optional) filetype for the output.
    :type fmt: :mod:`string`

    :param gridshape: (Optional) tuple denoting the desired grid shape
        (num_rows, num_cols) for arranging the subplots.
    :type gridshape: :func:`tuple` of the form (num_rows, num_cols)

    :param clabel: (Optional) colorbar title.
    :type clabel: :mod:`string`

    :param ptitle: (Optional) plot title.
    :type ptitle: :mod:`string`

    :param subtitles: (Optional) list of titles for each subplot.
    :type subtitles: :class:`list` of :mod:`string`

    :param cmap: (Optional) string or :class:`matplotlib.colors.LinearSegmentedColormap`
        instance denoting the colormap. This must be able to be recognized by
        `Matplotlib's get_cmap function <http://matplotlib.org/api/cm_api.html#matplotlib.cm.get_cmap>`_.
    :type cmap: :mod:`string` or :class:`matplotlib.colors.LinearSegmentedColormap`

    :param clevs: (Optional) contour levels values.
    :type clevs: :class:`list` of :class:`int` or :class:`float`

    :param nlevs: (Optional) target number of contour levels if clevs is None.
    :type nlevs: :class:`int`

    :param parallels: (Optional) list of ints or floats for the parallels to
        be drawn. See the `Basemap documentation <http://matplotlib.org/basemap/users/graticule.html>`_
        for additional information.
    :type parallels: :class:`list` of :class:`int` or :class:`float`

    :param meridians: (Optional) list of ints or floats for the meridians to
        be drawn. See the `Basemap documentation <http://matplotlib.org/basemap/users/graticule.html>`_
        for additional information.
    :type meridians: :class:`list` of :class:`int` or :class:`float`

    :param extend: (Optional) flag to toggle whether to place arrows at the colorbar
         boundaries. Default is 'neither', but can also be 'min', 'max', or
         'both'. Will be automatically set to 'both' if clevs is None.
    :type extend: :mod:`string`
    '''
    # Handle the single plot case. Meridians and Parallels are not labeled for
    # multiple plots to save space.
    if dataset.ndim == 2 or (dataset.ndim == 3 and dataset.shape[0] == 1):
        if dataset.ndim == 2:
            dataset = dataset.reshape(1, *dataset.shape)
        mlabels = [0, 0, 0, 1]
        plabels = [1, 0, 0, 1]
    else:
        mlabels = [0, 0, 0, 0]
        plabels = [0, 0, 0, 0]

    # Make sure gridshape is compatible with input data
    nplots = dataset.shape[0]
    gridshape = _best_grid_shape(nplots, gridshape)

    # Set up the figure
    fig = plt.figure()
    fig.set_size_inches((8.5, 11.))
    fig.dpi = 300

    # Make the subplot grid
    grid = ImageGrid(fig, 111,
                     nrows_ncols=gridshape,
                     axes_pad=0.3,
                     share_all=True,
                     add_all=True,
                     ngrids=nplots,
                     label_mode='L',
                     cbar_mode='single',
                     cbar_location='bottom',
                     cbar_size=.15,
                     cbar_pad='0%'
                     )

    # Determine the map boundaries and construct a Basemap object
    lonmin = lons.min()
    lonmax = lons.max()
    latmin = lats.min()
    latmax = lats.max()
    m = Basemap(projection='cyl', llcrnrlat=latmin, urcrnrlat=latmax,
                llcrnrlon=lonmin, urcrnrlon=lonmax, resolution='l')

    # Convert lats and lons to projection coordinates
    if lats.ndim == 1 and lons.ndim == 1:
        lons, lats = np.meshgrid(lons, lats)

    # Calculate contour levels if not given
    if clevs is None:
        # Cut off the tails of the distribution
        # for more representative contour levels
        clevs = _nice_intervals(dataset, nlevs)
        extend = 'both'

    cmap = plt.get_cmap(cmap)

    # Create default meridians and parallels. The interval between
    # them should be 1, 5, 10, 20, 30, or 40 depending on the size
    # of the domain
    length = max((latmax - latmin), (lonmax - lonmin)) / 5
    if length <= 1:
        dlatlon = 1
    elif length <= 5:
        dlatlon = 5
    else:
        dlatlon = np.round(length, decimals=-1)
    if meridians is None:
        meridians = np.r_[
            np.arange(0, -180, -dlatlon)[::-1], np.arange(0, 180, dlatlon)]
    if parallels is None:
        parallels = np.r_[np.arange(0, -90, -dlatlon)
                          [::-1], np.arange(0, 90, dlatlon)]

    x, y = m(lons, lats)
    for i, ax in enumerate(grid):
        # Load the data to be plotted
        data = dataset[i]
        m.ax = ax

        # Draw the borders for coastlines and countries
        m.drawcoastlines(linewidth=1)
        m.drawcountries(linewidth=.75)

        # Draw parallels / meridians
        m.drawmeridians(meridians, labels=mlabels, linewidth=.75, fontsize=10)
        m.drawparallels(parallels, labels=plabels, linewidth=.75, fontsize=10)

        # Draw filled contours
        cs = m.contourf(x, y, data, cmap=cmap, levels=clevs, extend=extend)

        # Add title
        if subtitles is not None:
            ax.set_title(subtitles[i], fontsize='small')

    # Add colorbar
    cbar = fig.colorbar(cs, cax=ax.cax, drawedges=True,
                        orientation='horizontal', extendfrac='auto')
    cbar.set_label(clabel)
    cbar.set_ticks(clevs)
    cbar.ax.tick_params(labelsize=6)
    cbar.ax.xaxis.set_ticks_position('none')
    cbar.ax.yaxis.set_ticks_position('none')

    # This is an ugly hack to make the title show up at the correct height.
    # Basically save the figure once to achieve tight layout and calculate
    # the adjusted heights of the axes, then draw the title slightly above
    # that height and save the figure again
    fig.savefig(TemporaryFile(), bbox_inches='tight', dpi=fig.dpi)
    ymax = 0
    for ax in grid:
        bbox = ax.get_position()
        ymax = max(ymax, bbox.ymax)

    # Add figure title
    fig.suptitle(ptitle, y=ymax + .06, fontsize=16)
    fig.savefig('%s.%s' % (fname, fmt), bbox_inches='tight', dpi=fig.dpi)
    fig.clf()
Example #39
0
norm1 = mpl.colors.BoundaryNorm(values1, cmap.N)
norm2 = mpl.colors.BoundaryNorm(values2, cmap2.N)

lats = rmse_difmpd1.lat.values
lons = rmse_difmpd1.lon.values
lons, lats = np.meshgrid(lons, lats)

pos1 = [[0.1, 0.57, 0.4, 0.4], [0.55, 0.57, 0.4, 0.4], [0.1, 0.08, 0.4, 0.4],
        [0.55, 0.08, 0.4, 0.4]]
pos2 = [[0.25, 0.55, 0.5, 0.015], [0.25, 0.065, 0.5, 0.015]]

fig = plt.figure(figsize=(10, 7))

ax1 = fig.add_axes(pos1[0])
m = Basemap(projection='kav7', lon_0=0, resolution=None)
m.ax = ax1
m.drawmapboundary(color='0.8', fill_color='0.8')
im1 = m.pcolormesh(lons,
                   lats,
                   rmse_difumpd1.values,
                   shading='flat',
                   cmap=cmap,
                   norm=norm1,
                   latlon=True)
ax1.set_ylabel('RMSE (not mapped)')
ax1.set_title('UKESM1', fontweight='bold')
ax1.set_title('a.', fontweight='bold', loc='left')

cbax = fig.add_axes(pos2[0])
cb = mpl.colorbar.ColorbarBase(ax=cbax,
                               cmap=cmap,
Example #40
0
def main(show=True, outfile=None):
    db = connect()
    stations = get_stations(db, all=False)
    coords = [(sta.Y, sta.X) for sta in stations]
    coords = np.array(coords)

    sta_map = folium.Map(
        location=[np.mean(coords[:, 0]),
                  np.mean(coords[:, 1])],
        zoom_start=3,
        tiles='OpenStreetMap')
    folium.RegularPolygonMarker(
        location=[np.mean(coords[:, 1]),
                  np.mean(coords[:, 0])]).add_to(sta_map)
    for sta in stations:
        folium.RegularPolygonMarker(location=[sta.Y, sta.X],
                                    popup="%s_%s" % (sta.net, sta.sta),
                                    fill_color='red',
                                    number_of_sides=3,
                                    radius=12).add_to(sta_map)

    sta_map.add_child(folium.LatLngPopup())
    if outfile:
        tmp = outfile
        if outfile.startswith("?"):
            now = datetime.datetime.now()
            now = now.strftime('station map on %Y-%m-%d %H.%M.%S')
            tmp = outfile.replace('?', now)
        print("output to:", tmp)
        sta_map.save('%s.html' % tmp)

    # plot topography/bathymetry as an image.
    bufferlat = (np.amax(coords[:, 0]) - np.amin(coords[:, 0])) + .1
    bufferlon = (np.amax(coords[:, 1]) - np.amin(coords[:, 1])) + .1
    m = Basemap(projection='mill',llcrnrlat=np.amin(coords[:,0])-bufferlat,urcrnrlat=np.amax(coords[:,0])+bufferlat,\
            llcrnrlon=np.amin(coords[:,1])-bufferlon,urcrnrlon=np.amax(coords[:,1])+bufferlon,resolution='i')

    # Draw station coordinates
    x, y = m(coords[:, 1], coords[:, 0])

    # create new figure, axes instance.
    fig = plt.figure()
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    # attach new axes image to existing Basemap instance.
    m.ax = ax
    #im = m.imshow(topodat,cm.GMT_haxby)
    try:
        m.shadedrelief()
    except:
        traceback.print_exc()
    m.scatter(x, y, 50, marker='v', color='r')
    for sta in stations:
        xpt, ypt = m(sta.X, sta.Y)
        plt.text(xpt,
                 ypt,
                 "%s_%s" % (sta.net, sta.sta),
                 fontsize=9,
                 ha='center',
                 va='top',
                 color='k',
                 bbox=dict(boxstyle="square", ec='None', fc=(1, 1, 1, 0.5)))
    # draw coastlines and political boundaries.
    m.drawcoastlines()
    m.drawcountries()
    m.drawstates()
    # draw parallels and meridians.
    # label on left and bottom of map.
    parallels = np.arange(-90, 90, 10.)
    m.drawparallels(parallels, labels=[1, 0, 0, 1])
    meridians = np.arange(0., 360., 10.)
    m.drawmeridians(meridians, labels=[1, 0, 0, 1])
    # add colorbar
    #cb = m.colorbar(im,"right", size="5%", pad='2%')
    ax.set_title('Station map')

    if outfile:
        if outfile.startswith("?"):
            now = datetime.datetime.now()
            now = now.strftime('station map on %Y-%m-%d %H.%M.%S')
            outfile = outfile.replace('?', now)
        print("output to:", outfile)
        plt.savefig(outfile)
    if show:
        plt.show()
        norm2plot = np.sqrt(u2plot * u2plot * v2plot * v2plot)

        # Vorticity
        dux, duy = np.gradient(np.squeeze(u2plot))
        dvx, dvy = np.gradient(np.squeeze(v2plot))
        vort = (dvy / dx - dux / dy) / f

        figsuffix = time.strftime("%Y_%m_%d_%H_%M_%S", time.gmtime(time2plot))
        figtitle = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time2plot))

        if doplotvort == 1:
            # Make the plot
            fig = plt.figure()
            ax = fig.add_subplot(111)

            m.ax = ax

            Q = plt.quiver(
                x[::NN, ::NN],
                y[::NN, ::NN],
                u2plot[::NN, ::NN],
                v2plot[::NN, ::NN],
                vort[::NN, ::NN],
                units="width",
                scale=7.5,
                width=0.003,
                color="k",
                zorder=2,
                cmap=cmap,
                norm=norm2,
            )
Example #42
0
def create_map(lon_min=-180., lon_max=180., lat_min=-90., lat_max=90.,
        projection='cyl', resolution='auto', epsg=None,
        lon_center=None, lat_center=None, lat_ts=None, zoom=None, ax=None,
        overlay=False, fullscreen=False, nocache=False, cache_dir=None, **kwargs):
    """Generic creation of a :class:`Basemap` instance with caching

    .. todo:: Merge :func:`get_map` with :func:`create_map`
    """
    kwmap = kwfilter(kwargs, 'basemap', defaults={'area_thresh':0.})
    kwmap.update(kwfilter(kwargs, 'map_'))

    # Map arguments
    kwargs.setdefault('area_thresh', 0.)
    kwargs.setdefault('rsphere', RSHPERE_WGS84) # WGS-84
    if kwargs['rsphere'] in [None, False, True]: del kwargs['rsphere']
    projection = kwargs.pop('proj', projection)
    if lon_center is None: lon_center = .5*(lon_min+lon_max)
    if lat_center is None: lat_center = .5*(lat_min+lat_max)
    if lat_ts is None: lat_ts = lat_center
    if lon_max-lon_min<1.e-5:
        lon_min = lon_center-1
        lon_max = lon_center+1
    if lat_max-lat_min<1.e-5:
        lat_min = N.clip(lat_center-1, 0, 90)
        lat_max = N.clip(lat_center+1, 0, 90)
    if isinstance(zoom, (int, float)):
        lon_min, lat_min, lon_max, lat_max = zoombox(
            [lon_min, lat_min, lon_max, lat_max], zoom)

    # Special overlay case
    if overlay:
        projection = 'merc'
        resolution = None
        lat_center = 0
        lon_center = 0
    elif projection == None:
        projection = 'cyl'

    # Guess resolution
    res = kwargs.pop('res', resolution)
    if res is True:
        res = 'auto'
    elif res is False or res=='None':
        res = None
    elif isinstance(res, int):
        if res < 0:
            res= 'auto'
        else:
            res = GSHHS_RESLIST[4-res]
    if res == 'auto':
        res = gshhs_autores(lon_min, lon_max, lat_min, lat_max)
    if res in GSHHS_RESLIST:
        kwargs.setdefault('resolution', res)
    else:
        kwargs['resolution'] = None

    # Basemap args
    if isinstance(projection, str) and projection.lower() == 'rgf93' :
        # RGF93
        kwargs.update(lon_0=3, lat_0=46.5, lat_1=44, lat_2=49,
            rsphere=RSHPERE_WGS84, projection='lcc')
    else:
        # standard
        kwargs.setdefault('lon_0', lon_center)
        kwargs.setdefault('lat_0', N.clip(lat_center, -90, 90))
        kwargs.setdefault('lat_1', kwargs['lat_0'])
        kwargs.setdefault('lat_2', kwargs['lat_1'])
        kwargs.setdefault('lat_ts', N.clip(lat_center, -90, 90))
        kwargs.setdefault('projection', projection)
    kwargs.setdefault('llcrnrlon', lon_min)
    kwargs.setdefault('urcrnrlon', lon_max)
    kwargs.setdefault('llcrnrlat', N.clip(lat_min, -90, 90))
    kwargs.setdefault('urcrnrlat', N.clip(lat_max, -90, 90))
    kwargs['epsg'] = epsg

    # Check the cache
    kwcache = kwargs.copy()
    if cache_dir is not None:
        kwcache['mapdir'] = cache_dir
    if not nocache:
        mymap = cached_map(**kwcache)
    else:
        mymap = None

    # Create the map object
    if mymap is None:
        mymap = Basemap(ax=ax, **kwargs)

        # Cache it?
        if int(nocache)<=1:
            if cache_dir is not None:
                kwcache = {'mapdir':cache_dir}
            else:
                kwcache = {}
            cache_map(mymap, **kwcache)
    elif ax is not None:
        mymap.ax = ax
    mymap.res = res
    return mymap
Example #43
0
def mapdap(
    varname = 'hr24_prcp',
    bbox = '-180,-90,180,90',
    url = 'http://opendap.bom.gov.au:8080/thredds/dodsC/PASAP/atmos_latest.nc',
    timeindex = 'Default',
    imgwidth = 256,
    imgheight = 256,
    request = 'GetMap',
    time = 'Default',
    save_local_img = False,
    colorrange = (-4,4),
    palette = 'RdYlGn',
    colorbounds = 'Default',
    style = 'grid',
    ncolors = 10,
    mask = -999,
    plot_mask = True,
    mask_varname = 'mask',
    mask_value = 1.0
    ):
    """ Using Basemap, create a contour plot using some dap available data 
   
        Data is assumed to have dimensions [time,lat,lon] 
            TODO -- deal with other shapes
            TODO -- determine the dimension ordering using CF convention

        varname -- name of variable in opendap file
        bbox -- lonmin,latmin,lonmax,latmax for plot
        url -- OPEnDAP url
        timeindex -- time index to plot
        imgwidth,imgheight -- size of png image to return
        request -- 'GetMap','GetLegend','GetFullFigure'
        time -- time vale to plot. Assumes a particular format."%Y-%m-%dT%H:%M:%S"
        mask -- mask out these values
        if plot_mask is True, mask_varname and mask_value must be given
    
    """
    transparent = True
    lonmin,latmin,lonmax,latmax = tuple([float(a) for a in bbox.rsplit(',')])
   
    # It's not clear there is any point in this. Pydap doesn't actually
    # download data until you subscript 
    
    if url not in cache:
        dset = open_url(url)
    else:
        dset = cache[url]
    
    # Get the correct time.
    time_var = dset['time']
    time_units = time_var.attributes['units']
    available_times = np.array(time_var[:])
    
    

    # TODO there is a potential conflict here between time and timeindex.
    # On the one hand we want to allow using the actual time value.
    # On the other hand we want to make it easy to get a time index
    # without knowing the value.
    timestep=0
    if timeindex == 'Default':
        timestep=0
    else:
        timestep=int(timeindex)
    if time != 'Default':
        dtime = datetime.datetime.strptime(time, "%Y-%m-%dT%H:%M:%S" )
        reftime = date2num(dtime,time_units)
        timestep = np.where(available_times >= reftime)[0].min()

    # TODO Get only the section of the field we need to plot
    # TODO Determine lat/lon box indices and only download this slice

    # TODO Set default range (the below does not work)
    #colorrange = np.min(var),np.max(var)
    
    lat = dset['lat'][:]
    lon = dset['lon'][:]
    
    # CHANGED
    var = dset[varname][timestep,:,:]
 
    #xcoords = lonmin,lonmax
    #xcoords,lon,var = transform_lons(xcoords,lon,var)
 
    # TODO
    # Needs mre thought - the idea here is to only grab a slice of the data
    # Need to grab a slightly larger slice of data so that tiling works.
    #lat_idx = (lat > latmin) & (lat < latmax)
    #lon_idx = (lon > lonmin) & (lon < lonmax)
    #lat = dset['lat'][lat_idx]
    #lon = dset['lon'][lon_idx]
    #latdx1 = np.where(lat_idx)[0].min()
    #latdx2 = np.where(lat_idx)[0].max()
    #londx1 = np.where(lon_idx)[0].min()
    #londx2 = np.where(lon_idx)[0].max()
    #var = var[latdx1:latdx2+1,londx1:londx2+1]
    #var = dset[varname][timestep,latdx1:latdx2+1,londx1:londx2+1]

    # todo clean up this logic
    if 'mask' in dset.keys():
        if plot_mask:
            maskvar = dset['mask'][timestep,:,:]
            #maskvar = dset['mask'][timestep,latdx1:latdx2+1,londx1:londx2+1]
            varm = np.ma.masked_array(var,mask=maskvar)
            mask = varm.mask 
    else:
        varm = np.ma.masked_array(var,mask=np.isinf(var))

    xcoords = lonmin,lonmax
    # Call the trans_coords function to ensure that basemap is asked to
    # plot something sensible.
    xcoords,lon,varm = transform_lons(xcoords,lon,varm)
    lonmin,lonmax = xcoords
    varnc = dset[varname]

    try:
        var_units = varnc.attributes['units']
    except KeyError:
       var_units = '' 


    
    # Plot the data
    # For the basemap drawing we can't go outside the range of coordinates
    # WMS requires us to give an empty (transparent) image for these spurious lats
    
    # uc = upper corner, lc = lower corner
    bmapuclon=lonmax
    bmaplclon=lonmin
    bmapuclat=min(90,latmax)
    bmaplclat=max(-90,latmin)
    if bmaplclat==90:
        bmaplclat = 89.0
    if bmapuclat==-90:
        bmapuclat = -89.0

    # TODO set figsize etc here  
    fig = mpl.figure.Figure()
    canvas = FigureCanvas(fig)
    
    ax = fig.add_axes((0,0,1,1),frameon=False,axisbg='k',alpha=0,visible=False)
    m = Basemap(projection='cyl',resolution='c',urcrnrlon=bmapuclon,
        urcrnrlat=bmapuclat,llcrnrlon=bmaplclon,llcrnrlat=bmaplclat,
        suppress_ticks=True,fix_aspect=False,ax=ax)

    DPI=100.0

    # Convert the latitude extents to Basemap coordinates
    bmaplatmin,bmaplonmin = m(latmin,lonmin)
    bmaplatmax,bmaplonmax = m(latmax,lonmax)
    lon_offset1 = abs(bmaplclon - bmaplonmin)
    lat_offset1 = abs(bmaplclat - bmaplatmin)
    lon_offset2 = abs(bmapuclon - bmaplonmax)
    lat_offset2 = abs(bmapuclat - bmaplatmax)
    lon_normstart = lon_offset1 / abs(bmaplonmax - bmaplonmin)
    lat_normstart = lat_offset1 / abs(bmaplatmax - bmaplatmin)
    ax_xfrac = abs(bmapuclon - bmaplclon)/abs(bmaplonmax - bmaplonmin)
    ax_yfrac = abs(bmapuclat - bmaplclat)/abs(bmaplatmax - bmaplatmin)

    # Set plot_coords, the plot boundaries. If this is a regular WMS request,
    # the plot must fill the figure, with whitespace for invalid regions.
    # If it's a full figure, we need to make sure there is space for the legend
    # and also for the text.
    if request == 'GetFullFigure':
        coords = lonmin,latmin,lonmax,latmax
        plot_coords = figurePlotDims(imgheight,imgwidth,coords)
    else:
        plot_coords = (lon_normstart,lat_normstart,ax_xfrac,ax_yfrac)

    m = Basemap(projection='cyl',resolution='c',urcrnrlon=bmapuclon,
        urcrnrlat=bmapuclat,llcrnrlon=bmaplclon,llcrnrlat=bmaplclat,
        suppress_ticks=True,fix_aspect=False,ax=ax)

    ax = fig.add_axes(plot_coords,frameon=False,axisbg='k')

    m.ax = ax
    varm,lonwrap = addcyclic(varm,lon)
    x,y = m(*np.meshgrid(lonwrap[:],lat[:]))

    """ To plot custom colors
    rgb_cmap = mpl.colors.ListedColormap([  
            (0.0,0.0,0.0),
            (0.25,0.25,0.25),
            (0.3,0.25,0.25),
            (0.5,0.5,0.5),
            (0.6,0.5,0.5),
            (0.75,0.75,0.75),
            (0.75,0.85,0.75),
            (1.0,1.0,1.0) ],name='rgbcm')
    default_color_bounds = [-1,-0.75,-0.5,-0.25,0.0,0.25,0.5,0.75,1.0]
    default_norm = mpl.colors.BoundaryNorm(default_color_bounds, rgb_cmap.N)
    m.contourf(x,y,var,cmap=rgb_cmap,norm=default_norm)
    contours = m.contour(x,y,var,cmap=rgb_cmap,norm=default_norm)
    contours.clabel(colors='k')
    """
    colormap = mpl.cm.get_cmap(palette)
    # colormap = cmap_discretize(colormap,ncolors)
    # if colorbounds = 'Default':
    # colorbounds = list(np.arange(colorrange[0],colorrange[1]+increment,increment))
    # else:
    #    colorbounds = list(np.arange(colorrange[0],colorrange[1]+increment,increment))
    #    Do some checks on the size of the list, and fix if we can
    #    pass

    if style == 'contour':
        # Interpolate to a finer resolution
        # TODO: make this sensitive to the chosen domain
        increment = float(colorrange[1]-colorrange[0]) / float(ncolors-2)
        colorbounds = list(np.arange(colorrange[0],colorrange[1]+increment,increment))
        
        
        # CHANGED
        colormap = cmap_discretize(colormap,ncolors)
        
        colvs =[-999]+colorbounds+[999]
        lat_idx = np.argsort(lat)
        lat = lat[lat_idx]
        varm = varm[lat_idx,:]

        data_lonmin = min(lonwrap)
        data_lonmax = max(lonwrap)
        data_latmin = min(lat)
        data_latmax = max(lat)

        new_lons = np.arange(data_lonmin-1.0,data_lonmax+1.0,1.0)
        new_lats = np.arange(data_latmin-1.0,data_latmax+1.0,1.0)
        newx,newy = m(*np.meshgrid(new_lons[:],new_lats[:]))
        x = newx
        y = newy
        
        # Two pass interpolation to deal with the mask.
        # The first pass does a bilinear, the next pass does a nearest neighbour to keep the mask
        # These steps slow down the plotting significantly
        # It's not clear this is working, and the problem is likely solved by
        # ensuring the right mask is used!
        varm_bl = interp(varm, lonwrap[:], lat[:], newx, newy,order=1)
        varm_nn = interp(varm, lonwrap[:], lat[:], newx, newy,order=0)
        varm = varm_bl
        varm[varm_nn.mask == 1] = varm_nn[varm_nn.mask == 1]

        # contourf has an extent keyword (x0,x1,y0,y1)
        # return "mapdap\n"
        # STUCK it gets stuck here (in apache)        
        main_render = m.contourf(x,y,varm[:,:],colorbounds,extend='both',cmap=colormap,ax=ax)
        
        contours = m.contour(x,y,varm,colorbounds,colors='k',ax=ax)
        contours.clabel(colors='k',rightside_up=True,fmt='%1.1f',inline=True)
        
        
        
    elif style == 'grid':
        main_render = m.pcolormesh(x,y,varm[:,:],vmin=colorrange[0],vmax=colorrange[1],
            cmap=colormap,ax=ax)
    elif style == 'grid_threshold':
        increment = float(colorrange[1]-colorrange[0]) / float(ncolors)
        colorbounds = list(np.arange(colorrange[0],colorrange[1]+increment,increment))
        colornorm = mpl.colors.BoundaryNorm(colorbounds,colormap.N)
        main_render = m.pcolor(x,y,varm[:,:],vmin=colorrange[0],vmax=colorrange[1],
            cmap=colormap,ax=ax,norm=colornorm)
    else:
        main_render = m.pcolormesh(x,y,varm[:,:],vmin=colorrange[0],vmax=colorrange[1],
            cmap=colormap,ax=ax)


    fig.set_dpi(DPI)
    fig.set_size_inches(imgwidth/DPI,imgheight/DPI)

    title_font_size = 9
    tick_font_size = 8
    if request == 'GetFullFigure':
        # Default - draw 5 meridians and 5 parallels
        n_merid = 5
        n_para = 5

        # base depends on zoom
        mint = (lonmax - lonmin)/float(n_merid)
        base = mint
        meridians = [lonmin + i*mint for i in range(n_merid)]
        meridians = [ int(base * round( merid / base)) for merid in meridians]
        
        # Some sensible defaults for debugging
        #meridians = [45,90,135,180,-135,-90,-45]

        pint = int((latmax - latmin)/float(n_para))
        base = pint
        parallels = [latmin + i*pint for i in range(1,n_para+1)] 
        parallels = [ int(base * round( para / base)) for para in parallels]
        #parallels = [-60,-40,-20,0,20,40,60]
        #parallels = [((parallel + 180.) % 360.) - 180. for parallel in parallels]
        m.drawcoastlines(ax=ax)
        
        m.drawmeridians(meridians,labels=[0,1,0,1],fmt='%3.1f',fontsize=tick_font_size)
        m.drawparallels(parallels,labels=[1,0,0,0],fmt='%3.1f',fontsize=tick_font_size)
        m.drawparallels([0],linewidth=1,dashes=[1,0],labels=[0,1,1,1],fontsize=tick_font_size)
        titlex,titley = (0.05,0.98)
        
        # CHANGED 
        # STUCK getting an error somewhere in this function
        # title = get_pasap_plot_title(dset,varname=varname,timestep=timestep)
        title = "We're getting errors in the get title function"
        fig.text(titlex,titley,title,va='top',fontsize=title_font_size)
   
    colorbar_font_size = 8
    if request == 'GetLegendGraphic':
        # Currently we make the plot, and then if the legend is asked for
        # we use the plot as the basis for the legend. This is not optimal.
        # Instead we should be making the legend manually. However we need
        # to set up more variables, and ensure there is a sensible min and max.
        # See the plot_custom_colors code above
        fig = mpl.figure.Figure(figsize=(64/DPI,256/DPI))
        canvas = FigureCanvas(fig)
        # make some axes
        cax = fig.add_axes([0,0.1,0.2,0.8],axisbg='k')
        # put a legend in the axes
        
        
        cbar = fig.colorbar(main_render,cax=cax,extend='both',format='%1.1f')
        cbar.set_label(var_units,fontsize=colorbar_font_size)
        for t in cbar.ax.get_yticklabels():
            t.set_fontsize(colorbar_font_size)
        # i.e. you don't need to plot the figure...
        #fig.colorbar(filled_contours,cax=cax,norm=colornorm,boundaries=colvs,values=colvs,
        #   ticks=colorbounds,spacing='proportional')
    elif request == 'GetFullFigure':
        # Add the legend to the figure itself.
        # Figure layout parameters
        # plot_coords = tuple with (xi,yi,dx,dy)
        # legend_coords = tuple with (xi,yi,dx,dy) as per mpl convention
        # First change the plot coordinates so that they do not cover the whole image
        legend_coords = (0.8,0.1,0.02,plot_coords[3])
        cax = fig.add_axes(legend_coords,axisbg='k')
        cbar = fig.colorbar(main_render,cax=cax,extend='both')
        for t in cbar.ax.get_yticklabels():
            t.set_fontsize(colorbar_font_size)
        cbar.set_label(var_units,fontsize=colorbar_font_size)
        transparent=False
        # Experimenting here with custom color map and ticks. Assigning everything manually
        # (e.g. ticks=[-2,-1,0,1,2]) is easy. Doing it in an automated way given a range is
        # hard...
        #fig.colorbar(filled_contours,cax=cax,boundaries=colvs,ticks=colorbounds)
        #,norm=colornorm,#boundaries=colvs,values=colvs,        #extend='both')
           
    imgdata = StringIO.StringIO()
    fig.savefig(imgdata,format='png',transparent=transparent)
    
    if save_local_img:
        fig.savefig('map_plot_wms_output.png',format='png')
        return

    if url not in cache:
        cache[url] = dset

    value = imgdata.getvalue()

    #imgdata.close()
    fig = None
    
    
    return value
Example #44
0
def compare_3csv():
    dirs = "../result_h/compare_3csv/"
    dirs_A = "../result_h/compare_3csv/A/"
    dirs_theta = "../result_h/compare_3csv/theta/"
    dirs_R2 = "../result_h/compare_3csv/R2/"
    dirs_e2 = "../result_h/compare_3csv/e2/"
    mkdir(dirs_A)
    mkdir(dirs_theta)
    mkdir(dirs_R2)
    mkdir(dirs_e2)

    kw_list = [["A", "A_30_90", "A_30_w_iw"],
               ["theta", "theta_30_90", "theta_w_iw"],
               ["R2", "R2_30_90", "R2_w_iw"],
               ["epsilon2", "epsilon2_30_90", "epsilon2_w_iw"]]
    for i, start in enumerate(start_list):
        print("******************  {}/{}  *******************".format(
            i + 1, M))
        helmert_30_30_fname = "../data/csv_Helmert_30/Helmert_30_" + str(
            start)[:6] + ".csv"
        data_30 = pd.read_csv(helmert_30_30_fname)
        helmert_30_90_fname = "../data/csv_Helmert_ocean_90/Helmert_30_90_" + str(
            start)[:6] + ".csv"
        data_90 = pd.read_csv(helmert_30_90_fname)
        helmert_30_30_w_iw_fname = "../data/csv_Helmert_both_30_w_iw/Helmert_both_30_w_iw_" + str(
            start)[:6] + ".csv"
        data_30_w_iw = pd.read_csv(helmert_30_30_w_iw_fname)

        save_name_list = ["A", "theta", "R2", "e2"]
        for j in range(4):
            data_30_plot = np.array(data_30[kw_list[j][0]])
            data_90_plot = np.array(data_90[kw_list[j][1]])
            data_30_w_iw_plot = np.array(data_30_w_iw[kw_list[j][2]])

            data_list = [data_30_plot, data_90_plot, data_30_w_iw_plot]
            v_lim_list = [[0.025, 0], [180, -180], [1, 0], [None, 0]]
            fig, axes = plt.subplots(1, 3)
            for k in range(3):
                ax = axes[k]
                ax.set_title(kw_list[j][k])
                m = Basemap(lon_0=180,
                            boundinglat=50,
                            resolution='l',
                            projection='npstere')
                m.ax = ax
                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(data_list[k])
                data1 = np.reshape(data, (145, 145), order='F')

                im = m.pcolormesh(xx_ex - dx1,
                                  yy_ex + dy1,
                                  data1,
                                  cmap=plt.cm.jet,
                                  vmax=v_lim_list[j][0],
                                  vmin=v_lim_list[j][1])
                fig.colorbar(im, ax=ax)
                #m.colorbar(location='bottom')
            save_name = dirs + save_name_list[j] + "/" + str(
                start)[:6] + ".png"
            print(save_name)
            plt.savefig(save_name, dpi=750)
            plt.close()
    # Construct year-month-day
    deltatime = dt.datestr2num('1987,1,1') - dt.datestr2num('1970,1,1')
    ttime = time.gmtime((deltatime + (windtime[0] / 24)) * 86400)
    figtitle = str(ttime.tm_year) + '-' + str(ttime.tm_mon) + '-' + str(
        ttime.tm_mday)

    #------------------------------------------------------------------------------------
    # Plot velocity field
    if doplotvel == 1:

        uvnorm = np.sqrt(uwind * uwind + vwind * vwind)

        # Make the plot
        fig = plt.figure()
        ax = fig.add_subplot(111)
        m.ax = ax

        contour = m.contourf(x,
                             y,
                             uvnorm,
                             levels2plot,
                             cmap=cmap,
                             norm=norm,
                             extend='max')
        Q=m.quiver(x,y,uwind,vwind,\
                   width=0.003,color='k')
        k = plt.quiverkey(Q,
                          .95,
                          1.075,
                          10,
                          r'$10\, ms^{-1}$',
Example #46
0
def ocean_30_vs_90():
    dirs = "../result_h/mean_vector/ocean_currents_30_vs_90/"
    mkdir(dirs)

    start_list.pop()
    for i, start in enumerate(start_list):
        print("******************  {}/{}  *******************".format(
            i + 1, M))
        helmert_30_30_fname = "../data/csv_Helmert_30/Helmert_30_" + str(
            start)[:6] + ".csv"
        data_30 = pd.read_csv(helmert_30_30_fname)
        data_30_vec = [
            np.array(data_30["ocean_u"]),
            np.array(data_30["ocean_v"])
        ]
        helmert_90_90_fname = "../data/csv_Helmert_both_90/Helmert_both_90_" + str(
            start)[:6] + ".csv"
        data_90 = pd.read_csv(helmert_90_90_fname)
        data_90_vec = [
            np.array(data_90["ocean_u_90"]),
            np.array(data_90["ocean_v_90"])
        ]
        helmert_30_30_w_iw_fname = "../data/csv_Helmert_both_30_w_iw/Helmert_both_30_w_iw_" + str(
            start)[:6] + ".csv"
        data_30_w_iw = pd.read_csv(helmert_30_30_w_iw_fname)
        data_30_w_iw_vec = [
            np.array(data_30_w_iw["ocean_u_w_iw"]),
            np.array(data_30_w_iw["ocean_v_w_iw"])
        ]

        fig, axes = plt.subplots(1, 3)
        fig.figsize = (6, 9)
        title_list = ["30", "90", "30_w_iw"]
        vector_list = [data_30_vec, data_90_vec, data_30_w_iw_vec]
        for j, title in enumerate(title_list):
            ax = axes[j]
            ax.set_title(title)
            m = Basemap(lon_0=180,
                        boundinglat=50,
                        resolution='l',
                        projection='npstere')
            m.ax = ax
            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

            vector_u = np.ma.masked_invalid(vector_list[j][0])
            vector_v = np.ma.masked_invalid(vector_list[j][1])
            vector_speed = np.sqrt(vector_u * vector_u + vector_v * vector_v)

            data_non_wind = vector_speed
            data_non_wind = np.ma.masked_invalid(data_non_wind)
            data1 = np.reshape(data_non_wind, (145, 145), order='F')

            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
            ])

            m.pcolormesh(xx_ex - dx1,
                         yy_ex + dy1,
                         data1,
                         cmap=plt.cm.jet,
                         vmax=0.2,
                         vmin=0)
            #m.colorbar(location='bottom')
            m.quiver(x, y, vector_u, vector_v, color="k")
        save_name = dirs + str(start)[:6] + ".png"
        print(save_name)
        plt.savefig(save_name, dpi=750)
        plt.close()
        print("\n")
def plot_wind_sat_interp(windfiles, domain, lon, lat, uwind, vwind, windtime, figdir, m):

    import os
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.dates as dt
    import time

    from matplotlib  import colors
    from mpl_toolkits.basemap import Basemap

    figname = os.path.basename(windfiles)[:-3].replace('.','_')

    cdict = {'red': ((0.0, 1.0, 1.0),
                 (0.5, 1.0, 1.0),
                 (1.0, 0.0, 0.0)),
         'green': ((0.0, 1.0, 1.0),
                   (0.5, .0, 0.0),
                   (1.0, 0.0, 0.0)),
         'blue': ((0.0, 0.20, 0.2),
                  (0.5, 0.0, 0.0),
                  (1.0, 0.0, 0.0))}

    cmap = colors.LinearSegmentedColormap('my_colormap',cdict,256)
    cmapvort = plt.cm.RdBu_r
    vmin = 0.
    vmax = 15.
    dvar=2.5

    deltatime=(dt.datestr2num('1990,1,1')-dt.datestr2num('1970,1,1'))*86400

    bounds = np.arange(vmin,vmax+0.01,dvar)
    norm = colors.Normalize(vmin=vmin,vmax=vmax+0.001)
    normvort = colors.Normalize(vmin=-1.,vmax=1.0)
    meridians=np.arange(np.ceil(domain[0]),domain[1],domain[4])
    parallels=np.arange(domain[2],domain[3],domain[5])

    m = Basemap(projection='merc',llcrnrlon=domain[0],llcrnrlat=domain[2]+0.1,
                urcrnrlon=domain[1],urcrnrlat=domain[3],
                lat_ts=0.5*(domain[2]+domain[3]),
                resolution='l')

    # Wind norm (should be same as windspeed)
    windnorm=np.sqrt(uwind*uwind+vwind*vwind)

    x,y=m(lon,lat)

    # Make the plot
    fig=plt.figure()
    ax = fig.add_subplot(111)
    m.ax=ax

    # Wind curl
    f = 4*(np.pi/86400)*np.sin(np.deg2rad(0.5*(domain[2] * domain[3])))

    dx = np.gradient(x)
    dy = np.gradient(y)
    dux, duy = np.gradient(uwind)
    dvx, dvy = np.gradient(vwind)
    vort = (dvy / dx - dux / dy) / f

    Q=m.quiver(x, y, uwind, vwind, vort,
               units='width', scale=400, width=0.0015, norm=normvort, cmap=cmapvort)

    m.drawparallels(parallels, linewidth=0.0, labels=[1, 0, 0, 0], fontsize=16)
    m.drawmeridians(meridians, linewidth=0.0, labels=[0, 0, 0, 1], fontsize=16)

    m.fillcontinents(color="w", ax=ax, zorder=2)

    # Add the colorbar
    cbar=fig.colorbar(Q,cmap=cmap, orientation='vertical',
                      pad=0.025, aspect=15, shrink=1., norm=norm, extend='both')
    ax.annotate(r'($ms^{-1}$)', xy=(0.98, 1.03), xycoords='axes fraction')
    cbar.set_ticks(bounds)
    cbar.ax.set_yticklabels(bounds,fontsize=16)


    ## Export figure and display it
    plt.savefig(figdir+figname, dpi=300, facecolor='w', edgecolor='w',
             transparent=False, bbox_inches='tight', pad_inches=0.1)
    #plt.show()
    plt.close()
Example #48
0
    def make_grid_animation(self, FPS, DPI, zminmax=None, doBasemap=False):

        save_file = self.save_file_prefix + "_grid.mp4"

        # Keep the data from each time step in netCDF variable form, and slice into it as needed
        level_ncVar = self.sim_data.variables['level']
        height_ncVar = self.sim_data.variables['height']
        alt_ncVar = self.sim_data.variables['altitude']

        # Get ranges
        N_STEP = len(self.times)
        z_min = np.inf
        z_max = -np.inf
        z_avs = []
        for i, levelstep in enumerate(level_ncVar):
            masked_data = np.ma.masked_where(height_ncVar[i] == 0.0000,
                                             levelstep)
            z_min = min(masked_data.min(), z_min)
            z_max = max(masked_data.max(), z_max)
            z_avs.append(masked_data.mean())

        z_max = np.max(
            np.ma.masked_where(height_ncVar[0] == 0.0000, level_ncVar[0]))

        print("min: {}, max: {}, av: {}".format(z_min, z_max,
                                                np.array(z_avs).mean()))
        if (zminmax != None): z_min, z_max = zminmax

        # Initialize movie writing stuff
        FFMpegWriter = manimation.writers['ffmpeg']
        metadata = dict(title='TsunamiSquares',
                        artist='Matplotlib',
                        comment='Animation')
        writer = FFMpegWriter(fps=FPS, metadata=metadata, bitrate=1000)

        # Initialize the frame and axes
        fig = plt.figure()

        if not doBasemap:
            ax = fig.add_subplot(111)
            plt.xlim(self.minlon, self.maxlon)
            plt.ylim(self.minlat, self.maxlat)
            #ax.get_xaxis().get_major_formatter().set_useOffset(False)
            #ax.get_yaxis().get_major_formatter().set_useOffset(False)
        else:
            m = Basemap(projection='cyl',
                        llcrnrlat=self.minlat,
                        urcrnrlat=self.maxlat,
                        llcrnrlon=self.minlon,
                        urcrnrlon=self.maxlon,
                        lat_0=self.meanlat,
                        lon_0=self.meanlon,
                        resolution='h')
            m.drawmeridians(np.linspace(self.minlon, self.maxlon, num=5.0),
                            labels=[0, 0, 0, 1],
                            linewidth=0)
            m.drawparallels(np.linspace(self.minlat, self.maxlat, num=5.0),
                            labels=[1, 0, 0, 0],
                            linewidth=0)
            m.drawcoastlines(linewidth=0.5)
            m.ax = fig.add_subplot(111)
            ax = m.ax

        # Colorbar
        cmap = plt.get_cmap('Blues_r')
        landcolor = 'orange'  #'black'#'#FFFFCC'
        cmap.set_bad(landcolor, 1.0)

        norm = mcolor.Normalize(vmin=z_min, vmax=z_max)
        divider = make_axes_locatable(ax)
        cbar_ax = divider.append_axes("right", size="5%", pad=0.05)

        cb = mcolorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=norm)
        framelabelfont = mfont.FontProperties(style='normal',
                                              variant='normal',
                                              size=14)
        plt.figtext(0.95,
                    0.7,
                    r'water altitude $[m]$',
                    rotation='vertical',
                    fontproperties=framelabelfont)

        surface = None
        with writer.saving(fig, save_file, DPI):
            for index in range(int(N_STEP)):
                # Get the subset of data corresponding to current time
                this_level = level_ncVar[index]
                this_height = height_ncVar[index]
                this_alt = alt_ncVar[index]
                time = self.times[index]

                # Masked array via conditional, don't color the land unless it has water on it
                masked_data = np.ma.masked_where(this_height == 0.0000,
                                                 this_level)

                print("step: {}  time: {}".format(index, time))

                # Plot the surface for this time step
                if surface is None:
                    ax.imshow(masked_data,
                              cmap=cmap,
                              origin='lower',
                              norm=norm,
                              extent=[
                                  self.minlon, self.maxlon, self.minlat,
                                  self.maxlat
                              ],
                              interpolation='none')
                else:
                    surface.set_data(masked_data)

                # Text box with the time
                plt.figtext(0.02,
                            0.5,
                            'Time: {:02d}:{:02d}'.format(
                                int(time / 60), int(time % 60)),
                            bbox={
                                'facecolor': 'yellow',
                                'pad': 5
                            })

                writer.grab_frame()
Example #49
0
def draw_contour_map(dataset, lats, lons, fname, fmt='png', gridshape=(1, 1),
                     clabel='', ptitle='', subtitles=None, cmap=None,
                     clevs=None, nlevs=10, parallels=None, meridians=None,
                     extend='neither', aspect=8.5/2.5):
    '''
    Purpose::
        Create a multiple panel contour map plot.

    Input::
        dataset -  3d array of the field to be plotted with shape (nT, nLon, nLat)
        lats - array of latitudes
        lons - array of longitudes
        fname  - a string specifying the filename of the plot
        fmt  - an optional string specifying the filetype, default is .png
        gridshape - optional tuple denoting the desired grid shape (nrows, ncols) for arranging
                    the subplots.
        clabel - an optional string specifying the colorbar title
        ptitle - an optional string specifying plot title
        subtitles - an optional list of strings specifying the title for each subplot
        cmap - an string or optional matplotlib.colors.LinearSegmentedColormap instance
               denoting the colormap
        clevs - an optional list of ints or floats specifying contour levels
        nlevs - an optional integer specifying the target number of contour levels if
                clevs is None
        parallels - an optional list of ints or floats for the parallels to be drawn
        meridians - an optional list of ints or floats for the meridians to be drawn
        extend - an optional string to toggle whether to place arrows at the colorbar
             boundaries. Default is 'neither', but can also be 'min', 'max', or
             'both'. Will be automatically set to 'both' if clevs is None.
    '''
    # Handle the single plot case. Meridians and Parallels are not labeled for
    # multiple plots to save space.
    if dataset.ndim == 2 or (dataset.ndim == 3 and dataset.shape[0] == 1):
        if dataset.ndim == 2:
            dataset = dataset.reshape(1, *dataset.shape)
        mlabels = [0, 0, 0, 1]
        plabels = [1, 0, 0, 1]
    else:
        mlabels = [0, 0, 0, 0]
        plabels = [0, 0, 0, 0]

    # Make sure gridshape is compatible with input data
    nplots = dataset.shape[0]
    gridshape = _best_grid_shape(nplots, gridshape)

    # Set up the figure
    fig = plt.figure()
    fig.set_size_inches((8.5, 11.))
    fig.dpi = 300

    # Make the subplot grid
    grid = ImageGrid(fig, 111,
                     nrows_ncols=gridshape,
                     axes_pad=0.3,
                     share_all=True,
                     add_all=True,
                     ngrids=nplots,
                     label_mode='L',
                     cbar_mode='single',
                     cbar_location='bottom',
                     cbar_size=.15,
                     cbar_pad='0%'
                     )

    # Determine the map boundaries and construct a Basemap object
    lonmin = lons.min()
    lonmax = lons.max()
    latmin = lats.min()
    latmax = lats.max()
    m = Basemap(projection = 'cyl', llcrnrlat = latmin, urcrnrlat = latmax,
                llcrnrlon = lonmin, urcrnrlon = lonmax, resolution = 'l')

    # Convert lats and lons to projection coordinates
    if lats.ndim == 1 and lons.ndim == 1:
        lons, lats = np.meshgrid(lons, lats)

    # Calculate contour levels if not given
    if clevs is None:
        # Cut off the tails of the distribution
        # for more representative contour levels
        clevs = _nice_intervals(dataset, nlevs)
        extend = 'both'

    cmap = plt.get_cmap(cmap)

    # Create default meridians and parallels. The interval between
    # them should be 1, 5, 10, 20, 30, or 40 depending on the size
    # of the domain
    length = max((latmax - latmin), (lonmax - lonmin)) / 5
    if length <= 1:
        dlatlon = 1
    elif length <= 5:
        dlatlon = 5
    else:
        dlatlon = np.round(length, decimals = -1)
    if meridians is None:
        meridians = np.r_[np.arange(0, -180, -dlatlon)[::-1], np.arange(0, 180, dlatlon)]
    if parallels is None:
        parallels = np.r_[np.arange(0, -90, -dlatlon)[::-1], np.arange(0, 90, dlatlon)]

    x, y = m(lons, lats)
    for i, ax in enumerate(grid):
        # Load the data to be plotted
        data = dataset[i]
        m.ax = ax

        # Draw the borders for coastlines and countries
        m.drawcoastlines(linewidth=1)
        m.drawcountries(linewidth=.75)

        # Draw parallels / meridians
        m.drawmeridians(meridians, labels=mlabels, linewidth=.75, fontsize=10)
        m.drawparallels(parallels, labels=plabels, linewidth=.75, fontsize=10)

        # Draw filled contours
        cs = m.contourf(x, y, data, cmap=cmap, levels=clevs, extend=extend)

        # Add title
        if subtitles is not None:
            ax.set_title(subtitles[i], fontsize='small')

    # Add colorbar
    cbar = fig.colorbar(cs, cax=ax.cax, drawedges=True, orientation='horizontal', extendfrac='auto')
    cbar.set_label(clabel)
    cbar.set_ticks(clevs)
    cbar.ax.tick_params(labelsize=6)
    cbar.ax.xaxis.set_ticks_position('none')
    cbar.ax.yaxis.set_ticks_position('none')

    # This is an ugly hack to make the title show up at the correct height.
    # Basically save the figure once to achieve tight layout and calculate
    # the adjusted heights of the axes, then draw the title slightly above
    # that height and save the figure again
    fig.savefig(TemporaryFile(), bbox_inches='tight', dpi=fig.dpi)
    ymax = 0
    for ax in grid:
        bbox = ax.get_position()
        ymax = max(ymax, bbox.ymax)

    # Add figure title
    fig.suptitle(ptitle, y=ymax + .06, fontsize=16)
    fig.savefig('%s.%s' %(fname, fmt), bbox_inches='tight', dpi=fig.dpi)
    fig.clf()
Example #50
0
def Draw_China_Map(Region,title1,levfile='',b_showimg=0,imgfile='tmp1.png',b_show_ss=0,b_show_site=0,b_cnfont=1):
    '''
    Setup: Generate data...
    '''
    nx, ny = 100,120
    #RegionR = np.loadtxt('1971_2010_45_12_1_TA.txt')
    #RegionR = np.loadtxt(filename)
    #Region = RegionR[1:,:]
    #shapeR = np.shape(Region)

    #if(shapeR[1]>3):
    #    x,y,z = Region[:,1],Region[:,2],Region[:,3]

    #if(3==shapeR[1]):
    x,y,z = Region[:,0],Region[:,1],Region[:,2]

    #
    xmin,xmax,ymin,ymax = 73.6,134.7,16.2,54.0
    #xmin,xmax,ymin,ymax = 100.0,134.7,16.2,30.0

    x1 = np.linspace(xmin, xmax, nx)
    y1 = np.linspace(ymin, ymax, ny)

    print('lontlatbox=',x.min(),x.max(),y.min(),y.max())
    print(x1.shape,y1.shape)

    #离散点插值到网格
    # mytic()
    # if np.size(x)>350 :
    #     #zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='Invdisttree')#Invdisttree
    #     zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='griddata')#Invdisttree
    # else:
    #     zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='Invdisttree')#Invdisttree
    #     #zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='griddata')#Invdisttree
    #     #zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='nearest')#Invdisttree
    # mytoc(u'离散点插值到网格')
    # #重要

    #平滑插值

    if(0):
        mytic()
        zi,xi,yi,x1,y1,nx,ny=dgrid.extened_grid(zi,x1,y1,zoom=6)
        #print(zi.ravel())
        #sys.exit(0)
        mytoc(u'扩展矩阵插值: ')
        #sys.exit(0)

    #获取mask矩阵

    # mytic()
    # grid1 = dgrid.build_inside_mask_array( \
    #     os.path.join(Spatial_Data,r"china_province"),x1,y1) #shapes
    # grid1,shapes = dgrid.build_inside_mask_array(r"spatialdat\CJ_BOUND",x1,y1)
    # mytoc(u'mask非绘图区域')
    # zi[np.logical_not(grid1)]=np.NaN

    #-----------------------------------------------------------------------------------
    fig = plt.figure(figsize=(12, 9), dpi=100)
    ax1 = fig.add_axes([0.1,0.1,0.8,0.8])
    #原始的中国区域
    #m = Basemap(llcrnrlon=86,llcrnrlat=13.5,urcrnrlon=140,urcrnrlat=51, \
    #            projection='lcc',lon_0=110,lat_0=30.0,lat_1=60.0,resolution='l') #resolution=None

    #新的调试
    m = Basemap(llcrnrlon=86,llcrnrlat=13.5,urcrnrlon=146.5,urcrnrlat=51, \
            projection='lcc',lon_0=110,lat_0=30.0,lat_1=60.0,resolution='l') #resolution=None

    #resolution == 'c':
    #resolution == 'l':
    #resolution == 'i':
    #resolution == 'h':
    #resolution == 'f':


    m.ax=ax1
    m.drawparallels(np.arange(20,71,10),labels=[0,1,0,1],linewidth=0.2, fontsize=8)
    m.drawmeridians(np.arange(80,131,10),labels=[0,1,0,1,0,1],linewidth=0.2, fontsize=8)
    m.drawcoastlines(linewidth=0.2)
    #m.drawcountries(linewidth=0.2)
    #m.drawmapboundary()

    mytic()
    dgrid.draw_map_lines(m,os.path.join(Spatial_Data,"china_province"))
    mytoc(u'画省界')

    mytic()
    dgrid.draw_map_lines(m,os.path.join(Spatial_Data,"huanghe_ganliu"),color='b',linewidth=1.0)
    mytoc(u'画黄河干流: ')

    mytic()
    dgrid.draw_map_lines(m,os.path.join(Spatial_Data,"CJ_LVL1_RIVER"),color='b',linewidth=1.0)
    mytoc(u'画长江干流: ')
    mytic()
    plt.show()
    #mytic()
    #dgrid.draw_map_lines(m,r"spatialdat\CJ_BOUND",color='k',linewidth=1.0)
    #dgrid.draw_map_lines(m,r"spatialdat\CJ_BOUND",color='g',linewidth=0.50)
    #mytoc(u'画长江')

    mytic()
    xi, yi = m(xi,yi)
    #lev = [-150, -100, -50, -20, 0 ,20, 50, 100, 200]
    #lev = [-3.,-2., -1., -0.5,  0. ,0.5, 1., 2., 3.]
    #maplev = np.loadtxt('maplev_TA.txt')

    print('levfile=',levfile)
    if( os.path.isfile(levfile)):
        #maplev = np.loadtxt('maplev_RAP.lev')
        maplev = np.loadtxt(levfile)
        cmap2 = maplev[:,:-1]
        cmap2 = cmap2/255.0
        lev = maplev[:,-1]
        #print(cmap2)
        #cax = m.contourf(xi,yi,zi,colors=cmap2,levels=lev,extend='both')#plt.cm.jet,
        cax = m.contourf(xi,yi,zi,colors=cmap2,levels=lev,extend='both')#plt.cm.jet, #max
        CS = m.contour(xi,yi,zi,levels=lev,linewidths=0.5,colors='k')
    else:
        #---------------------------------------------------
        #cax = m.contourf(xi,yi,zi,cmap=plt.cm.gist_ncar)
        #CS = m.contour(xi,yi,zi,linewidths=0.5,colors='k')
        #---------------------------------------------------
        lev = np.arange(-1,17)+0.5
        #print('cccccccccccccccccccccc')
        #print(xi.shape,yi.shape,zi.shape)
        #print(zi)

        cax = m.contourf(xi,yi,zi,cmap=plt.cm.spectral)#,extend='both')#plt.cm.jet, ,levels=lev
        #CS = m.contour(xi,yi,zi,levels=lev,linewidths=0.5,colors='k')
        CS = m.contour(xi,yi,zi,linewidths=.6,colors='k')  #,levels=lev
        #---------------------------------------------------
        #im1 = m.pcolor(xi,yi,zi,shading='flat',cmap=plt.cm.jet, norm=plt.Normalize(0,17))
        #cb = m.colorbar(im1,"bottom", size="5%", pad="2%")
        #m.pcolor(xi,yi,zi)#,cmap=plt.cm.spectral)
        #m.imshow(zi)


        #---------------------------------------------------
        #m.imshow(zi, interpolation='nearest')
        #m.pcolormesh(xi,yi,zi)

    #l, b, w, h = pos.bounds
    #cax = plt.axes([l+w+0.075, b, 0.05, h]) # setup colorbar axes
    #plt.colorbar(drawedges=True, cax=cax)
    plt.colorbar(cax,shrink=0.6)#orientation='vertical',shrink=0.6,ticks=lev)#,drawedges=True,
    #plt.colorbar(ax=ax1)



    plt.clabel(CS, fmt='%4.1f',inline=1,fontsize=8)  #inline 为等值线标注值周围的间隔

    #print(x,y)
    x,y = m(x,y)  #变换为proj.4
    #print(x,y)
    #sys.exit(0)
    #m.plot(x,y,c=z,s=10,markeredgewidth=0.1)

    import dclimate as dclim
    cnfont = dclim.GetCnFont()
    if(b_show_site):
        m.scatter(x,y,s=4,lw=0)
        for ii in range(len(x)):
            #plt.text(x[ii],y[ii],'%f'%z[ii],fontsize=5)
            str1 = '%d'%z[ii];
            #print(str1)
            #plt.text(x[ii],y[ii],'1',fontsize=8)
            if b_cnfont:
                plt.text(x[ii],y[ii],str1,fontsize=6,fontproperties=cnfont)
            else:
                plt.text(x[ii],y[ii],str1,fontsize=4)


    #m.plot(x,y,'o',markeredgewidth=0.1)

    #plt.title(ptitle,y=1.075, fontproperties=cnfont)


    if b_cnfont :

        cnfont = dclim.GetCnFont()
        #plt.title(ptitle,y=1.075, fontproperties=cnfont)
        plt.title(title1, fontproperties=cnfont,size=16)
    else:
        plt.title(title1,size=16)


    #麦卡托投影哦
    pos = ax1.get_position()
    #print(pos)
    mytoc(u'正式绘图')

    if(b_show_ss):
        ax2 = fig.add_axes([0.5866,0.1482,0.2,0.2])
        m2 = Basemap(projection='cyl',llcrnrlat=4,urcrnrlat=25, \
                     llcrnrlon=107,urcrnrlon=122,resolution='h',ax=ax2)
        #sf = shapefile.Reader(r"spatialdat\Export_Output_12")
        mytic()
        southsea_file = os.path.join(Spatial_Data,"Export_Output_12")
        print(southsea_file)
        df.draw_map_lines(m2,southsea_file,linewidth=0.5)
        mytoc(u'画南海')
        #sys.exit(0)


    if(0):
        ax2 = fig.add_axes([0.0533,0.1393,0.2,0.2])
        m2 = Basemap(projection='cyl',llcrnrlat=4,urcrnrlat=25, \
                     llcrnrlon=107,urcrnrlon=122,resolution='h',ax=ax2)
        #sf = shapefile.Reader(r"spatialdat\Export_Output_12")
        mytic()
        dgrid.draw_map_lines(m2,os.path.join(Spatial_Data,"Export_Output_12"),linewidth=0.5)
        mytoc(u'画南海')

    #plt.colorbar()
    print(imgfile)
    plt.savefig(imgfile)
    #plt.savefig('tmp1.pdf')
    df.CutPicWhiteBorder(imgfile)

    #plt.savefig('03.pdf')
    #plt.savefig('03.ps')
    #plt.savefig('03.svg')
    if(b_showimg):
        plt.show()
    plt.close()
    mytoc(u'绘图所耗时间')
Example #51
0
def main(show=True, outfile=None):
    db = connect()
    stations = get_stations(db, all=False)
    coords = [(sta.Y, sta.X) for sta in stations]
    coords = np.array(coords)

    sta_map = folium.Map(location=[np.mean(coords[:, 0]),
                                   np.mean(coords[:, 1])],
                         zoom_start=3, tiles='OpenStreetMap')
    folium.RegularPolygonMarker(location=[np.mean(coords[:, 1]),
                                          np.mean(coords[:, 0])]).\
        add_to(sta_map)
    for sta in stations:
        folium.RegularPolygonMarker(location=[sta.Y, sta.X],
                                    popup="%s_%s" % (sta.net, sta.sta),
                                    fill_color='red',
                                    number_of_sides=3,
                                    radius=12).add_to(sta_map)

    sta_map.add_child(folium.LatLngPopup())
    if outfile:
        tmp = outfile
        if outfile.startswith("?"):
            now = datetime.datetime.now()
            now = now.strftime('station map on %Y-%m-%d %H.%M.%S')
            tmp = outfile.replace('?', now)
        logging.debug("output to:", tmp)
        sta_map.save('%s.html' % tmp)

    # plot topography/bathymetry as an image.
    bufferlat = (np.amax(coords[:, 0])-np.amin(coords[:, 0]))+.1
    bufferlon = (np.amax(coords[:, 1])-np.amin(coords[:, 1]))+.1
    m = Basemap(projection='mill', llcrnrlat=np.amin(coords[:, 0])-bufferlat,
                urcrnrlat=np.amax(coords[:, 0])+bufferlat,
                llcrnrlon=np.amin(coords[:, 1])-bufferlon,
                urcrnrlon=np.amax(coords[:, 1])+bufferlon, resolution='i')

    # Draw station coordinates
    x, y = m(coords[:, 1], coords[:, 0])

    # create new figure, axes instance.
    fig = plt.figure()
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    # attach new axes image to existing Basemap instance.
    m.ax = ax
    try:
        m.shadedrelief()
    except:
        traceback.print_exc()
    m.scatter(x, y, 50, marker='v', color='r')
    for sta in stations:
        xpt, ypt = m(sta.X, sta.Y)
        plt.text(xpt, ypt, "%s_%s" % (sta.net, sta.sta), fontsize=9,
                 ha='center', va='top', color='k',
                 bbox=dict(boxstyle="square", ec='None', fc=(1, 1, 1, 0.5)))
    # draw coastlines and political boundaries.
    m.drawcoastlines()
    m.drawcountries()
    m.drawstates()
    # draw parallels and meridians.
    # label on left and bottom of map.
    parallels = np.arange(-90, 90, 10.)
    m.drawparallels(parallels, labels=[1, 0, 0, 1])
    meridians = np.arange(0., 360., 10.)
    m.drawmeridians(meridians, labels=[1, 0, 0, 1])
    # add colorbar
    ax.set_title('Station map')

    if outfile:
        if outfile.startswith("?"):
            now = datetime.datetime.now()
            now = now.strftime('station map on %Y-%m-%d %H.%M.%S')
            outfile = outfile.replace('?', now)
        logging.info("output to:", outfile)
        plt.savefig(outfile)
    if show:
        plt.show()
Example #52
0
lat = np.linspace(41.8, 42.4, 10)
lon = np.linspace(-70.15, -70.75, 10)

#CL=np.genfromtxt(FN,names=['lon','lat'])
#axes3.plot(CL['lon'],CL['lat'])
#axes3.axis([-70.94,-70.0,41.52659,42.562711])
axes1.scatter(lon, lat, s=7, color='green')
for a in np.arange(len(lon)):
    axes1.text(lon[a] + 0.02, lat[a], dian[a], fontsize=12)
#axes3.xaxis.tick_top()
m = Basemap(projection='cyl',llcrnrlat=41.5,urcrnrlat=42.5,\
            llcrnrlon=-70.94,urcrnrlon=-70.0,resolution='h')#,fix_aspect=False)
#  draw coastlines
m.drawcoastlines(color='black')
m.ax = axes1
m.fillcontinents(color='grey', alpha=1, zorder=2)
m.drawmapboundary()
#draw major rivers
#m.drawrivers()
parallels = np.arange(41.5, 42.5, 0.1)
m.drawparallels(parallels,
                labels=[1, 0, 0, 0],
                dashes=[1, 1000],
                fontsize=10,
                zorder=0)
meridians = np.arange(-70.94, -70.0, 0.2)
m.drawmeridians(meridians,
                labels=[0, 0, 0, 1],
                dashes=[1, 1000],
                fontsize=10,
Example #53
0
def Draw_China_Split(filename,title1,b_show_ss=0,levfile='',b_showimg=0,imgfile='tmp1.png',b_cnfont=1,cluster_num=4,projtype=1):
    '''
    Setup: Generate data...
    '''
    nx, ny = 400*1.5,480*1.5
    #RegionR = np.loadtxt('1971_2010_45_12_1_TA.txt')
    RegionR = np.loadtxt(filename)
    Region = RegionR[1:,:]
    shapeR = np.shape(Region)
    
    if(shapeR[1]>3):
        x,y,z = Region[:,1],Region[:,2],Region[:,3]

    if(3==shapeR[1]):
        x,y,z = Region[:,0],Region[:,1],Region[:,2]


    #
    xmin,xmax,ymin,ymax = 73.6,134.7,16.2,54.0
    #xmin,xmax,ymin,ymax = 100.0,134.7,16.2,30.0

    x1 = np.linspace(xmin, xmax, nx)
    y1 = np.linspace(ymin, ymax, ny)

    print('lontlatbox=',x.min(),x.max(),y.min(),y.max())
    print(x1.shape,y1.shape)

    #离散点插值到网格
    mytic()
    if np.size(x)>350 :
        #zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='Invdisttree')#Invdisttree
        zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='nearest')#Invdisttree
    else:
        #zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='line_rbf2')#Invdisttree
        #zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='griddata')#Invdisttree
        zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='nearest')#Invdisttree
        zi.round()
    mytoc(u'离散点插值到网格')
    #重要

    #平滑插值
    np.savetxt('Z.txt',zi,fmt='%02d')

    if(0):
        mytic()
        zi,xi,yi,x1,y1,nx,ny=dgrid.extened_grid(zi,x1,y1,zoom=2)
        zi=zi.round()
        #print(zi.ravel())
        #sys.exit(0)
        mytoc(u'扩展矩阵插值: ')
        #sys.exit(0)

    #获取mask矩阵

    mytic()
    grid1 = dgrid.build_inside_mask_array(\
        os.path.join(Spatial_Data,r"china_province"),x1,y1) #shapes
    #grid1,shapes = dgrid.build_inside_mask_array(r"spatialdat\CJ_BOUND",x1,y1)
    mytoc(u'mask非绘图区域')
    zi[np.logical_not(grid1)]=np.NaN

    #-----------------------------------------------------------------------------------
    fig = plt.figure(figsize=(12, 9), dpi=100)
    ax1 = fig.add_axes([0.1,0.1,0.8,0.8])

    #lcc 蓝波托投影
    if(1==projtype):
        m = Basemap(llcrnrlon=86,llcrnrlat=13.5,urcrnrlon=140,urcrnrlat=51,\
            projection='lcc',lon_0=110,lat_0=30.0,lat_1=60.0,resolution='l') #resolution=None
        m.drawparallels(np.arange(20,71,10),labels=[0,1,0,1],linewidth=0.2, fontsize=8)
        m.drawmeridians(np.arange(80,135,10),labels=[0,1,0,1,0,1],linewidth=0.2, fontsize=8)

    #Equidistant Cylindrical Projection 等距圆柱投影 CYL
    if(2==projtype):
        m = Basemap(projection='cyl',llcrnrlat=17,urcrnrlat=55, \
                    llcrnrlon=72,urcrnrlon=136,resolution='l')
        m.drawparallels(np.arange(20,75,5),labels=[0,1,0,1],linewidth=0.2, fontsize=8)
        m.drawmeridians(np.arange(80,135,5),labels=[0,1,0,1,0,1],linewidth=0.2, fontsize=8)


#resolution == 'c':
    #resolution == 'l':
    #resolution == 'i':
    #resolution == 'h':
    #resolution == 'f':


    m.ax=ax1

    m.drawcoastlines(linewidth=0.5)

    #m.drawcoastlines()
    #m.drawcountries(linewidth=0.2)
#    m.maskoceans()
    m.drawmapboundary()
    
    # mytic()
    # dgrid.draw_map_lines(m,'spatialdat/CJ_BOUND.shp')#os.path.join(Spatial_Data,"china_province")
    # mytoc(u'画省界')
    #
    # mytic()
    # dgrid.draw_map_lines(m,os.path.join(Spatial_Data,"huanghe_ganliu"),color='b',linewidth=1.0)
    # mytoc(u'画黄河干流: ')
    #
    # mytic()
    # dgrid.draw_map_lines(m,os.path.join(Spatial_Data,"CJ_LVL1_RIVER"),color='b',linewidth=1.0)
    # mytoc(u'画长江干流: ')
    # mytic()

    #mytic()
    #dgrid.draw_map_lines(m,r"spatialdat\CJ_BOUND",color='k',linewidth=1.0)
    #dgrid.draw_map_lines(m,r"spatialdat\CJ_BOUND",color='g',linewidth=0.50)
    #mytoc(u'画长江')

    mytic()
    xi, yi = m(xi,yi)
    #lev = [-150, -100, -50, -20, 0 ,20, 50, 100, 200]
    #lev = [-3.,-2., -1., -0.5,  0. ,0.5, 1., 2., 3.]
    #maplev = np.loadtxt('maplev_TA.txt')


    if( os.path.isfile(levfile)):
        #maplev = np.loadtxt('maplev_RAP.lev')
        maplev = np.loadtxt(levfile)
        cmap2 = maplev[:,:-1]
        cmap2 = cmap2/255.0
        lev = maplev[:,-1]
        #print(cmap2)
        cax = m.contourf(xi,yi,zi,colors=cmap2,levels=lev)#,extend='both')#plt.cm.jet,
        CS = m.contour(xi,yi,zi,levels=lev,linewidths=0.5,colors='k')
    else:
        #---------------------------------------------------
        #cax = m.contourf(xi,yi,zi,cmap=plt.cm.gist_ncar)
        #CS = m.contour(xi,yi,zi,linewidths=0.5,colors='k')
        #---------------------------------------------------
        lev = np.arange(1,cluster_num+1)+0.5
        '''
        for ii in range(1,12):
            xi2 = np.where(zi==ii,xi,np.nan)
            yi2 = np.where(zi==ii,yi,np.nan)
            zi2 = np.where(zi==ii,zi,np.nan)

            #cax = m.contourf(xi2,yi2,zi2,cmap=plt.cm.spectral,levels=lev)#,extend='both')#plt.cm.jet,
            #CS = m.contour(xi,yi,zi,levels=lev,linewidths=0.5,colors='k')
            CS = m.contour(xi2,yi2,zi2,levels=lev,linewidths=.6,colors='k')
            #CS = m.contour(xi2,yi2,zi2,contours=1)
            #cs = m.pcolor(xi2,yi2,zi2, norm=plt.Normalize(0,17))
        #plt.colorbar(cax,shrink=0.6)
        '''
        #---------------------------------------------------
        #im1 = m.pcolor(xi,yi,zi,shading='flat',cmap=plt.cm.jet, norm=plt.Normalize(0,17))
        #cb = m.colorbar(im1,"bottom", size="5%", pad="2%")
        #m.pcolor(xi,yi,zi,cmap=plt.cm.spectral, norm=plt.Normalize(0,17))
        cmap = plt.get_cmap('jet',cluster_num)
        cmap.set_bad(color='w',alpha=1)
        zi = np.ma.masked_invalid(zi)
        iml =m.pcolormesh(xi,yi,zi,cmap=cmap, norm=plt.Normalize(1,cluster_num+1))
        cb = m.colorbar(iml,"bottom", size="2%", pad="1%")
        cb.set_ticks(np.arange(1,cluster_num+1))
        #m.imshow(zi,interpolation="none")#interpolation="nearest")

        #---------------------------------------------------
        #m.imshow(zi, interpolation='nearest')
        #m.pcolormesh(xi,yi,zi)

    #l, b, w, h = pos.bounds
    #cax = plt.axes([l+w+0.075, b, 0.05, h]) # setup colorbar axes
    #plt.colorbar(drawedges=True, cax=cax)
    ##plt.colorbar(cax,shrink=0.6)#orientation='vertical',shrink=0.6,ticks=lev)#,drawedges=True,
    #plt.colorbar(ax=ax1)



    ###plt.clabel(CS, fmt='%4.1f',inline=0.5, fontsize=8)  #inline 为等值线标注值周围的间隔

    x5,y5 = m(x,y)  #变换为proj.4

    #m.plot(x,y,c=z,s=10,markeredgewidth=0.1)

    m.plot(x5,y5,'bo',markersize=2)
    #m.scatter(x,y,s=4,lw=0)

    for ii in range(len(x)):
        plt.text(x5[ii],y5[ii],'%d'%int(z[ii]))#,fontsize=9)


    #m.plot(x,y,'o',markeredgewidth=0.1)
    import pkgs.dclimate as dclim

    if b_cnfont :

        cnfont = dclim.GetCnFont()
        #plt.title(ptitle,y=1.075, fontproperties=cnfont)
        plt.title(title1, fontproperties=cnfont,size=20)
    else:
        plt.title(title1,size=20)


    #麦卡托投影哦
    pos = ax1.get_position()
    #print(pos)
    mytoc(u'正式绘图')
    if(b_show_ss):
        ax2 = fig.add_axes([0.0533,0.1393,0.2,0.2])
        m2 = Basemap(projection='cyl',llcrnrlat=4,urcrnrlat=25, \
                 llcrnrlon=107,urcrnrlon=122,resolution='h',ax=ax2)
        #sf = shapefile.Reader(r"spatialdat\Export_Output_12")

        mytic()
        df.draw_map_lines(m2,os.path.join(Spatial_Data,"Export_Output_12"),linewidth=0.5)
        mytoc(u'画南海')

    #plt.colorbar()
    plt.savefig(imgfile,dbi=200)
    df.CutPicWhiteBorder(imgfile)

    #plt.savefig('03.pdf')
    #plt.savefig('03.ps')
    #plt.savefig('03.svg')
    if(b_showimg):
        plt.show()
    mytoc(u'绘图所耗时间')
Example #54
0
            lat_1=50.,lon_0=-107.)
# transform to nx x ny regularly spaced native projection grid
nx = int((m.xmax - m.xmin) / 40000.) + 1
ny = int((m.ymax - m.ymin) / 40000.) + 1
topodat, x, y = m.transform_scalar(topoin,
                                   lonsin,
                                   latsin,
                                   nx,
                                   ny,
                                   returnxy=True)
# create the figure.
fig = plt.figure(figsize=(8, 8))
# add an axes.
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
# associate this axes with the Basemap instance.
m.ax = ax
# make topodat a masked array, masking values lower than sea level.
topodat = np.where(topodat < 0., 1.e10, topodat)
topodatm = ma.masked_values(topodat, 1.e10)
palette = plt.cm.YlOrRd
palette.set_bad('aqua', 1.0)
# plot image over map with imshow.
im = m.imshow(topodatm,
              palette,
              norm=colors.Normalize(vmin=0.0, vmax=3000.0, clip=False))
m.colorbar(im, pad='12%')  # draw colorbar
# plot blue dot on boulder, colorado and label it as such.
xpt, ypt = m(-104.237, 40.125)
m.plot([xpt], [ypt], 'bo')
ax.text(xpt + 100000, ypt + 100000, 'Boulder')
# draw coastlines and political boundaries.
Example #55
0
def draw_cj_map(Region,Title1,Levfile='',b_showimg=0,imgfile='tmp1.png',projtype=1,grid_type='line_rbf'):
    '''
    Setup: Generate data...

    test command:
    RegionR = np.loadtxt('out.txt')
    Region = RegionR[1:,:]
    draw_cj_map(Region,Title1='中午测试',Levfile='',b_showimg=0,imgfile='tmp1.png')

    '''

    #(np.array(X1),np.array(Y1),ST , np.array(AVG_Val),np.array(STID) )
    xs,ys,staname,_,_=GetStaInfo(os.path.join(Station_Data,"cj_sta.txt"))
    print(staname)

    mytic()
    #Title1 = 'Title'
    #LevelFile = ''
    #nx, ny = 150,120
    nx, ny = 400,200
    #RegionR = np.loadtxt('1971_2010_45_12_1_TA.txt')

    ##RegionR = np.loadtxt('out.txt')
    ##Region = RegionR#[1:,:]
    #print(stats._support.unique(Region))
    ##shapeR = np.shape(Region)

    #print(shapeR[1])
    #sys.exit(0)
    #if(shapeR[1]>3):
    #    x,y,z = Region[:,1],Region[:,2],Region[:,3]
    #if(3==shapeR[1]):
    #if(1):
    x,y,z = Region[:,0],Region[:,1],Region[:,2]
    #
    #xmin,xmax,ymin,ymax = 73.6,134.7,16.2,54.0
    #xmin,xmax,ymin,ymax =108,116.5,29,34
    xmin,xmax,ymin,ymax = 90,122.5,24.0,36.0

    x1 = np.linspace(xmin, xmax, nx)
    y1 = np.linspace(ymin, ymax, ny)

    print('lontlatbox=',x.min(),x.max(),y.min(),y.max())
    print(x1.shape,y1.shape)

    #离散点插值到网格
    #if('line_rbf2'==grid_type):
    zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func=grid_type)

    #if('Invdisttree'==grid_type):
    #    zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='Invdisttree')

    #if('line_rbf'==grid_type):
    #    zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='line_rbf')

    #if('nearest'==grid_type):
    #    zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='nearest')
    #    if('nearest'==func):
    #    if('griddata'==func):
    #    if('kriging'==func):
    #    if('scipy_idw'==func):
    #    if('line_rbf'==func):
    #    if('line_rbf2'==func):
    #    if('Invdisttree'==func):
    #    if('nat_grid'==func):

    '''
    if(1):
        mytic()
        if np.size(x)>500 :
            #zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='griddata')#Invdisttree
            zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='line_rbf')#Invdisttree
            #zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='nearest')#Invdisttree
            #zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='line_rbf2')#Invdisttree
        else:
            #zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='nearest')#Invdisttree
            zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='line_rbf')#scipy_idw
            #line_rbf line_rbf2
        #mytoc(u'离散点插值到网格')
        mytoc(u'插值')
    '''

    #平滑插值
    print(zi.shape,x1.shape,y1.shape)
    #sys.exit(0)
    mytic()
    zi,xi,yi,x1,y1,nx,ny=dgrid.extened_grid(zi,x1,y1,zoom=2)
    #mytoc(u'扩展矩阵插值: ')
    mytoc(u'扩展: ')
    #sys.exit(0)

    #获取mask矩阵

    mytic()
    #grid1,shapes = df.build_inside_mask_array(r"spatialdat\china_province",x1,y1)
    #grid1,shapes = df.build_inside_mask_array(r"spatialdata\hbsj-mian",x1,y1)
    grid1 = dgrid.build_inside_mask_array(os.path.join(Spatial_Data,"CJ_BOUND"),x1,y1)
    mytoc(u'mask')#非绘图区域
    zi[np.logical_not(grid1)]=np.NaN

    #-----------------------------------------------------------------------------------
    fig = plt.figure(figsize=(12, 9), dpi=100)
    ax1 = fig.add_axes([0.1,0.1,0.8,0.8])
    #m = Basemap(llcrnrlon=108,llcrnrlat=29,urcrnrlon=116.9,urcrnrlat=33.6,\
    #兰伯拖投影 lambert 投影
    if(1==projtype):
        m = Basemap(llcrnrlon=92.2,llcrnrlat=23.0,urcrnrlon=123.7,urcrnrlat=35.0, \
                projection='lcc',lon_0=105,lat_0=30.0,lat_1=60.0)
    #90,122.5,24.0,36.0
    #Equidistant Cylindrical Projection 等距圆柱投影 CYL
    if(2==projtype):
        m = Basemap(projection='cyl',llcrnrlat=24,urcrnrlat=36.4, \
                    llcrnrlon=90,urcrnrlon=122.7,resolution='l')
    m.ax=ax1
    m.drawparallels(np.arange(20,71,5),labels=[1,0,0,0,],linewidth=0.3, fontsize=10)
    m.drawmeridians(np.arange(80,131,5),labels=[0,0,0,1],linewidth=0.3, fontsize=10)
    #m.drawcoastlines(linewidth=0.2)  #画海岸线
    #m.drawcountries(linewidth=0.2)
    #m.drawmapboundary()


    mytic()
    #df.draw_map_lines(m,r"CJ_GIS_INFO\CJ_Province_CLIP",color='k',linewidth=0.5,debug=1)
    #m.readshapefile('CJ_GIS_INFO\CJ_Province_CLIP','',drawbounds=True,color='#0000ff',linewidth=0.2)
    m.readshapefile(os.path.join(Spatial_Data,'china_province'),'',drawbounds=True,color='#888888',linewidth=0.2)
    mytoc(u'1画流域内省界:');# ')

    mytic()
    #df.draw_map_lines(m,r"CJ_GIS_INFO\CJ_Basin2_Line",color='r',linewidth=0.2)
    #m.readshapefile(os.path.join(Spatial_Data,'CJ_Basin2_Line'),'',drawbounds=True,color='r',linewidth=0.2)
    m.readshapefile(os.path.join(Spatial_Data,'upstreamCD'),'',drawbounds=True,color='r',linewidth=0.2)
    #upstreamCD
    mytoc(u'2画流域界:')# ')

    mytic()
    dgrid.draw_map_lines(m,os.path.join(Spatial_Data,"CJ_LVL1_RIVER"),color='b',linewidth=1.0)
    mytoc(u'3画长江干流: ')#')

    mytic()
    #dgrid.draw_map_lines(m,os.path.join(Spatial_Data,"sxrivers"),color='b',linewidth=0.4)
    mytoc(u'3-1画长江干流: ')#')

    mytic()
    dgrid.draw_map_lines(m,os.path.join(Spatial_Data,"CJ_BOUND"),color='k',linewidth=1.0)
    dgrid.draw_map_lines(m,os.path.join(Spatial_Data,"CJ_BOUND"),color='g',linewidth=0.50)
    mytoc(u'4画省界')

    xi, yi = m(xi,yi)
    #lev = [-150, -100, -50, -20, 0 ,20, 50, 100, 200]
    #lev = [-3.,-2., -1., -0.5,  0. ,0.5, 1., 2., 3.]


    if(not os.path.isfile(Levfile)):
        Levfile = os.path.join(Level_Path,Levfile)

    if( os.path.isfile(Levfile)):
        maplev = np.loadtxt(Levfile)
        #maplev = np.loadtxt('LEV\maplev_TA.LEV')

        cmap2 = maplev[:,:-1]
        cmap2 = cmap2/255.0
        lev = maplev[:,-1]
        #print(cmap2)

        cax = m.contourf(xi,yi,zi,colors=cmap2,levels=lev,extend='both')#plt.cm.jet,
        #l, b, w, h = pos.bounds
        #cax = plt.axes([l+w+0.075, b, 0.05, h]) # setup colorbar axes
        #plt.colorbar(drawedges=True, cax=cax)
        plt.colorbar(cax,shrink=0.3)#orientation='vertical',shrink=0.6,ticks=lev)#,drawedges=True,
        #plt.colorbar(ax=ax1)
        CS = m.contour(xi,yi,zi,levels=lev,linewidths=0.5,colors='k')
        plt.clabel(CS, fmt='%4.1f',inline=0.5, fontsize=8)  #inline 为等值线标注值周围的间隔
    else:
        cax = m.contourf(xi,yi,zi)
        #CS = m.contour(xi,yi,zi,levels=lev,linewidths=0.5,colors='k')
        CS = m.contour(xi,yi,zi,linewidths=.6,colors='k')  #,levels=lev
        plt.colorbar(cax,shrink=0.3)#orientation='vertical',shrink=0.6,ticks=lev)#,drawedges=True,
        plt.clabel(CS, fmt='%4.1f',inline=0.5, fontsize=8)  #inline 为等值线标注值周围的间隔



    x5,y5 = m(x,y)
    x,y = m(x,y)  #变换为proj.4

    #m.plot(x,y,c=z,s=10,markeredgewidth=0.1)
    #m.scatter(x,y,c=z,s=4,lw=0)

    #m.plot(x,y,'o',markeredgewidth=0.1)
    import dclimate as dclim
    cnfont = dclim.GetCnFont()

    plt.title(Title1.decode('gbk'),fontproperties=cnfont,size=12)
    #麦卡托投影

    #################
    xsm,ysm = m(xs,ys)
    xsm2,ysm2 = m(xs-0.5,ys+0.2)
    m.plot(xsm,ysm,'o',markersize=4,markeredgewidth=0.01)
    for ii in range(len(staname)):
        str1 = unicode(staname[ii],'gbk')
        plt.text(xsm2[ii],ysm2[ii],str1,fontsize=9,fontproperties=cnfont)

        #plt.text(x2[i],y2[i],str1,fontsize=6,fontproperties=cnfont)
      #变换为proj.4

    #m.plot(x,y,c=z,s=10,markeredgewidth=0.1)

    #m.plot(x5,y5,'bo',markersize=2)

    #plt.colorbar()
    #print(Magick_Convert)
    #imgfile = 'out.png'
    plt.savefig(imgfile, dpi=120)
    df.CutPicWhiteBorder(imgfile)



    #plt.savefig('03.png',dpi=120)
    #plt.savefig('03.pdf')
    #plt.savefig('03.ps')
    #plt.savefig('03.svg')
    #plt.savefig('03.eps')
    if(b_showimg):
        plt.show()
    plt.close()

    mytoc(u'绘图所耗时间')
config['parallels-quiet'] = config['parallels'].copy()
config['parallels-quiet']['labels'] = [False, False, False, False]

config['meridians-quiet'] = config['meridians'].copy()
config['meridians-quiet']['labels'] = [False, False, False, False]

config['parallels-right'] = config['parallels'].copy()
config['parallels-right']['labels'] = [False, True, False, False]

# Initiate figure and subplots
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(6.66, 7))

# Topography
# ----------
ax = axes[0, 0]
bm.ax = ax
ax.set_title("(a)", y=1.08, loc='left')
ax.set_title("Neuquen Basin", y=1.08, loc="center")
x, y = bm(topography['lon'], topography['lat'])
shape = topography['shape']
vmax = np.abs([np.nanmin(topography['topo']),
               np.nanmax(topography['topo'])]).max()
vmin = -vmax
cmap = plt.cm.gist_earth

# Hillshaded topography
ls = LightSource(azdeg=120)
rgb = ls.shade(topography['topo'].reshape(shape),
               cmap,
               blend_mode='soft',
               vert_exag=1000,
Example #57
0
def draw_cj_map_split(Region,Title1,Levfile='',b_showimg=0,imgfile='tmp1.png',cluster_num=4,projtype=1):
    '''
    Setup: Generate data...

    test command:
    RegionR = np.loadtxt('out.txt')
    Region = RegionR[1:,:]
    draw_cj_map(Region,Title1='中午测试',Levfile='',b_showimg=0,imgfile='tmp1.png')

    '''
    mytic()
    #Title1 = 'Title'
    #LevelFile = ''
    nx, ny = 70,30
    #nx, ny = 400,200
    #RegionR = np.loadtxt('1971_2010_45_12_1_TA.txt')

    ##RegionR = np.loadtxt('out.txt')
    ##Region = RegionR#[1:,:]
    #print(stats._support.unique(Region))
    ##shapeR = np.shape(Region)

    #print(shapeR[1])
    #sys.exit(0)
    #if(shapeR[1]>3):
    #    x,y,z = Region[:,1],Region[:,2],Region[:,3]
    #if(3==shapeR[1]):
    #if(1):
    x,y,z = Region[:,0],Region[:,1],Region[:,2]
    print(x)
    print(y)
    print(z)
    #
    #xmin,xmax,ymin,ymax = 73.6,134.7,16.2,54.0
    #xmin,xmax,ymin,ymax =108,116.5,29,34
    #原始信息 xmin,xmax,ymin,ymax = 90,122.5,24.0,36.0
    xmin,xmax,ymin,ymax = 98,122.5,24.0,36.0

    x1 = np.linspace(xmin, xmax, nx)
    y1 = np.linspace(ymin, ymax, ny)

    print('lontlatbox=',x.min(),x.max(),y.min(),y.max())
    print(x1.shape,y1.shape)

    #离散点插值到网格
    if(1):
        mytic()
        #if np.size(x)>500 :
        #    zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='Invdisttree')#Invdisttree
        #else:
        zi,xi,yi = dgrid.griddata_all(x,y,z,x1,y1,func='nearest')
            #line_rbf line_rbf2 nearest
        #mytoc(u'离散点插值到网格')
        mytoc(u'插值')


    #平滑插值
    print(zi.shape,x1.shape,y1.shape)
    #sys.exit(0)
    mytic()
    #zi,xi,yi,x1,y1,nx,ny=dgrid.extened_grid(zi,x1,y1,zoom=2)
    #mytoc(u'扩展矩阵插值: ')
    mytoc(u'扩展: ')
    #sys.exit(0)

    #获取mask矩阵

    mytic()
    #grid1,shapes = df.build_inside_mask_array(r"spatialdat\china_province",x1,y1)
    #grid1,shapes = df.build_inside_mask_array(r"spatialdata\hbsj-mian",x1,y1)
    grid1 = dgrid.build_inside_mask_array(os.path.join(Spatial_Data,"CJ_BOUND"),x1,y1)
    mytoc(u'mask')#非绘图区域
    zi[np.logical_not(grid1)]=np.NaN

    #-----------------------------------------------------------------------------------
    fig = plt.figure(figsize=(12, 9), dpi=100)
    ax1 = fig.add_axes([0.1,0.1,0.8,0.8])
    #m = Basemap(llcrnrlon=108,llcrnrlat=29,urcrnrlon=116.9,urcrnrlat=33.6,\
    #兰伯拖投影 lambert 投影
    if(1==projtype):
        m = Basemap(llcrnrlon=92.2,llcrnrlat=23.0,urcrnrlon=123.7,urcrnrlat=35.0, \
                    projection='lcc',lon_0=105,lat_0=30.0,lat_1=60.0)
        #90,122.5,24.0,36.0
    #Equidistant Cylindrical Projection 等距圆柱投影 CYL
    if(2==projtype):
        m = Basemap(projection='cyl',llcrnrlat=24,urcrnrlat=36.4, \
                    llcrnrlon=90,urcrnrlon=122.7,resolution='l')
    m.ax=ax1
    m.drawparallels(np.arange(20,71,5),labels=[1,0,0,0,],linewidth=0.3, fontsize=10)
    m.drawmeridians(np.arange(80,131,5),labels=[0,0,0,1],linewidth=0.3, fontsize=10)
    #m.drawcoastlines(linewidth=0.2)  #画海岸线
    #m.drawcountries(linewidth=0.2)
    #m.drawmapboundary()

    mytic()
    #df.draw_map_lines(m,r"CJ_GIS_INFO\CJ_Province_CLIP",color='k',linewidth=0.5,debug=1)
    #m.readshapefile('CJ_GIS_INFO\CJ_Province_CLIP','',drawbounds=True,color='#0000ff',linewidth=0.2)
    m.readshapefile(os.path.join(Spatial_Data,'china_province'),'',drawbounds=True,color='#888888',linewidth=0.2)
    mytoc(u'1画流域内省界:');# ')

    mytic()
    #df.draw_map_lines(m,r"CJ_GIS_INFO\CJ_Basin2_Line",color='r',linewidth=0.2)
    m.readshapefile(os.path.join(Spatial_Data,'CJ_Basin2_Line'),'',drawbounds=True,color='r',linewidth=0.2)
    mytoc(u'2画流域界:')# ')

    mytic()
    dgrid.draw_map_lines(m,os.path.join(Spatial_Data,"CJ_LVL1_RIVER"),color='b',linewidth=1.0)
    mytoc(u'3画长江干流: ')#')

    mytic()
    dgrid.draw_map_lines(m,os.path.join(Spatial_Data,"sxrivers"),color='b',linewidth=0.4)
    mytoc(u'3-1画长江干流: ')#')

    mytic()
    dgrid.draw_map_lines(m,os.path.join(Spatial_Data,"CJ_BOUND"),color='k',linewidth=1.0)
    dgrid.draw_map_lines(m,os.path.join(Spatial_Data,"CJ_BOUND"),color='g',linewidth=0.50)
    mytoc(u'4画省界')


    xi, yi = m(xi,yi)
    #lev = [-150, -100, -50, -20, 0 ,20, 50, 100, 200]
    #lev = [-3.,-2., -1., -0.5,  0. ,0.5, 1., 2., 3.]
    if( os.path.isfile(Levfile)):
        maplev = np.loadtxt(Levfile)
        #maplev = np.loadtxt('LEV\maplev_TA.LEV')

        cmap2 = maplev[:,:-1]
        cmap2 = cmap2/255.0
        lev = maplev[:,-1]
        #print(cmap2)

        cax = m.contourf(xi,yi,zi,colors=cmap2,levels=lev,extend='both')#plt.cm.jet,
        #l, b, w, h = pos.bounds
        #cax = plt.axes([l+w+0.075, b, 0.05, h]) # setup colorbar axes
        #plt.colorbar(drawedges=True, cax=cax)
        plt.colorbar(cax,shrink=0.3)#orientation='vertical',shrink=0.6,ticks=lev)#,drawedges=True,
        #plt.colorbar(ax=ax1)
        CS = m.contour(xi,yi,zi,levels=lev,linewidths=0.5,colors='k')
        plt.clabel(CS, fmt='%4.1f',inline=0.5, fontsize=8)  #inline 为等值线标注值周围的间隔
    else:
        #cmap = plt.get_cmap('jet',cluster_num)
        #cmap.set_bad(color='w',alpha=1)
        '''
        zi = np.ma.masked_invalid(zi)
        print(zi)
        iml =m.pcolormesh(xi,yi,zi,edgecolors='w', linewidths=0.01)#,cmap=cmap, norm=plt.Normalize(1,cluster_num+1))
            cb = m.colorbar(iml,"right", size="2%", pad="1%")
        '''
        cmap = plt.get_cmap('jet',cluster_num)
        cmap.set_bad(color='w',alpha=1)
        zi = np.ma.masked_invalid(zi)
        iml =m.pcolormesh(xi,yi,zi,cmap=cmap, norm=plt.Normalize(1,cluster_num+1))
        cb = m.colorbar(iml,"bottom", size="2%", pad="1%")
        cb.set_ticks(np.arange(1,cluster_num+1))



        #cb.set_ticks(np.arange(1,cluster_num+1))

    x5,y5 = m(x,y)  #变换为proj.4

    m.plot(x5,y5,'bo',markersize=2)
    #m.plot(x,y,c=z,s=10,markeredgewidth=0.1)
    #m.scatter(x,y,c=z,s=4,lw=0)

    #m.plot(x,y,'o',markeredgewidth=0.1)
    import dclimate as dclim
    cnfont = dclim.GetCnFont()

    plt.title(Title1.decode('gbk'),fontproperties=cnfont,size=12)

    #麦卡托投影哦

    #plt.colorbar()
    #print(Magick_Convert)
    #imgfile = 'out.png'
    plt.savefig(imgfile, dpi=120)
    df.CutPicWhiteBorder(imgfile)



    #plt.savefig('03.png',dpi=120)
    #plt.savefig('03.pdf')
    #plt.savefig('03.ps')
    #plt.savefig('03.svg')
    #plt.savefig('03.eps')
    if(b_showimg):
        plt.show()

    mytoc(u'绘图所耗时间')
   

    # Apply transformation
   # field=1.0*(field.squeeze()-273.15)

    # Mask land values
    field = np.ma.masked_array(field,field==field.fill_value)

    newticks=newticks.round(2)

    # Make the plot
    fig=plt.figure()
    ax = fig.add_subplot(111)


    m.ax=ax

    
    x,y = m(lon,lat)

    pcm=m.pcolormesh(x,y,field,cmap=cmap,norm=norm)

    # Add grid, coastline and continent
    m.drawcoastlines(ax=ax)
    m.fillcontinents(color='.15', ax=ax)
    #m.bluemarble()

    meridians=np.arange(lonmin,lonmax,dlon)
    parallels=np.arange(latmin,latmax,dlat)
    m.drawmeridians(meridians,labels=[0, 0, 0, 1],linewidth=0.5,fontsize=18,\
                    fontname='Times New Roman')
Example #59
0
def draw_cj_map_split2(zi,Title1,Levfile='',b_showimg=0,imgfile='tmp1.png',cluster_num=4,projtype=1):
    '''
    Setup: Generate data...

    test command:
    RegionR = np.loadtxt('out.txt')
    Region = RegionR[1:,:]
    draw_cj_map(Region,Title1='中午测试',Levfile='',b_showimg=0,imgfile='tmp1.png')

    '''
    nx, ny = 70,30
    xmin,xmax,ymin,ymax = 98,122.5,24.0,36.0

    x1 = np.linspace(xmin, xmax, nx)
    y1 = np.linspace(ymin, ymax, ny)
    xi, yi = np.meshgrid(x1, y1)

    #-----------------------------------------------------------------------------------
    fig = plt.figure(figsize=(12, 9), dpi=100)
    ax1 = fig.add_axes([0.1,0.1,0.8,0.8])
    #m = Basemap(llcrnrlon=108,llcrnrlat=29,urcrnrlon=116.9,urcrnrlat=33.6,\
    #兰伯拖投影 lambert 投影
    if(1==projtype):
        m = Basemap(llcrnrlon=92.2,llcrnrlat=23.0,urcrnrlon=123.7,urcrnrlat=35.0, \
                    projection='lcc',lon_0=105,lat_0=30.0,lat_1=60.0)
        #90,122.5,24.0,36.0
    #Equidistant Cylindrical Projection 等距圆柱投影 CYL
    if(2==projtype):
        m = Basemap(projection='cyl',llcrnrlat=24,urcrnrlat=36.4, \
                    llcrnrlon=90,urcrnrlon=122.7,resolution='l')
    m.ax=ax1
    m.drawparallels(np.arange(20,71,5),labels=[1,0,0,0,],linewidth=0.3, fontsize=10)
    m.drawmeridians(np.arange(80,131,5),labels=[0,0,0,1],linewidth=0.3, fontsize=10)
    #m.drawcoastlines(linewidth=0.2)  #画海岸线
    #m.drawcountries(linewidth=0.2)
    #m.drawmapboundary()


    mytic()
    #df.draw_map_lines(m,r"CJ_GIS_INFO\CJ_Province_CLIP",color='k',linewidth=0.5,debug=1)
    #m.readshapefile('CJ_GIS_INFO\CJ_Province_CLIP','',drawbounds=True,color='#0000ff',linewidth=0.2)
    m.readshapefile(os.path.join(Spatial_Data,'china_province'),'',drawbounds=True,color='#888888',linewidth=0.2)
    mytoc(u'1画流域内省界:');# ')

    mytic()
    #df.draw_map_lines(m,r"CJ_GIS_INFO\CJ_Basin2_Line",color='r',linewidth=0.2)
    m.readshapefile(os.path.join(Spatial_Data,'CJ_Basin2_Line'),'',drawbounds=True,color='r',linewidth=0.2)
    mytoc(u'2画流域界:')# ')

    mytic()
    dgrid.draw_map_lines(m,os.path.join(Spatial_Data,'CJ_LVL1_RIVER'),color='b',linewidth=1.0)
    mytoc(u'3画长江干流: ')#')

    mytic()
    dgrid.draw_map_lines(m,os.path.join(Spatial_Data,'CJ_BOUND'),color='k',linewidth=1.0)
    dgrid.draw_map_lines(m,os.path.join(Spatial_Data,'CJ_BOUND'),color='g',linewidth=0.50)
    mytoc(u'4画省界')

    xi, yi = m(xi,yi)
    #lev = [-150, -100, -50, -20, 0 ,20, 50, 100, 200]
    #lev = [-3.,-2., -1., -0.5,  0. ,0.5, 1., 2., 3.]
    if( os.path.isfile(Levfile)):
        maplev = np.loadtxt(Levfile)
        #maplev = np.loadtxt('LEV\maplev_TA.LEV')

        cmap2 = maplev[:,:-1]
        cmap2 = cmap2/255.0
        lev = maplev[:,-1]
        #print(cmap2)

        cax = m.contourf(xi,yi,zi,colors=cmap2,levels=lev,extend='both')#plt.cm.jet,
        #l, b, w, h = pos.bounds
        #cax = plt.axes([l+w+0.075, b, 0.05, h]) # setup colorbar axes
        #plt.colorbar(drawedges=True, cax=cax)
        plt.colorbar(cax,shrink=0.3)#orientation='vertical',shrink=0.6,ticks=lev)#,drawedges=True,
        #plt.colorbar(ax=ax1)
        CS = m.contour(xi,yi,zi,levels=lev,linewidths=0.5,colors='k')
        plt.clabel(CS, fmt='%4.1f',inline=0.5, fontsize=8)  #inline 为等值线标注值周围的间隔
    else:
        #cmap = plt.get_cmap('jet',cluster_num)
        #cmap.set_bad(color='w',alpha=1)
        '''
        zi = np.ma.masked_invalid(zi)
        print(zi)
        iml =m.pcolormesh(xi,yi,zi,edgecolors='w', linewidths=0.01)#,cmap=cmap, norm=plt.Normalize(1,cluster_num+1))
            cb = m.colorbar(iml,"right", size="2%", pad="1%")
        '''
        cmap = plt.get_cmap('jet',cluster_num)
        cmap.set_bad(color='w',alpha=1)
        zi = np.ma.masked_invalid(zi)
        print(zi)
        iml =m.pcolormesh(xi,yi,zi,cmap=cmap, norm=plt.Normalize(1,cluster_num+1))
        cb = m.colorbar(iml,"bottom", size="2%", pad="1%")
        cb.set_ticks(np.arange(1,cluster_num+1))



        #cb.set_ticks(np.arange(1,cluster_num+1))

    #m.plot(x,y,c=z,s=10,markeredgewidth=0.1)
    #m.scatter(x,y,c=z,s=4,lw=0)

    #m.plot(x,y,'o',markeredgewidth=0.1)
    import dclimate as dclim
    cnfont = dclim.GetCnFont()

    plt.title(Title1.decode('gbk'),fontproperties=cnfont,size=12)

    #麦卡托投影哦

    #plt.colorbar()
    #print(Magick_Convert)
    #imgfile = 'out.png'
    plt.savefig(imgfile, dpi=120)
    df.CutPicWhiteBorder(imgfile)



    #plt.savefig('03.png',dpi=120)
    #plt.savefig('03.pdf')
    #plt.savefig('03.ps')
    #plt.savefig('03.svg')
    #plt.savefig('03.eps')
    if(b_showimg):
        plt.show()

    mytoc(u'绘图所耗时间')