def create_map(extent, xstep, ystep): # 加载shp shp_path_p = '/Users/wangyucheng/Desktop/kuihua/Province_9/' shp_path_c = '/Users/wangyucheng/Desktop/kuihua/diqujie/' # --创建画图空间 proj = ccrs.PlateCarree() # 创建坐标系 fig = plt.figure(figsize=(8, 10)) # 创建页面 ax = plt.axes(projection=ccrs.PlateCarree()) # --设置地图属性 reader_p = Reader(shp_path_p + 'Province_9.shp') province = cfeat.ShapelyFeature(reader_p.geometries(), proj, edgecolor='k', facecolor='none') reader_c = Reader(shp_path_c + 'diquJie_polyline.shp') city = cfeat.ShapelyFeature(reader_c.geometries(), proj, edgecolor='k', facecolor='none') # 加载省界线 ax.add_feature(province) # 加载市界 ax.add_feature(city) # 加载经纬范围 ax.set_extent(extent, crs=proj) # --设置网格点属性 gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1.2, color='k', alpha=0.5, linestyle='--') gl.xlabels_top = False # 关闭顶端的经纬度标签 gl.ylabels_right = False # 关闭右侧的经纬度标签 gl.xformatter = LONGITUDE_FORMATTER # x轴设为经度的格式 gl.yformatter = LATITUDE_FORMATTER # y轴设为纬度的格式 gl.xlocator = mticker.FixedLocator( np.arange(extent[0], extent[1] + xstep, xstep)) gl.ylocator = mticker.FixedLocator( np.arange(extent[2], extent[3] + ystep, ystep)) return fig, ax
def plot_mineral_deposits(self, ax, facecolors='none'): reader = Reader(mineral_output_basename) ax.scatter([point.x for point in reader.geometries()], [point.y for point in reader.geometries()], facecolors=facecolors, transform=ccrs.PlateCarree(), edgecolors='black', s=30, zorder=99) reader_au = Reader(mineral_AU_output_basename) ax.scatter([point.x for point in reader_au.geometries()], [point.y for point in reader_au.geometries()], facecolors=facecolors, edgecolors='gold', transform=ccrs.PlateCarree(), s=30, zorder=99)
def plot(self, xar): plt.close() self.fig = plt.figure(**self.fig_kws) self.savefig = self.fig.savefig ax = plt.axes(projection=self.proj) states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lines', scale='50m', facecolor='none') countries = cfeature.NaturalEarthFeature( category='cultural', name='admin_0_boundary_lines_land', scale='50m', facecolor='none') rivers = cfeature.NaturalEarthFeature(scale='50m', category='physical', name='rivers_lake_centerlines', edgecolor='blue', facecolor='none') ax.add_feature(countries, edgecolor='grey') ax.coastlines('50m') #ax.add_feature(states_provinces, edgecolor='gray') ax.add_feature(rivers, edgecolor='blue') if self.kwargs.get('drainage_baisins', True): sf = Reader( "../data/drainage_basins/Major_Basins_of_the_World.shp") shape_feature = ShapelyFeature(sf.geometries(), self.transform, edgecolor='black') ax.add_feature(shape_feature, facecolor='none', edgecolor='green') xar.plot(transform=self.transform, ax=ax, subplot_kws={'projection': self.proj}) self.ax = ax
} ############################################################################## ''' Set up the daily average salinity grid ''' if 'mask' not in vars(): working_scenario = cb avesalD_coords = coords.ix[avesalD_nodes] lon = np.array(avesalD_coords['lon']) lat = np.array(avesalD_coords['lat']) loni = np.linspace(min(lon), max(lon), 100) lati = np.linspace(min(lat), max(lat), 100) glon, glat = np.meshgrid(loni, lati) shp = Reader(shp_path) geoms = list(shp.geometries()) max_area = 0 max_area_id = 0 for i in range(len(geoms)): if geoms[i].area > max_area: max_area = geoms[i].area max_area_id = i polygon = geoms[i] mask = inpolygon(polygon, glon.ravel(), glat.ravel()) mask = mask.reshape(glon.shape) ############################################################################## ''' Make the base map ''' lats = [28.142815, 28.142622, 28.128572, 28.128588] lons = [-97.057931, -97.041549, -97.041542, -97.057923]
def plot(self, xar, **kwargs): """Wraps xr.DataArray.plot.pcolormesh and formats the plot as configured in the call to Map(). title is xar.long_name cbar_label is xar.units Parameters ---------- xar : xr.DataArray two-dimensional data array kwargs : dict are passed on to xr.DataArray.plot.pcolormesh() Returns ---------- fig : matplotlib.pyplot.figure ax : matplotlib.pyplot.axis """ for dim in ['longitude', 'latitude']: if dim not in xar.coords: raise KeyError(dim+' not found in coordinates!') plt.close() fig = plt.figure(**self.fig_kws) if not self.proj: self.proj = choose_proj_from_xar(xar) ax = plt.axes(projection=self.proj) countries = cfeature.NaturalEarthFeature( category='cultural', name='admin_0_boundary_lines_land', scale='50m', facecolor='none') rivers = cfeature.NaturalEarthFeature(scale='50m', category='physical', name='rivers_lake_centerlines', edgecolor='blue', facecolor='none') ax.add_feature(countries, edgecolor='grey') ax.coastlines('50m') ax.add_feature(rivers, edgecolor='blue') gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True) gl.xlabels_top = False if self.drainage_baisins: sf = Reader("../data/drainage_basins/Major_Basins_of_the_World.shp") shape_feature = ShapelyFeature(sf.geometries(), self.transform, edgecolor='black') ax.add_feature(shape_feature, facecolor='none', edgecolor='green') # cbar_kwargs = kwargs.pop('cbar_kwargs', dict()) subplot_kws = kwargs.pop('subplot_kws', dict()) subplot_kws['projection'] = self.proj # choose which colormap to use: pos and neg values => RdYlGn, else inferno if ((xar.max()-xar.min()) > xar.max()): cmap = 'RdYlGn' else: cmap = 'spring_r' # colorbar preset to match height of plot # if 'fraction' not in cbar_kwargs: cbar_kwargs['fraction'] = 0.015 xar.plot.pcolormesh(ax=ax, transform=self.transform, subplot_kws=subplot_kws, cmap=cmap, **kwargs) return fig, ax
import os plt.clf() #ax = geo_plots.add_map(bbox=(-89,-85,27.5,31)) ax = geo_plots.add_map(bbox=(-90, -84, 27.5, 31)) #land_10m = cfeature.NaturalEarthFeature('physical','land','50m',\ # edgecolor='face',facecolor='0.75') ##ax.add_feature(cfeature.LAND, facecolor='0.75') #ax.add_feature(land_10m) #if bbox not specified, this will use map bounds from bna bathy_file = os.path.join('gom_bathy','Bathymetry.shp') bathy = Reader(bathy_file) for rec,geo in zip(bathy.records(),bathy.geometries()): if rec.attributes['DEPTH_METR'] in ['100m','500m','1000m']: shape_feature = ShapelyFeature(geo,ccrs.PlateCarree(), facecolor='none') ax.add_feature(shape_feature) #add particles at one time t = datetime.datetime(2016, 9, 21, 1) filename = 'gulf_tamoc.nc' ax = geo_plots.contour_particles(ax,filename,t,levels=[0.1, 0.4, 0.6, 1]) #ax = geo_plots.plot_particles(ax,filename,t,depth=0,color='b') #add initial location
else: background_image['alpha'] = 1.0 #Draw geography m.drawstates() m.drawcoastlines() m.drawcountries() print("--> Plotted geographic & political boundaries") #======================================================================================================== # Plot data #======================================================================================================== #Iterate through all states total_cases = 0 for record, state in zip(shp.records(), shp.geometries()): #Reference state name as a separate variable name = record.attributes['NAME'] #Get state's case data for this date if name.lower() in cases.keys(): idx = cases[name.lower()]['date'].index(plot_start_date) if plot_type not in [ 'confirmed', 'confirmed_normalized', 'deaths', 'recovered', 'active', 'daily' ]: plot_type = 'confirmed' case_number = cases[name.lower()][plot_type][idx] total_cases += case_number else:
#create the salinity mask if 'mask' not in vars(): print('Preparing salinity mask\n') #get all nodes within the extent, and get their lons and lats avesalD_coords = coords.loc[avesalD_nodes] lon = np.array(avesalD_coords['lon']) lat = np.array(avesalD_coords['lat']) #create an array of lat and lon ranges for gridding loni = np.linspace(min(lon), max(lon), 150) lati = np.linspace(min(lat), max(lat), 150) #create mesh grid glon, glat = np.meshgrid(loni, lati) #read the shapefile shp = Reader(shp_path) #get the geometries from the shapefile geoms = list(shp.geometries()) max_area = 0 max_area_id = 0 #find the largest polygon in the shapefile, the inside of which will be the bay for i in range(len(geoms)): if geoms[i].area > max_area: max_area = geoms[i].area max_area_id = i polygon = geoms[i] #create the mask based on which points are inside the largest polygon mask = inpolygon(polygon, glon.ravel(), glat.ravel()) #reshape the mask to the same size as the meshgrid mask = mask.reshape(glon.shape) else: print('Salinity mask already created\n')
for i in range(len(cn_multipoly)): cn_geom, = geos_to_path(cn_multipoly.geoms[i]) paths.append(cn_geom) path = Path.make_compound_path(*paths) for collection in contourf.collections: collection.set_clip_path(path, proj._as_mpl_transform(ax)) # 白化刻度 # contour = ax.contour(lon,lat,u1_avg,lev,cmap='Blues',transform=proj,extend='both') # cn_label = plt.clabel(contour,inline=1,fontsize=10,fmt="%.fr") # if cn_label: # clip_map_shapely = Polygon(path.vertices) # for text_object in cn_label: # if not clip_map_shapely.contains(Point(text_object.get_position())): # text_object.set_visible(False) ax.add_geometries(cn_multipoly, crs=proj, edgecolor='black', linewidths=1, facecolor='none', zorder=10, alpha=0.8) #ax.gridlines(color="black", linestyle="--") ax.gridlines(color='gray', linestyle = 'dotted', xlocs = np.arange(70,140+20,20), ylocs = np.arange(15,65+10,10)) fig.colorbar(contourf, format='%.1f',shrink=0.8) sub_ax = fig.add_axes([0.60, 0.20, 0.17, 0.2],projection=proj) # Add ocean, land, rivers and lakes # Set figure extent sub_ax.set_extent([105, 125, 0, 25],crs=proj) sub_ax.add_geometries(shp.geometries(),crs=proj,edgecolor='black', linewidths=1,facecolor='none',zorder=10,alpha=0.8) fig.savefig('*.png',bbox_inches = 'tight')
#facecolor=feature.COLORS['land'], facecolor='lightgray', name='land', ) fname = 'files/ne_10m_populated_places.shp' reader = Reader(fname) #city names city = [] for i, record in enumerate(reader.records()): name = record.attributes['name_es'] geometry = record.geometry x, y = geometry.centroid.x, geometry.centroid.y if all([lon_min < x < lon_max, lat_min < y < lat_max]): city.append([x, y, name]) #city points points = [list(point.coords) for point in reader.geometries()] xp = [ point[0][0] for point in points if all( [lon_min < point[0][0] < lon_max, lat_min < point[0][1] < lat_max]) ] yp = [ point[0][1] for point in points if all( [lon_min < point[0][0] < lon_max, lat_min < point[0][1] < lat_max]) ] #features=[land,coastline,states,reader] #ocean= feature.ShapelyFeature( # Reader('ne_10m_ocean.shp').geometries(), # ccrs.PlateCarree(), # )
import os plt.clf() #ax = geo_plots.add_map(bbox=(-89,-85,27.5,31)) ax = geo_plots.add_map(bbox=(-90, -84, 27.5, 31)) #land_10m = cfeature.NaturalEarthFeature('physical','land','50m',\ # edgecolor='face',facecolor='0.75') ##ax.add_feature(cfeature.LAND, facecolor='0.75') #ax.add_feature(land_10m) #if bbox not specified, this will use map bounds from bna bathy_file = os.path.join('gom_bathy', 'Bathymetry.shp') bathy = Reader(bathy_file) for rec, geo in zip(bathy.records(), bathy.geometries()): if rec.attributes['DEPTH_METR'] in ['100m', '500m', '1000m']: shape_feature = ShapelyFeature(geo, ccrs.PlateCarree(), facecolor='none') ax.add_feature(shape_feature) #add particles at one time t = datetime.datetime(2016, 9, 21, 1) filename = 'gulf_tamoc.nc' ax = geo_plots.contour_particles(ax, filename, t, levels=[0.1, 0.4, 0.6, 1]) #ax = geo_plots.plot_particles(ax,filename,t,depth=0,color='b') #add initial location
filename=r'F:/Rpython/lp28/data/XJ1224.xlsx' df=pd.read_excel(filename)#读取文件 lon=df['lon']#读取站点经度 lat=df['lat']#读取站点纬度 tem=df['h']#读取站点气温 # 创建画布 fig = plt.figure(figsize=(12,10),dpi=600) olon=np.linspace(70,100,90) olat=np.linspace(30,55,75) olon,olat=np.meshgrid(olon,olat)#网格化 func=Rbf(lon,lat,tem,function='cubic')#定义径向基函数插值 tem_new=func(olon,olat)#获得插值后的网格气温 ax = fig.subplots(1, 1, subplot_kw={'projection': proj}) # 创建子图 extent=[73,97,34,50]#限定绘图范围 reader = Reader(shp_path) enshicity = cfeat.ShapelyFeature(reader.geometries(), proj, edgecolor='k', facecolor='none') ax.add_feature(enshicity, linewidth=0.7)#添加市界细节 ax.set_extent(extent,crs=proj) ax.set_xticks(np.arange(extent[0],extent[1]+1,3),crs=proj) ax.set_yticks(np.arange(extent[-2],extent[-1]+1,2),crs=proj) ax.xaxis.set_major_formatter(LongitudeFormatter()) ax.yaxis.set_major_formatter(LatitudeFormatter()) cs1= ax.contourf(olon,olat,tem_new,levels=np.arange(0,2000,200),cmap='gist_rainbow',extend='both')#画图cmap='Spectral_r', cs2= ax.contour(olon,olat,tem_new,colors='red',linewidths=0.6)#画图 b=plt.colorbar(cs1,shrink=0.65,orientation='vertical',extend='both',pad=0.035,aspect=20) #orientation='horizontal' clip1=maskout2.shp2clip(cs1,ax,r'F:/Rpython/lp17/data/xinjiang0819.shp') #白化1 clip2=maskout2.shp2clip(cs2,ax,r'F:/Rpython/lp17/data/xinjiang0819.shp') #白化2 font3={'family':'SimHei','size':8,'color':'k'} plt.scatter(df['lon'].values,df['lat'].values,marker='o',s=6,color ="k") for i, j, k in list(zip(df['lon'].values, df['lat'].values, df['name'].values)): plt.text(i-0.2,j-0.3,k,fontdict=font3)
south_china_sea = 3415 crs = ccrs.Mercator() crs2 = ccrs.epsg(3415) crs = ccrs.Mercator() fig = plt.figure(figsize=(20, 20)) ax = fig.add_subplot(1, 1, 1, projection=crs) #ax = plt.axes(projection=crs) #ax.set_extent([140, 80, -2, 55], crs=crs) ax.set_extent([136, 72, 3, 55], crs=crs) world = Reader(path_join('Basemap', 'world')) nation = Reader(path_join('Basemap', 'nation')) province = Reader(path_join('Basemap', 'province')) river = Reader(path_join('Basemap', 'river')) lake = Reader(path_join('Basemap', 'lake')) ax.add_geometries(world.geometries(), crs=crs, edgecolor='#555555', facecolor='none', linewidth=1.5) ax.add_geometries(nation.geometries(), crs=crs, edgecolor='#000000', facecolor='none', linewidth=2) ax.add_geometries(province.geometries(), crs=crs, edgecolor='#222222', facecolor='none', linewidth=1) ax.add_geometries(river.geometries(),
new_dpco2_cube.standard_name = dpco2_cube.standard_name new_d14c_cube.units = d14c_cube.units new_dpco2_cube.units = dpco2_cube.units new_d14c_cube.var_name = d14c_cube.var_name new_dpco2_cube.var_name = dpco2_cube.var_name shpfilename = natural_earth(resolution='110m', category='physical', name='land') reader = Reader(shpfilename) continents = reader.records() new_d14c_cube.coord('latitude').guess_bounds() new_d14c_cube.coord('longitude').guess_bounds() new_dpco2_cube.coord('latitude').guess_bounds() new_dpco2_cube.coord('longitude').guess_bounds() continent_geometries = reader.geometries() # NB. Switched from using records() all_continents_geometry = cascaded_union(list(continent_geometries)) area_weights = geometry_area_weights(new_d14c_cube, all_continents_geometry) land_mask = np.where(area_weights > 0, True, False) new_d14c_cube.data = np.ma.array(new_d14c_cube.data, mask=land_mask) area_weights = geometry_area_weights(new_dpco2_cube, all_continents_geometry) land_mask = np.where(area_weights > 0, True, False) new_dpco2_cube.data = np.ma.array(new_dpco2_cube.data, mask=land_mask) iris.fileformats.netcdf.save(new_d14c_cube, output_directory+model+'_d14c_hist.nc') iris.fileformats.netcdf.save(new_dpco2_cube, output_directory+model+'_dpco2_hist.nc') subprocess.call('rm '+temporary_file_space+temp_file3, shell=True) else: print 'No variable input files for this model' else:
# %matplotlib inline import cartopy.crs as ccrs from cartopy.io.shapereader import Reader from cartopy.feature import ShapelyFeature ax = plt.axes(projection=ccrs.LambertConformal( central_latitude=39, central_longitude=-96, standard_parallels=(33, 45))) ax.set_extent([-125, -66.5, 20, 50]) # Read in county-level shapefiles fname = "/data301/data/cb_2017_us_county_5m/cb_2017_us_county_5m" shp = Reader(fname) # Add each county to the data set. ax.add_geometries(shp.geometries(), ccrs.PlateCarree(), facecolor="None", edgecolor='black') # - # To make a choropleth, we simply need to set the `facecolor` of each geometry. First, let's read in some county-level data that we can plot. import pandas as pd election_df = pd.read_csv( "https://raw.githubusercontent.com/dlsun/data-science-book/" "master/data/election2016.csv") election_df # We need to merge this data with the shapefile that we just loaded. We can create a `DataFrame` out of the `records` of a shapefile.
working_dir = 'lon-%d~%d_lat-%d~%d_time-%s~%s' % ( extent[2], extent[3], extent[0], extent[1], from_date, to_date) if not os.path.exists(working_dir): os.makedirs(working_dir) f = open('full.data', 'rb') storedlist = pickle.load(f) # Map GHI storedlist = storedlist[0] reader = Reader(os.path.join('shape', 'Province_9.shp')) proj = ccrs.PlateCarree() provinces = cfeat.ShapelyFeature(reader.geometries(), proj, edgecolor='k', facecolor='none') for i in range(total_frame): print("%f%%\r" % (i / total_frame * 100)) time = int(i / total_frame * time_range) plt.figure(figsize=(10, 10)) ax = plt.axes(projection=proj) ax.add_feature(provinces, linewidth=0.5) ax.set_extent(extent, crs=proj) ax.stock_img() gl = ax.gridlines(crs=ccrs.PlateCarree(),
from cartopy.io.shapereader import Reader #------------------------------------------------------------------------------ # files_cli = sorted(glob.glob(os.path.join('/home/alley/work/Dong/mongo/seasonal_analysis/data/data/download_from_mongo/cli', '*.grb'))) # file_cur = "/home/alley/work/Dong/mongo/seasonal_analysis/data/data/download_from_mongo/cur/gh_500_201911.grb" # f_cli = xr.concat([xr.load_dataarray(file, engine="cfgrib") for file in files_cli], dim="time") # c_cur = xr.load_dataarray(file_cur, engine="cfgrib") # f_cli = xr.open_mfdataset(filenames_cli, engine="cfgrib", concat_dim=["time"]) #f_cur = Nio.open_file(filenames_cur) # print(f_cli.dims) #------------------------------------------------------------------------------ shp_path = '/home/alley/work/data/Cartopy_shapefiles/ne_50m_coastline.shp' reader = Reader(shp_path) proj = ccrs.PlateCarree(central_longitude=140) coastlines = cfeature.ShapelyFeature(reader.geometries(), proj, edgecolor='k', facecolor='none') fig = plt.figure(figsize=(4, 4), dpi=600) ax = fig.subplots(1, 1, subplot_kw={'projection': proj}) ax.add_feature(coastlines, linewidth=0.7) # ax.coastlines() # ax.add_feature(cfeature.LAND) # ax.add_feature(cfeature.COASTLINE, lw=0.3) # ax.add_feature(cfeature.RIVERS, lw=0.3) # ax.add_feature(cfeature.LAKES) # ax.add_feature(cfeature.OCEAN) extent = [100, 180, 0, 60] ax.set_extent(extent) gl = ax.gridlines(crs=ccrs.PlateCarree(),