'width': width, 'height': height }) with rasterio.open('C:/data/new_tif', 'w', **profile) as dst: rasterio.warp.reproject( source=rasterio.band(src, 1), destination=rasterio.band(dst, 1), src_transform=transform, src_crs=source_crs, dst_transform=transform, dst_crs={'init': 'EPSG:3857'}, resampling=rasterio.warp.Resampling.bilinear) source_crs = ccrs.LambertConformal(central_longitude=-95,central_latitude=38.936454, cutoff=20) ax = plt.subplot(projection = ccrs.LambertConformal(central_longitude=-95,central_latitude=38.936454, cutoff=20)) ax.add_feature(shape_michigan['MI'], facecolor='none', edgecolor='yellow', linewidth=0.5) def main(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) ax.set_extent([40, 45, -90, -85], crs=ccrs.PlateCarree()) ax.add_feature(cfeature.LAND) ax.add_feature(cfeature.OCEAN) ax.add_feature(cfeature.COASTLINE) ax.add_feature(cfeature.BORDERS, linestyle=':') ax.add_feature(cfeature.LAKES, alpha=0.5) ax.add_feature(cfeature.RIVERS)
def generate_season(fin, vmin, vmax): # Where to save images # If the directory does not exist, we create it rep0 = config.repout if not(os.path.exists(rep0)): os.makedirs(rep0) rep1 = os.path.join(rep0, 'seasonavg') if not(os.path.exists(rep1)): os.makedirs(rep1) # Projection for plotting proj = ccrs.LambertConformal(central_latitude = 37, central_longitude = 10, standard_parallels = (37, 37) ) file_name = os.path.basename(fin) var = file_name.split("_")[0] # Open file as a dataset d = nc.Dataset(fin) # Read data, latitude, longitude, time data = d[var][:,:,:] name = d[var].long_name units = d[var].units lat = d['lat'][:,:] lon = d['lon'][:,:] d.close() # Temporal mean - season data_winter = data[0] + data[1] data_spring = 0 data_summer = 0 data_fall = 0 for i in range(10): if i<9: data_winter = data_winter + data[11+12*i] + data[12+12*i] + data[13+12*i] data_spring = data_spring + data[2+12*i] + data[3+12*i] + data[4+12*i] data_summer = data_summer + data[5+12*i] + data[6+12*i] + data[7+12*i] data_fall = data_fall + data[8+12*i] + data[9+12*i] + data[10+12*i] data_winter_moy = data_winter/29 data_spring_moy = data_spring/30 data_summer_moy = data_summer/30 data_fall_moy = data_fall/30 #PLOTS # Domain to be plotted bbox = [-24,44,14,56] # Map projection is Lambert Conformal (proj) fig, axes = plt.subplots(2,2,figsize=(15,10),subplot_kw=dict(projection=proj)) data_season = [data_winter_moy, data_spring_moy, data_summer_moy, data_fall_moy] title_season = ['winter','spring','summer','fall'] for i, ax in enumerate(axes.flat): # Apply domain to be plotted ax.set_extent(bbox,crs=ccrs.PlateCarree()) # Add coastlines ax.coastlines('50m') # Add country borders ax.add_feature(cf.BORDERS) # *must* call draw in order to get the axis boundary used to add ticks fig.canvas.draw() xticks = range(-180,181,10) yticks = range(-90,91,10) ax.gridlines(xlocs=xticks, ylocs=yticks,linestyle='--',lw=1,color='dimgrey') # Label the end-points of the gridlines using the custom tick makers: ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER) ax.yaxis.set_major_formatter(LATITUDE_FORMATTER) lambert_xticks(ax, xticks) lambert_yticks(ax, yticks) # Plot data if var == "pctisccp" or var == "pctmodis": # if pct convert to hPa data_season[i] /= 100 units = "hPa" ax.set_title('{0} ({1})\n[2007-2016] - {2}'.format(name,units,title_season[i])) cs = ax.pcolormesh(lon,lat,data_season[i], transform=ccrs.PlateCarree(), cmap=cm.gist_ncar, vmin=vmin, vmax=vmax,shading='gouraud') # Add colorbar fig.subplots_adjust(right=0.8, hspace=0.5) cbar = fig.colorbar(cs, ax=axes[:,:], shrink=0.5, orientation='horizontal',pad=0.1) # Save in png plot_name = '{}.png'.format(var) plot_path = os.path.join(rep1, plot_name) plt.savefig(plot_path, bbox_inches='tight') print("Plot saved at {}".format(plot_path)) plt.close()
# the level variable is 'isobaric1'. Unfortunately, these can be different with # each file you use, so you'll always need to check what they are by listing # the coordinate variable names # print(data.Geopotential_height.coords) hght_500 = data.Geopotential_height.sel(time=vtimes[0], isobaric1=500) uwnd_500 = data.u_wind.sel(time=vtimes[0], isobaric1=500) vwnd_500 = data.v_wind.sel(time=vtimes[0], isobaric1=500) ######################################## # Now make the 500-hPa map # ------------------------ # Must set data projection, NAM is LCC projection datacrs = ccrs.LambertConformal( central_latitude=data.Lambert_Conformal.latitude_of_projection_origin, central_longitude=data.Lambert_Conformal.longitude_of_central_meridian) # A different LCC projection for the plot. plotcrs = ccrs.LambertConformal(central_latitude=45., central_longitude=-100., standard_parallels=[30, 60]) states_provinces = cfeature.NaturalEarthFeature( category='cultural', name='admin_1_states_provinces_lakes', scale='50m', facecolor='none') fig = plt.figure(figsize=(17., 11.)) ax = plt.axes(projection=plotcrs) ax.coastlines('50m', edgecolor='black')
def plot_all(dom): t1dom = time.perf_counter() print(('Working on ' + dom)) # Map corners for each domain llcrnrlon = np.min(lon) llcrnrlat = np.min(lat) urcrnrlon = np.max(lon) urcrnrlat = np.max(lat) lat_0 = Lat0 lon_0 = Lon0 extent = [llcrnrlon, urcrnrlon, llcrnrlat - 1, urcrnrlat] # create figure and axes instances fig = plt.figure(figsize=(10, 10)) ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # Define where Cartopy Maps are located cartopy.config['data_dir'] = CARTOPY_DIR os.environ["CARTOPY_USER_BACKGROUNDS"] = CARTOPY_DIR + '/raster_files' back_res = '50m' back_img = 'off' # set up the map background with cartopy myproj = ccrs.LambertConformal(central_longitude=lon_0, central_latitude=lat_0, false_easting=0.0, false_northing=0.0, secant_latitudes=None, standard_parallels=None, globe=None) ax = plt.axes(projection=myproj) ax.set_extent(extent) fline_wd = 0.5 # line width falpha = 0.3 # transparency # natural_earth # land=cfeature.NaturalEarthFeature('physical','land',back_res, # edgecolor='face',facecolor=cfeature.COLORS['land'], # alpha=falpha) lakes = cfeature.NaturalEarthFeature('physical', 'lakes', back_res, edgecolor='blue', facecolor='none', linewidth=fline_wd, alpha=falpha) coastline = cfeature.NaturalEarthFeature('physical', 'coastline', back_res, edgecolor='blue', facecolor='none', linewidth=fline_wd, alpha=falpha) states = cfeature.NaturalEarthFeature('cultural', 'admin_1_states_provinces', back_res, edgecolor='black', facecolor='none', linewidth=fline_wd, linestyle=':', alpha=falpha) borders = cfeature.NaturalEarthFeature('cultural', 'admin_0_countries', back_res, edgecolor='red', facecolor='none', linewidth=fline_wd, alpha=falpha) # high-resolution background images if back_img == 'on': ax.background_img(name='NE', resolution='high') # ax.add_feature(land) ax.add_feature(lakes) ax.add_feature(states) ax.add_feature(borders) ax.add_feature(coastline) # All lat lons are earth relative, so setup the associated projection correct for that data transform = ccrs.PlateCarree() # Map/figure has been set up here, save axes instances for use again later keep_ax_lst = ax.get_children()[:] ################################ # Plot SLP ################################ t1 = time.perf_counter() print(('Working on slp for ' + dom)) units = 'mb' clevs = [ 976, 980, 984, 988, 992, 996, 1000, 1004, 1008, 1012, 1016, 1020, 1024, 1028, 1032, 1036, 1040, 1044, 1048, 1052 ] clevsdif = [-12, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10, 12] cm = plt.cm.Spectral_r norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs1_a = plt.pcolormesh(lon_shift, lat_shift, slp, transform=transform, cmap=cm, norm=norm) cbar1 = plt.colorbar(cs1_a, orientation='horizontal', pad=0.05, shrink=0.6, extend='both') cbar1.set_label(units, fontsize=8) cbar1.ax.tick_params(labelsize=8) cs1_b = plt.contour(lon_shift, lat_shift, slpsmooth, np.arange(940, 1060, 4), colors='black', linewidths=1.25, transform=transform) plt.clabel(cs1_b, np.arange(940, 1060, 4), inline=1, fmt='%d', fontsize=8) ax.text(.5, 1.03, 'WRF SLP (' + units + ') \n initialized: ' + itime + ' valid: ' + vtime + ' (f' + fhour + ')', horizontalalignment='center', fontsize=8, transform=ax.transAxes, bbox=dict(facecolor='white', alpha=0.85, boxstyle='square,pad=0.2')) compress_and_save('slp_' + dom + '_f' + fhour + '.png') t2 = time.perf_counter() t3 = round(t2 - t1, 3) print(('%.3f seconds to plot slp for: ' + dom) % t3) plt.clf()
lats * units.degrees, dim_order='yx') ###################################################################### # Map Creation # ------------ # # This next set of code creates the plot and draws contours on a Lambert # Conformal map centered on -100 E longitude. The main view is over the # CONUS with geopotential heights contoured every 60 m and absolute # vorticity colorshaded (:math:`*10^5`). # # Set up the projection that will be used for plotting mapcrs = ccrs.LambertConformal(central_longitude=-100, central_latitude=35, standard_parallels=(30, 60)) # Set up the projection of the data; if lat/lon then PlateCarree is what you want datacrs = ccrs.PlateCarree() # Start the figure and create plot axes with proper projection fig = plt.figure(1, figsize=(17, 16)) ax = plt.subplot(111, projection=mapcrs) ax.set_extent([-130, -72, 20, 55], ccrs.PlateCarree()) # Add geopolitical boundaries for map reference ax.add_feature(cfeature.COASTLINE.with_scale('50m')) ax.add_feature(cfeature.STATES.with_scale('50m')) # Absolute Vorticity colors
def exec(self): log.info('[START] {}'.format("exec")) try: if (platform.system() == 'Windows'): globalVar['inpPath'] = 'E:/DATA/OUTPUT' globalVar['outPath'] = 'E:/DATA/OUTPUT' # 옵션 설정 sysOpt = { # 시작/종료 시간 'srtDate': '2020-09-01' , 'endDate': '2020-09-03' } else: # 옵션 설정 sysOpt = { # 시작/종료 시간 'srtDate': globalVar['srtDate'] , 'endDate': globalVar['endDate'] } inpPosFile = '{}/{}'.format(globalVar['cfgPath'], 'stnInfo/GA_STN_INFO.xlsx') posData = pd.read_excel(inpPosFile) posDataL1 = posData[['id', 'lat', 'lon']] lat1D = np.array(posDataL1['lat']) lon1D = np.array(posDataL1['lon']) # lon2D, lat2D = np.meshgrid(lon1D, lat1D) if (globalVar['sysOs'] == 'Windows'): globalVar['inpPath'] = 'E:/DATA/OUTPUT' globalVar['outPath'] = 'E:/DATA/OUTPUT' # ******************************************************* # GK2A # ******************************************************* dtSrtDate = pd.to_datetime(sysOpt['srtDate'], format='%Y-%m-%d') dtEndDate = pd.to_datetime(sysOpt['endDate'], format='%Y-%m-%d') dtIncDateList = pd.date_range(start=dtSrtDate, end=dtEndDate, freq=Minute(10)) cfgFile = '{}/{}'.format(globalVar['cfgPath'], 'satInfo/gk2a_ami_le2_cld_ko020lc_202009010000.nc') log.info("[CHECK] cfgFile : {}".format(cfgFile)) cfgDs = xr.open_dataset(cfgFile) # 위/경도 반환 imgProjInfo = cfgDs['gk2a_imager_projection'].attrs # ccrs.LambertConformal() mapLccProj = ccrs.LambertConformal( central_longitude=imgProjInfo['central_meridian'] , central_latitude=imgProjInfo['origin_latitude'] , secant_latitudes=(imgProjInfo['standard_parallel1'], imgProjInfo['standard_parallel2']) , false_easting=imgProjInfo['false_easting'] , false_northing=imgProjInfo['false_northing'] ) mapLccProjInfo = '+proj=lcc +lat_0=38 +lon_0=126 +lat_1=30 +lat_2=60 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs +type=crs' try: mapLccProjInfo = mapLccProj.to_proj4() except Exception as e: log.error("Exception : {}".format(e)) mapProj = pyproj.Proj(mapLccProjInfo) nx = imgProjInfo['image_width'] ny = imgProjInfo['image_height'] xOffset = imgProjInfo['lower_left_easting'] yOffset = imgProjInfo['lower_left_northing'] res = imgProjInfo['pixel_size'] # 직교 좌표 rowEle = (np.arange(0, nx, 1) * res) + xOffset colEle = (np.arange(0, ny, 1) * res) + yOffset colEle = colEle[::-1] # posLon = posInfo['lon'] # posLat = posInfo['lat'] posRow, posCol = mapProj(lon1D, lat1D, inverse=False) # lon1D = np.array(posLon).reshape(1) # lat1D = np.array(posLat).reshape(1) # dtIncDateInfo = dtIncDateList[0] dsDataL2 = xr.Dataset() for i, dtIncDateInfo in enumerate(dtIncDateList): log.info("[CHECK] dtIncDateInfo : {}".format(dtIncDateInfo)) saveFile = '{}/TEST/SAT/GK2A_{}_{}.nc'.format(globalVar['outPath'], pd.to_datetime(dtSrtDate).strftime('%Y%m%d'), pd.to_datetime(dtEndDate).strftime('%Y%m%d')) if (os.path.exists(saveFile)): continue dtDateYm = dtIncDateInfo.strftime('%Y%m') dtDateDay = dtIncDateInfo.strftime('%d') dtDateHour = dtIncDateInfo.strftime('%H') dtDateYmdHm = dtIncDateInfo.strftime('%Y%m%d%H%M') # /SYSTEMS/OUTPUT/OBS/202109/01/AWS_OBS_202109010000.txt inpFilePattern = 'SAT/{}/{}/{}/gk2a_ami_le2_*_ko020lc_{}*.nc'.format(dtDateYm, dtDateDay, dtDateHour, dtDateYmdHm) inpFile = '{}/{}'.format(globalVar['inpPath'], inpFilePattern) fileList = sorted(glob.glob(inpFile)) if (len(fileList) < 1): continue # raise Exception("[ERROR] fileInfo : {} : {}".format("입력 자료를 확인해주세요.", inpFile)) fileInfo = fileList[0] dsData = xr.Dataset() for j, fileInfo in enumerate(fileList): # log.info("[CHECK] fileInfo : {}".format(fileInfo)) ds = xr.open_dataset(fileInfo) ds = ds.assign_coords( {"dim_x": ("dim_x", rowEle) , "dim_y": ("dim_y", colEle) } ) dsData = dsData.merge(ds) try: selNearVal = dsData.sel(dim_x=posRow, dim_y=posCol, method='nearest') selIntpVal = dsData.interp(dim_x=posRow, dim_y=posCol) dsDataL1 = xr.Dataset( { 'CA': ( ('time', 'lat', 'lon'), (selNearVal['CA'].values).reshape(1, len(lat1D), len(lon1D)) ) , 'CF': ( ('time', 'lat', 'lon'), (selNearVal['CF'].values).reshape(1, len(lat1D), len(lon1D)) ) , 'CLD': (('time', 'lat', 'lon'), (selNearVal['CLD'].values).reshape(1, len(lat1D), len(lon1D))) , 'DSR': ( ('time', 'lat', 'lon'), (selNearVal['DSR'].values).reshape(1, len(lat1D), len(lon1D)) ) , 'ASR': ( ('time', 'lat', 'lon'), (selNearVal['ASR'].values).reshape(1, len(lat1D), len(lon1D)) ) , 'RSR': ( ('time', 'lat', 'lon'), (selNearVal['RSR'].values).reshape(1, len(lat1D), len(lon1D)) ) , 'CA_intp': ( ('time', 'lat', 'lon'), (selIntpVal['CA'].values).reshape(1, len(lat1D), len(lon1D)) ) , 'CF_intp': ( ('time', 'lat', 'lon'), (selIntpVal['CF'].values).reshape(1, len(lat1D), len(lon1D)) ) , 'CLD_intp': (('time', 'lat', 'lon'), (selIntpVal['CLD'].values).reshape(1, len(lat1D), len(lon1D))) , 'DSR_intp': ( ('time', 'lat', 'lon'), (selIntpVal['DSR'].values).reshape(1, len(lat1D), len(lon1D)) ) , 'ASR_intp': ( ('time', 'lat', 'lon'), (selIntpVal['ASR'].values).reshape(1, len(lat1D), len(lon1D)) ) , 'RSR_intp': ( ('time', 'lat', 'lon'), (selIntpVal['RSR'].values).reshape(1, len(lat1D), len(lon1D)) ) } , coords={ 'time': pd.date_range(dtIncDateInfo, periods=1) , 'lat': lat1D , 'lon': lon1D } ) dsDataL2 = dsDataL2.merge(dsDataL1) except Exception as e: log.error("Exception : {}".format(e)) os.makedirs(os.path.dirname(saveFile), exist_ok=True) dsDataL2.to_netcdf(saveFile) log.info('[CHECK] saveFile : {}'.format(saveFile)) except Exception as e: log.error("Exception : {}".format(e)) raise e finally: log.info('[END] {}'.format("exec"))
# <headingcell level=2> # Find points of LambertConformal grid withing lon/lat bounding box using Cartopy # <codecell> import cartopy import cartopy.crs as ccrs # <codecell> #globe = ccrs.Globe(ellipse='WGS84') #default globe = ccrs.Globe(ellipse='sphere', semimajor_axis=grid.earth_radius) crs = ccrs.LambertConformal(central_longitude=lon0, central_latitude=lat0, standard_parallels=(lat0,lat1), globe=globe) # <codecell> #Find indices to read based on lon/lat bounding box #newcs = ccrs.PlateCarree.transform_points(crs,xx,yy) dest = ccrs.PlateCarree() #cartopy wants meters, not km x2d, y2d = np.meshgrid(uvar.x.data*1000.0, uvar.y.data*1000.0) lonlat = dest.transform_points(crs, x2d, y2d) # <codecell> print(uvar.coords.keys()) timecoord = None for coord in uvar.coords.keys():
def spatial_neuron_activations(neuron_activations, output_path, mode, model_name, gmm_name=None, cluster=False, quant_thresh=0.99): """ Plot spatial distribution of top activated storms for each neuron Args: neuron_activations: CSV file of neuron activations output_path: Output path from config model_name: Model name from config mode: Data partition (train, va, or test) quant_thresh: Quantile to select storms that exceed threshold Returns: """ if cluster: col_type = 'cluster' else: col_type = 'neuron' if gmm_name is not None: file_name = f'Spatial_activations_{model_name}_{gmm_name}_{mode}.png' else: file_name = f'Spatial_activations_{model_name}_{mode}.png' fig = plt.figure(figsize=(20, 16)) lcc = ccrs.LambertConformal(central_longitude=-97.5, standard_parallels=(38.5, 38.5)) ax = fig.add_subplot(1, 1, 1, projection=lcc) ax.set_extent([-120, -74, 25, 50], crs=ccrs.PlateCarree()) ax.add_feature(cfeature.LAND) ax.add_feature(cfeature.OCEAN) ax.add_feature(cfeature.COASTLINE) ax.add_feature(cfeature.BORDERS) ax.add_feature(cfeature.LAKES, alpha=0.5) ax.add_feature(cfeature.STATES) columns = list(neuron_activations.columns[ neuron_activations.columns.str.contains(col_type)]) colors = sns.color_palette("deep", len(columns)) for i, col in enumerate(columns): data = neuron_activations[ neuron_activations[col] > neuron_activations[col].quantile( quant_thresh)] var = data[col] plt.scatter(data['centroid_lon'], data['centroid_lat'], transform=ccrs.PlateCarree(), label=None, color=colors[i], alpha=0.25, s=2.5) sns.kdeplot(data['centroid_lon'], data['centroid_lat'], data=var, levels=3, transform=ccrs.PlateCarree(), linewidths=5, thresh=0, color=colors[i], linestyles='--', label=f'{col.capitalize()} {i}') plt.legend(prop={'size': 16}) plt.title(f'Storm Activations Above {quant_thresh} Quantile - {mode}', fontsize=30) plt.savefig(join(output_path, file_name), dpi=300, bbox_inches='tight')
def plot_ensemble_neighborhood(beg, end, model_list, label_path, model_grid_path, out_path, file_format='pkl', min_lead_time=1, max_lead_time=18, gaussian_filter_sigma=1): """ Plot neighborhood spatial probability for two distinct models using output (pickle) from run_mode_cnn.py. Args: beg (str): beginning date string for neighborhood probability (format: 'YYYYMMDDHHHH') end (str): ending date string for neighborhood probability (format: 'YYYYMMDDHHHH') (can be same or after beg) model_list (list): List of model names label_path (str): path to pickle files model_grid_path (str): Path to grid (netCDF) which to plot neighborhood probabilities on out_path (str): Path to output file file_format (str): File format of labels min_lead_time (int): Minimum model lead time max_lead_time (int): Maximum model lead time gaussian_filter_sigma: Standard deviation to be used in the spatial gaussian smoother """ model_grid = xr.open_dataset(model_grid_path) storm_grid = generate_mode_grid(beg, end, label_path, model_list, model_grid, min_lead_time, max_lead_time, file_format) lcc = ccrs.LambertConformal(central_longitude=-97.5, standard_parallels=(38.5, 38.5)) fig, axes = plt.subplots(2, 3, figsize=(30, 19.6), sharex=True, sharey=True, subplot_kw={'projection': lcc}) cmap = plt.cm.get_cmap("turbo").copy() plt.subplots_adjust(wspace=0.05, hspace=-0.35) for i, ax in enumerate(axes.ravel()): data = gaussian_filter(storm_grid[list(storm_grid.data_vars)[i]], sigma=gaussian_filter_sigma) ax.set_extent([-120, -74, 25, 50], crs=ccrs.PlateCarree()) ax.add_feature(cfeature.LAND) ax.add_feature(cfeature.OCEAN) ax.add_feature(cfeature.COASTLINE) ax.add_feature(cfeature.BORDERS) ax.add_feature(cfeature.LAKES, alpha=0.5) ax.add_feature(cfeature.STATES) p = ax.contourf(storm_grid['lon'], storm_grid['lat'], data, levels=np.linspace(0.02, 1, 11), vmin=0, vmax=1, alpha=0.75, transform=ccrs.PlateCarree(), cmap=cmap, extend=None) plt.colorbar(p, ax=ax, shrink=0.45) ax.set_title(list(storm_grid.data_vars)[i].replace('_', ' '), fontsize=18, fontweight='bold') plt.savefig(join(out_path, f'neighborhood_prob_{beg}_{end}.png'), dpi=300, bbox_inches='tight')
def plot_all(dom): t1dom = time.perf_counter() print(('Working on '+dom)) # Map corners for each domain llcrnrlon = np.min(lon) llcrnrlat = np.min(lat) urcrnrlon = np.max(lon) urcrnrlat = np.max(lat) lat_0 = Lat0 lon_0 = Lon0 extent=[llcrnrlon,urcrnrlon,llcrnrlat-1,urcrnrlat] # create figure and axes instances fig = plt.figure(figsize=(10,10)) ax1 = fig.add_axes([0.1,0.1,0.8,0.8]) # Define where Cartopy Maps are located cartopy.config['data_dir'] = CARTOPY_DIR os.environ["CARTOPY_USER_BACKGROUNDS"]=CARTOPY_DIR+'/raster_files' back_res='50m' back_img='off' # set up the map background with cartopy myproj=ccrs.LambertConformal(central_longitude=lon_0, central_latitude=lat_0, false_easting=0.0, false_northing=0.0, secant_latitudes=None, standard_parallels=None, globe=None) ax = plt.axes(projection=myproj) ax.set_extent(extent) fline_wd = 0.5 # line width falpha = 0.3 # transparency # natural_earth # land=cfeature.NaturalEarthFeature('physical','land',back_res, # edgecolor='face',facecolor=cfeature.COLORS['land'], # alpha=falpha) lakes=cfeature.NaturalEarthFeature('physical','lakes',back_res, edgecolor='blue',facecolor='none', linewidth=fline_wd,alpha=falpha) coastline=cfeature.NaturalEarthFeature('physical','coastline', back_res,edgecolor='blue',facecolor='none', linewidth=fline_wd,alpha=falpha) states=cfeature.NaturalEarthFeature('cultural','admin_1_states_provinces', back_res,edgecolor='black',facecolor='none', linewidth=fline_wd,linestyle=':',alpha=falpha) borders=cfeature.NaturalEarthFeature('cultural','admin_0_countries', back_res,edgecolor='red',facecolor='none', linewidth=fline_wd,alpha=falpha) # high-resolution background images if back_img=='on': ax.background_img(name='NE', resolution='high') # ax.add_feature(land) ax.add_feature(lakes) ax.add_feature(states) ax.add_feature(borders) ax.add_feature(coastline) # All lat lons are earth relative, so setup the associated projection correct for that data transform = ccrs.PlateCarree() # Map/figure has been set up here, save axes instances for use again later keep_ax_lst = ax.get_children()[:] ################################ # Plot SLP ################################ t1 = time.perf_counter() print(('Working on slp for '+dom)) units = 'mb' clevs = [976,980,984,988,992,996,1000,1004,1008,1012,1016,1020,1024,1028,1032,1036,1040,1044,1048,1052] clevsdif = [-12,-10,-8,-6,-4,-2,0,2,4,6,8,10,12] cm = plt.cm.Spectral_r norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs1_a = plt.pcolormesh(lon_shift,lat_shift,slp,transform=transform,cmap=cm,norm=norm) cbar1 = plt.colorbar(cs1_a,orientation='horizontal',pad=0.05,shrink=0.6,extend='both') cbar1.set_label(units,fontsize=8) cbar1.ax.tick_params(labelsize=8) cs1_b = plt.contour(lon_shift,lat_shift,slpsmooth,np.arange(940,1060,4),colors='black',linewidths=1.25,transform=transform) plt.clabel(cs1_b,np.arange(940,1060,4),inline=1,fmt='%d',fontsize=8) ax.text(.5,1.03,'FV3-LAM SLP ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('slp_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot slp for: '+dom) % t3) ################################# # Plot 2-m T ################################# t1 = time.perf_counter() print(('Working on t2m for '+dom)) # Clear off old plottables but keep all the map info cbar1.remove() clear_plotables(ax,keep_ax_lst,fig) units = '\xb0''F' clevs = np.linspace(-16,134,51) cm = cmap_t2m() norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift,lat_shift,tmp2m,transform=transform,cmap=cm,norm=norm) cs_1.cmap.set_under('white') cs_1.cmap.set_over('white') cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,ticks=[-16,-4,8,20,32,44,56,68,80,92,104,116,128],extend='both') cbar1.set_label(units,fontsize=8) cbar1.ax.tick_params(labelsize=8) ax.text(.5,1.03,'FV3-LAM 2-m Temperature ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('2mt_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot 2mt for: '+dom) % t3) ################################# # Plot 2-m Dew Point ################################# t1 = time.perf_counter() print(('Working on 2mdew for '+dom)) # Clear off old plottables but keep all the map info cbar1.remove() clear_plotables(ax,keep_ax_lst,fig) units = '\xb0''F' clevs = np.linspace(-5,80,35) cm = cmap_q2m() norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift,lat_shift,dew2m,transform=transform,cmap=cm,norm=norm) cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,extend='both') cbar1.set_label(units,fontsize=8) cbar1.ax.tick_params(labelsize=8) ax.text(.5,1.03,'FV3-LAM 2-m Dew Point Temperature ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('2mdew_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot 2mdew for: '+dom) % t3) ################################# # Plot 10-m WSPD ################################# t1 = time.perf_counter() print(('Working on 10mwspd for '+dom)) # Clear off old plottables but keep all the map info cbar1.remove() clear_plotables(ax,keep_ax_lst,fig) units = 'kts' skip = 50 barblength = 4 clevs = [5,10,15,20,25,30,35,40,45,50,55,60] colorlist = ['turquoise','dodgerblue','blue','#FFF68F','#E3CF57','peru','brown','crimson','red','fuchsia','DarkViolet'] cm = matplotlib.colors.ListedColormap(colorlist) norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift,lat_shift,wspd10m,transform=transform,cmap=cm,vmin=5,norm=norm) cs_1.cmap.set_under('white',alpha=0.) cs_1.cmap.set_over('black') cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,ticks=clevs,extend='max') cbar1.set_label(units,fontsize=8) cbar1.ax.tick_params(labelsize=8) plt.barbs(lon_shift[::skip,::skip],lat_shift[::skip,::skip],uwind[::skip,::skip],vwind[::skip,::skip],length=barblength,linewidth=0.5,color='black',transform=transform) ax.text(.5,1.03,'FV3-LAM 10-m Winds ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('10mwind_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot 10mwspd for: '+dom) % t3) ################################# # Plot Surface-Based CAPE/CIN ################################# t1 = time.perf_counter() print(('Working on surface-based CAPE/CIN for '+dom)) # Clear off old plottables but keep all the map info cbar1.remove() clear_plotables(ax,keep_ax_lst,fig) units = 'J/kg' clevs = [100,250,500,1000,1500,2000,2500,3000,3500,4000,4500,5000] clevs2 = [-2000,-500,-250,-100,-25] colorlist = ['lightblue','blue','dodgerblue','cyan','mediumspringgreen','#FAFAD2','#EEEE00','#EEC900','darkorange','crimson','darkred'] cm = matplotlib.colors.ListedColormap(colorlist) norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift,lat_shift,cape,transform=transform,cmap=cm,vmin=100,norm=norm) cs_1.cmap.set_under('white',alpha=0.) cs_1.cmap.set_over('darkviolet') cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,ticks=clevs,extend='max') cbar1.set_label(units,fontsize=8) cbar1.ax.tick_params(labelsize=8) cs_1b = plt.contourf(lon_shift,lat_shift,cin,clevs2,colors='none',hatches=['**','++','////','..'],transform=transform) ax.text(.5,1.05,'FV3-LAM Surface-Based CAPE (shaded) and CIN (hatched) ('+units+') \n <-500 (*), -500<-250 (+), -250<-100 (/), -100<-25 (.) \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('sfcape_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot surface-based CAPE/CIN for: '+dom) % t3) ################################# # Plot 500 mb HGT/WIND/VORT ################################# # t1 = time.perf_counter() # print(('Working on 500 mb Hgt/Wind/Vort for '+dom)) # # # Clear off old plottables but keep all the map info # cbar1.remove() # clear_plotables(ax,keep_ax_lst,fig) # # units = 'x10${^5}$ s${^{-1}}$' # skip = 70 # barblength = 4 # # vortlevs = [16,20,24,28,32,36,40] # colorlist = ['yellow','gold','goldenrod','orange','orangered','red'] # cm = matplotlib.colors.ListedColormap(colorlist) # norm = matplotlib.colors.BoundaryNorm(vortlevs, cm.N) # # cs1_a = plt.pcolormesh(lon_shift,lat_shift,vort500,transform=transform,cmap=cm,norm=norm) # cs1_a.cmap.set_under('white') # cs1_a.cmap.set_over('darkred') # cbar1 = plt.colorbar(cs1_a,orientation='horizontal',pad=0.05,shrink=0.6,ticks=vortlevs,extend='both') # cbar1.set_label(units,fontsize=8) # cbar1.ax.tick_params(labelsize=8) # plt.barbs(lon_shift[::skip,::skip],lat_shift[::skip,::skip],u500[::skip,::skip],v500[::skip,::skip],length=barblength,linewidth=0.5,color='steelblue',transform=transform) # cs1_b = plt.contour(lon_shift,lat_shift,z500,np.arange(486,600,6),colors='black',linewidths=1,transform=transform) # plt.clabel(cs1_b,np.arange(486,600,6),inline_spacing=1,fmt='%d',fontsize=8) # ax.text(.5,1.03,'FV3-LAM 500 mb Heights (dam), Winds (kts), and $\zeta$ ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) # # compress_and_save('500_'+dom+'_f'+fhour+'.png') # t2 = time.perf_counter() # t3 = round(t2-t1, 3) # print(('%.3f seconds to plot 500 mb Hgt/Wind/Vort for: '+dom) % t3) ################################# # Plot 250 mb WIND ################################# t1 = time.perf_counter() print(('Working on 250 mb WIND for '+dom)) # Clear off old plottables but keep all the map info cbar1.remove() clear_plotables(ax,keep_ax_lst,fig) units = 'kts' skip = 70 barblength = 4 clevs = [50,60,70,80,90,100,110,120,130,140,150] colorlist = ['turquoise','deepskyblue','dodgerblue','#1874CD','blue','beige','khaki','peru','brown','crimson'] cm = matplotlib.colors.ListedColormap(colorlist) norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift,lat_shift,wspd250,transform=transform,cmap=cm,vmin=50,norm=norm) cs_1.cmap.set_under('white',alpha=0.) cs_1.cmap.set_over('red') cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,ticks=clevs,extend='max') cbar1.set_label(units,fontsize=8) cbar1.ax.tick_params(labelsize=8) plt.barbs(lon_shift[::skip,::skip],lat_shift[::skip,::skip],u250[::skip,::skip],v250[::skip,::skip],length=barblength,linewidth=0.5,color='black',transform=transform) ax.text(.5,1.03,'FV3-LAM 250 mb Winds ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('250wind_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot 250 mb WIND for: '+dom) % t3) ################################# # Plot Total QPF ################################# if (fhr > 0): # Do not make total QPF plot for forecast hour 0 t1 = time.perf_counter() print(('Working on total qpf for '+dom)) # Clear off old plottables but keep all the map info cbar1.remove() clear_plotables(ax,keep_ax_lst,fig) units = 'in' clevs = [0.01,0.1,0.25,0.5,0.75,1,1.25,1.5,1.75,2,2.5,3,4,5,7,10,15,20] clevsdif = [-3,-2.5,-2,-1.5,-1,-0.5,0,0.5,1,1.5,2,2.5,3] colorlist = ['chartreuse','limegreen','green','blue','dodgerblue','deepskyblue','cyan','mediumpurple','mediumorchid','darkmagenta','darkred','crimson','orangered','darkorange','goldenrod','gold','yellow'] cm = matplotlib.colors.ListedColormap(colorlist) norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift,lat_shift,qpf,transform=transform,cmap=cm,vmin=0.01,norm=norm) cs_1.cmap.set_under('white',alpha=0.) cs_1.cmap.set_over('pink') cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,ticks=clevs,extend='max') cbar1.set_label(units,fontsize=8) cbar1.ax.set_xticklabels(clevs) cbar1.ax.tick_params(labelsize=8) ax.text(.5,1.03,'FV3-LAM '+fhour+'-hr Accumulated Precipitation ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('qpf_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot total qpf for: '+dom) % t3) ################################# # Plot composite reflectivity ################################# t1 = time.perf_counter() print(('Working on composite reflectivity for '+dom)) # Clear off old plottables but keep all the map info cbar1.remove() clear_plotables(ax,keep_ax_lst,fig) units = 'dBZ' clevs = np.linspace(5,70,14) clevsdif = [20,1000] colorlist = ['turquoise','dodgerblue','mediumblue','lime','limegreen','green','#EEEE00','#EEC900','darkorange','red','firebrick','darkred','fuchsia'] cm = matplotlib.colors.ListedColormap(colorlist) norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) cs_1 = plt.pcolormesh(lon_shift,lat_shift,refc,transform=transform,cmap=cm,vmin=5,norm=norm) cs_1.cmap.set_under('white',alpha=0.) cs_1.cmap.set_over('black') cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,ticks=clevs,extend='max') cbar1.set_label(units,fontsize=8) cbar1.ax.tick_params(labelsize=8) ax.text(.5,1.03,'FV3-LAM Composite Reflectivity ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) compress_and_save('refc_'+dom+'_f'+fhour+'.png') t2 = time.perf_counter() t3 = round(t2-t1, 3) print(('%.3f seconds to plot composite reflectivity for: '+dom) % t3) ################################# # Plot Max/Min Hourly 2-5 km UH ################################# # if (fhr > 0): # Do not make max/min hourly 2-5 km UH plot for forecast hour 0 # t1 = time.perf_counter() # print(('Working on Max/Min Hourly 2-5 km UH for '+dom)) # # # Clear off old plottables but keep all the map info # cbar1.remove() # clear_plotables(ax,keep_ax_lst,fig) # # units = 'm${^2}$ s$^{-2}$' # clevs = [-150,-100,-75,-50,-25,-10,0,10,25,50,75,100,150,200,250,300] ## alternative colormap for just max UH if you don't want to plot the min UH too ## colorlist = ['white','skyblue','mediumblue','green','orchid','firebrick','#EEC900','DarkViolet'] # colorlist = ['blue','#1874CD','dodgerblue','deepskyblue','turquoise','#E5E5E5','#E5E5E5','#EEEE00','#EEC900','darkorange','orangered','red','firebrick','mediumvioletred','darkviolet'] # cm = matplotlib.colors.ListedColormap(colorlist) # norm = matplotlib.colors.BoundaryNorm(clevs, cm.N) # # cs_1 = plt.pcolormesh(lon_shift,lat_shift,uh25,transform=transform,cmap=cm,norm=norm) # cs_1.cmap.set_under('darkblue') # cs_1.cmap.set_over('black') # cbar1 = plt.colorbar(cs_1,orientation='horizontal',pad=0.05,shrink=0.6,extend='both') # cbar1.set_label(units,fontsize=8) # cbar1.ax.tick_params(labelsize=8) # ax.text(.5,1.03,'FV3-LAM 1-h Max/Min 2-5 km Updraft Helicity ('+units+') \n initialized: '+itime+' valid: '+vtime + ' (f'+fhour+')',horizontalalignment='center',fontsize=8,transform=ax.transAxes,bbox=dict(facecolor='white',alpha=0.85,boxstyle='square,pad=0.2')) # # compress_and_save('uh25_'+dom+'_f'+fhour+'.png') # t2 = time.perf_counter() # t3 = round(t2-t1, 3) # print(('%.3f seconds to plot Max/Min Hourly 2-5 km UH for: '+dom) % t3) # ###################################################### t3dom = round(t2-t1dom, 3) print(("%.3f seconds to plot all variables for: "+dom) % t3dom) plt.clf()
class MapProvider: """ Provides PlotDefinitions with figures already created and the regions base map already rendered. """ _log = logging.getLogger('map_provider') # All Map Settings for Regions _region_projections = {"eu": ccrs.LambertConformal(central_longitude=10.0, central_latitude=50.0, standard_parallels=(40, 55)), "na": ccrs.LambertConformal(central_longitude=-96.0, central_latitude=39.0, standard_parallels=(33, 45)), "sa": ccrs.LambertConformal(central_longitude=-64.0, central_latitude=-36.0, standard_parallels=(-24, 5), cutoff=30), "as": ccrs.LambertConformal(central_longitude=110.0, central_latitude=24.0, standard_parallels=(21, 42)), "oc": ccrs.LambertConformal(central_longitude=145.0, central_latitude=-25.0, standard_parallels=(-28, -11), cutoff=30)} _region_extent = {"eu": [-10, 27, 33, 70], "na": [-119, -68, 11, 55], "sa": [-93, -33, -54, 15], "as": [81, 140, -3, 55], "oc": [110, 180, -45, 2]} # If no color is provided the default DefaultColorScheme will be used for that region _region_custom_color = {"na": NorthAmericaColorScheme} def get_regions(self): """ Provides a list of regions supported by this MapProvider :return: List of supported regions """ return list(self._region_projections.keys()) def create(self, region): color_scheme = self._region_custom_color.get(region, DefaultColorScheme) fig = plt.figure(figsize=(12, 12)) # create a figure to contain the plot elements projection = self._region_projections[region] ax = plt.axes(projection=projection) ax.set_extent(self._region_extent[region]) ax.background_patch.set_facecolor(color_scheme.MAP_COLOR_WATER) self._add_base_features(ax, color_scheme) # Since the original extend box is a rectangle only in the PlateCarree projection we need to # project this bounding box onto the actual projection obtaining a more complex shape in general unprojected_poly = box(ax.viewLim.x0, ax.viewLim.y0, ax.viewLim.x1, ax.viewLim.y1) region_box = ccrs.PlateCarree().project_geometry(unprojected_poly, projection) # Returns minimum bounding region (minx, miny, maxx, maxy) # This region covers all of the actually visible map or more, since it is a box in the # PlatteCarree projection which completely fills the actual projection x_min, y_min, x_max, y_max = region_box.bounds bbox = str(x_min) + "," + str(y_min) + "," + str(x_max) + "," + str(y_max) return PlotDefinition(projection, fig, ax, region_box, bbox, color_scheme) @staticmethod def _add_base_features(ax, color_scheme): """ Adds Countries, Coastlines, Land, Lakes and Water to the base map. :param ax: Axis to which the features will be rendered :param color_scheme: The color scheme to use for the base map features """ # COUNTRIES AND LAND MASSES ax.add_feature(cfeature.NaturalEarthFeature( category='cultural', name='admin_0_countries', scale='50m', facecolor=color_scheme.MAP_COLOR_LAND, edgecolor=color_scheme.MAP_COLOR_COUNTRIES, linewidth=0.3)) # COASTLINES ax.add_feature(cfeature.NaturalEarthFeature( category='physical', name='coastline', scale='50m', facecolor='none', edgecolor=color_scheme.MAP_COLOR_COASTLINES, linewidth=0.5)) # LAKES ax.add_feature(cfeature.NaturalEarthFeature( category='physical', name='lakes', scale='50m', facecolor=color_scheme.MAP_COLOR_WATER, edgecolor=color_scheme.MAP_COLOR_COASTLINES, linewidth=0.25))
# debut des graphiques import matplotlib.pylab as plt import cartopy.crs as ccrs import cartopy.feature as cfeature ## Lecture du fichier filename = 'J:/REANALYSES/ERA5/PR_1h_Outaouais/tmp/ERA5_count_Fr_Th.nc' nc_fid = Dataset(filename, 'r') data = nc_fid.variables['Fr_Th'][:].squeeze() lons = nc_fid.variables['longitude'][:].squeeze() lats = nc_fid.variables['latitude'][:].squeeze() lon2d, lat2d = np.meshgrid(lons, lats) # prectot de l annee courant fig = plt.figure(figsize=(28, 16)) ax = plt.subplot(111, projection=ccrs.LambertConformal()) ax.set_extent([-82, -72, 45, 48]) # ax.coastlines(resolution='110m'); ax.add_feature(cfeature.OCEAN.with_scale('50m')) # couche ocean ax.add_feature(cfeature.LAND.with_scale('50m')) # couche land ax.add_feature(cfeature.LAKES.with_scale('50m')) # couche lac ax.add_feature(cfeature.BORDERS.with_scale('50m')) # couche frontieres ax.add_feature(cfeature.RIVERS.with_scale('50m')) # couche rivières coast = cfeature.NaturalEarthFeature( category='physical', scale='10m', # ajout de la couche cotière facecolor='none', name='coastline') ax.add_feature(coast, edgecolor='black') states_provinces = cfeature.NaturalEarthFeature(
reader = csv.reader(data, delimiter=',') for row in reader: states.append(row[0].rstrip()) numbs.append(float(row[1])) print(min(numbs)) print(max(numbs)) for i in range(50): data_dict.setdefault(states[i],numbs[i]) #print(states) #print(numbs) #print(data_dict) fig = plt.figure() ax = plt.axes([0,0,1,1],projection=ccrs.LambertConformal()) ax.set_extent([-160,-72,20,72],ccrs.Geodetic()) shape_name = 'admin_1_states_provinces_lakes_shp' states_shp = shp_reader.natural_earth(resolution='110m',category='cultural',name=shape_name) c = np.arange(1, 6) norm = mpl.colors.Normalize(vmin=c.min(), vmax=c.max()) cmap = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.PuBu) cmap.set_array([]) ax.outline_patch.set_visible(False) for states in shp_reader.Reader(states_shp).records(): edge_color = 'black' try:
def draw_etopo1(fname, cmap, vminmax=[10,10000]): ip = 10 # iskip minlat, maxlat, minlon, maxlon = [110, 290, 230, 450] minlat1, maxlat1, minlon1, maxlon1 = [110, 290, 230, 450] minlat2, maxlat2, minlon2, maxlon2 = [300, 470, 90, 280] bands = [412,443,490,555,660,680,745,865] nx, ny = [5685, 5567] ngrid = nx*ny dx, dy = 1., 1. minLat, maxLat, minLon, maxLon = 21., 50., 111., 150. lat_1deg = np.arange(minLat,maxLat+dy,dy) lon_1deg = np.arange(minLon,maxLon+dx,dx) lat_25km = np.arange(minLat,maxLat+dy/4.,dy/4.) lon_25km = np.arange(minLon,maxLon+dx/4.,dx/4.) lon = np.memmap('../../extra/LON.img',dtype='<f4').reshape((nx,ny)) lat = np.memmap('../../extra/LAT.img',dtype='<f4').reshape((nx,ny)) #dem = np.memmap('../../extra/GOCI_DEM.pxl',dtype='<f4').reshape((nx,ny)) #mu1 = np.memmap('../../extra/GDPS_MASK.in',dtype='<u1').reshape((nx,ny)) # fname_he5 = "./COMS_GOCI_L2C_GA_20190415031643.he5" # with h5py.File(fname_he5, mode='r') as f: # dset = f['/HDFEOS/GRIDS/Image Data/Data Fields/FLAG Image Pixel Values'][:,:] # bits = np.unpackbits(dset.view(np.uint8),bitorder='little').reshape(*dset.shape, 32) # bits1 = bits[:,:,31]*1000 + bits[:,:,30]*100 + bits[:,:,29]*10 + bits[:,:,28] # bits1 = bits1.astype(np.str) # slot = np.array([ int(bits1[i,j],2) for i in range(nx) for j in range(ny) ]).reshape((nx,ny)) # slot = np.where(bits[:,:,27] == 1, np.nan, slot) # np.save("./Slot_GOCI.npy",slot) slot = np.load("./Slot_GOCI.npy") # import metpy.calc as mpcalc # slot0 = mpcalc.smooth_n_point(slot, 9, 1) # print(slot0) # slot = slot - slot0 # slot = np.where(slot == 0.0, np.nan, slot) # slot = slot1 - slot2 lccproj = ccrs.LambertConformal(central_latitude=36, central_longitude=130) orthproj = ccrs.Orthographic(central_latitude=36,central_longitude=130) mecproj = ccrs.Mercator(central_longitude=130,min_latitude=21,max_latitude=51) geoproj = ccrs.Geostationary(central_longitude=130) plateproj = ccrs.PlateCarree() proj = plateproj #x, y, z = lon, lat, slot x, y, z = lon[::ip,::ip], lat[::ip,::ip], slot[::ip,::ip] vmin, vmax = vminmax fig = plt.figure(figsize=(10,4)) ax = fig.add_subplot(121, projection = lccproj, aspect = "equal") #projection = orthproj, #projection = plateproj, #projection = geoproj, ax.set_extent([115,145.5,21,49.5]) # ax.stock_img() n = 16 cmap = cm.get_cmap(cmap,n) bounds = np.arange(n+1) vals = bounds[:-1] norm = colors.BoundaryNorm(bounds,cmap.N) cmap.set_under(color=cf.COLORS['land']) # cmap.set_bad(color='k') mesh = ax.pcolormesh(x, y, z, transform=proj, cmap= cmap, norm=norm )#vmin=-0.5, vmax=0.5) cb = plt.colorbar(mesh, ax=ax, fraction=0.03, boundaries=bounds, values=vals) cb.ax.tick_params(length=0) cb.set_label(label='Slot number of GOCI', size=12, labelpad=10, rotation=-90) cb.set_ticks(vals[::2] + 0.5) cb.set_ticklabels(['Slot_{:02d}'.format(i+1) for i in vals[::2]]) ax.set_title('GOCI Slot and Test sites',fontsize=14,)# weight='bold') ax.set_xlabel('Longitude',fontsize=12) ax.set_ylabel('Latitude',fontsize=12) ax.coastlines(resolution='10m', color='black', linewidth=1) fig.canvas.draw() of = pd.read_csv('./geoinfo_obs_sample.csv') for i, (flat, flon, name) in enumerate(zip(np.array(of["Lat"]),np.array(of["Lon"]),np.array(of["Name"]))): ax.scatter(x=flon, y=flat+0.25, s=25, marker='o', c='r', transform=proj) ax.text( flon, flat+1.5, name, c='r', fontsize=14, weight='bold', ha='center',va='center', transform=proj) xticks=[105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155] yticks=[15, 20, 25, 30, 35, 40, 45, 50, 55] ax.gridlines(xlocs=xticks, ylocs=yticks, lw=1, color='gray', alpha=0.5, linestyle='--') ax.add_feature(cf.LAND) ax.add_feature(cf.OCEAN)#, facecolor='blue') ax.add_feature(cf.BORDERS) ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER) ax.yaxis.set_major_formatter(LATITUDE_FORMATTER) lambert_xticks(ax, xticks) lambert_yticks(ax, yticks) axL = fig.add_subplot(122, projection = lccproj, aspect = "equal") axL.set_extent([122.5,133,32,38.5]) # ax.stock_img() axL.set_title('Meteorological observation',fontsize=14,) # weight='bold') #axL.set_title('MET OBS',fontsize=14, weight='bold') axL.set_xlabel('Longitude',fontsize=12) axL.set_ylabel('Latitude',fontsize=12) axL.coastlines(resolution='10m', color='black', linewidth=1) fig.canvas.draw() of = pd.read_csv('./geoinfo_obs.csv') for i, (flat, flon, name, ha, inst) in enumerate(zip(np.array(of["Lat"]), np.array(of["Lon"]),np.array(of["Name"]),np.array(of["ha"]),np.array(of["Instrument"]))): if ha=='left': fha = 0.25 else: fha = -0.25 if inst=='Buoy': axL.scatter(x=flon, y=flat, s=25, marker='o', label='Buoy', facecolors='none', edgecolors='k', linewidth=1.25, transform=proj) axL.text( flon+fha, flat-0.025, name, c='k', fontsize=12, ha=ha,va='center', transform=proj) else: axL.scatter(x=flon, y=flat, s=25, marker='o', label='IGRA', c='k', transform=proj) axL.text( flon+fha, flat-0.025, name, c='k', fontsize=12, ha=ha,va='center', transform=proj) xticks=[120, 122, 124, 126, 128, 130, 132, 134] yticks=[30, 32, 34, 36, 38, 40] axL.gridlines(xlocs=xticks, ylocs=yticks, lw=1, color='gray', alpha=0.5, linestyle='--') axL.add_feature(cf.LAND) axL.add_feature(cf.OCEAN)#, facecolor='blue') axL.add_feature(cf.BORDERS) axL.xaxis.set_major_formatter(LONGITUDE_FORMATTER) axL.yaxis.set_major_formatter(LATITUDE_FORMATTER) lambert_xticks(axL, xticks) lambert_yticks(axL, yticks) legend_elements = [ Line2D([0], [0], marker='o', color='w', label='Buoy', markeredgecolor='k', markerfacecolor='none', markersize=12), Line2D([0], [0], marker='o', color='w', label='IGRA', markerfacecolor='k', markersize=12), ] axL.legend(handles=legend_elements, loc='lower right') axL.text(x=-0.05,y=1.0, s="b", fontsize=20, weight='bold', ha='center', va='bottom', transform=axL.transAxes) ax.text(x=-0.05,y=1.0, s="a", fontsize=20, weight='bold', ha='center', va='bottom', transform=ax.transAxes) plt.tight_layout() plt.savefig(fname,dpi=500) plt.show()
ds = f.to_dataset() x = ds.variables['x'][:] y = ds.variables['y'][:] dat = ds.variables['WV'] proj_var = ds.variables[dat.grid_mapping] print(proj_var) ########################################### # Create CartoPy projection information for the file globe = ccrs.Globe(ellipse='sphere', semimajor_axis=proj_var.earth_radius, semiminor_axis=proj_var.earth_radius) proj = ccrs.LambertConformal( central_longitude=proj_var.longitude_of_central_meridian, central_latitude=proj_var.latitude_of_projection_origin, standard_parallels=[proj_var.standard_parallel], globe=globe) ########################################### # Plot the image fig = plt.figure(figsize=(10, 12)) add_metpy_logo(fig, 125, 145) ax = fig.add_subplot(1, 1, 1, projection=proj) wv_norm, wv_cmap = ctables.registry.get_with_range('WVCIMSS', 100, 260) wv_cmap.set_under('k') im = ax.imshow(dat[:], cmap=wv_cmap, norm=wv_norm, extent=ds.img_extent,
# lats[day].append(lat) # lons[day].append(lon) # In[60]: states_provinces = cfeature.NaturalEarthFeature( category="cultural", name="admin_1_states_provinces_lines", scale="10m", facecolor="none") # In[89]: # projection = ccrs.PlateCarree() projection = ccrs.LambertConformal(central_latitude=25, central_longitude=265, standard_parallels=(25, 25)) fig = plt.figure(figsize=(16, 9), dpi=300) ax = plt.axes(projection=projection) lon1, lon2 = 236, 299 lat1, lat2 = 22, 55 ax_extent = [lon1, lon2, lat1, lat2] bg_extent = [lon1 - 360, lon2 - 360, lat1, lat2] ax.set_extent(ax_extent) # ax.stock_img() PyGuymer3.add_map_background(ax, name="natural-earth-1",
def generate_season_lw_sw_toa(fin1, fin2, data_type, vmin, vmax): # Where to save images # If the directory does not exist, we create it rep0 = config.repout if not (os.path.exists(rep0)): os.makedirs(rep0) rep1 = os.path.join(rep0, 'seasonavg') if not (os.path.exists(rep1)): os.makedirs(rep1) # Projection for plotting proj = ccrs.LambertConformal(central_latitude=37, central_longitude=10, standard_parallels=(37, 37)) file_name1 = os.path.basename(fin1) file_name2 = os.path.basename(fin2) var1 = file_name1.split("_")[0] var2 = file_name2.split("_")[0] # Open file as a dataset d1 = nc.Dataset(fin1) d2 = nc.Dataset(fin2) # Read data, latitude, longitude, time data1 = d1[var1][:, :, :] data2 = d2[var2][:, :, :] units = d1[var1].units lat = d1['lat'][:, :] lon = d1['lon'][:, :] d1.close() d2.close() # Temporal mean - season data_1 = [0, 0, 0, 0] data_2 = [0, 0, 0, 0] data_1_moy = [0, 0, 0, 0] data_2_moy = [0, 0, 0, 0] data_season = [0, 0, 0, 0] for i in range(10): for j in range(4): data_1[j] = data_1[j] + data1[335 + 3 * j + 12 * i] + data1[ 336 + 3 * j + 12 * i] + data1[337 + 3 * j + 12 * i] data_2[j] = data_2[j] + data2[335 + 3 * j + 12 * i] + data2[ 336 + 3 * j + 12 * i] + data2[337 + 3 * j + 12 * i] for j in range(4): data_1_moy[j] = data_1[j] / 30 data_2_moy[j] = data_2[j] / 30 for j in range(4): data_season[j] = (data_2_moy[j] - data_1_moy[j]) #PLOTS # Domain to be plotted bbox = [-24, 44, 14, 56] # Map projection is Lambert Conformal (proj) fig, axes = plt.subplots(2, 2, figsize=(15, 10), subplot_kw=dict(projection=proj)) title_season = ['winter', 'spring', 'summer', 'fall'] for i, ax in enumerate(axes.flat): # Apply domain to be plotted ax.set_extent(bbox, crs=ccrs.PlateCarree()) # Add coastlines ax.coastlines('50m') # Add country borders ax.add_feature(cf.BORDERS) # *must* call draw in order to get the axis boundary used to add ticks fig.canvas.draw() xticks = range(-180, 181, 10) yticks = range(-90, 91, 10) ax.gridlines(xlocs=xticks, ylocs=yticks, linestyle='--', lw=1, color='dimgrey') # Label the end-points of the gridlines using the custom tick makers: ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER) ax.yaxis.set_major_formatter(LATITUDE_FORMATTER) lambert_xticks(ax, xticks) lambert_yticks(ax, yticks) ax.set_title('TOA CRE {0} ({1}) - [2007-2016] - {2}'.format( data_type, units, title_season[i])) # Plot data cs = ax.pcolormesh(lon, lat, data_season[i], transform=ccrs.PlateCarree(), cmap=cm.gist_ncar, vmin=vmin, vmax=vmax, shading='gouraud') # Add colorbar fig.subplots_adjust(right=0.88, bottom=0.005, top=0.95, wspace=0.5) cbar = fig.colorbar(cs, ax=axes, shrink=0.5, orientation='horizontal', pad=0.07) # Save in png plot_name = '{}_TOA_CRE.png'.format(data_type) plot_path = os.path.join(rep1, plot_name) plt.savefig(plot_path, bbox_inches='tight') print("Plot saved at {}".format(plot_path)) plt.close()
def get_map_projection( proj_name, central_longitude=0.0, central_latitude=0.0, false_easting=0.0, false_northing=0.0, globe=None, standard_parallels=(20.0, 50.0), scale_factor=None, min_latitude=-80.0, max_latitude=84.0, true_scale_latitude=None, latitude_true_scale=None, ### BOTH secant_latitudes=None, pole_longitude=0.0, pole_latitude=90.0, central_rotated_longitude=0.0, sweep_axis='y', satellite_height=35785831, cutoff=-30, approx=None, southern_hemisphere=False, zone=15): #### numeric UTM zone proj_name = proj_name.lower() if (proj_name == 'albersequalarea'): proj = ccrs.AlbersEqualArea(central_longitude=central_longitude, central_latitude=central_latitude, false_easting=false_easting, false_northing=false_northing, globe=globe, standard_parallels=standard_parallels) elif (proj_name == 'azimuthalequidistant'): proj = ccrs.AzimuthalEquidistant(central_longitude=central_longitude, central_latitude=central_latitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'equidistantconic'): proj = ccrs.EquidistantConic(central_longitude=central_longitude, central_latitude=central_latitude, false_easting=false_easting, false_northing=false_northing, globe=globe, standard_parallels=standard_parallels) elif (proj_name == 'lambertconformal'): proj = ccrs.LambertConformal( central_longitude=-96.0, ########## central_latitude=39.0, ########## false_easting=false_easting, false_northing=false_northing, globe=globe, secant_latitudes=None, standard_parallels=None, ## default: (33,45) cutoff=cutoff) elif (proj_name == 'lambertcylindrical'): proj = ccrs.LambertCylindrical(central_longitude=central_longitude) elif (proj_name == 'mercator'): proj = ccrs.Mercator(central_longitude=central_longitude, min_latitude=min_latitude, max_latitude=max_latitude, latitude_true_scale=latitude_true_scale, false_easting=false_easting, false_northing=false_northing, globe=globe, scale_factor=None) ######### elif (proj_name == 'miller'): proj = ccrs.Miller(central_longitude=central_longitude, globe=globe) elif (proj_name == 'mollweide'): proj = ccrs.Mollweide(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'orthographic'): proj = ccrs.Orthographic(central_longitude=central_longitude, central_latitude=central_latitude, globe=globe) elif (proj_name == 'robinson'): proj = ccrs.Robinson(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'sinusoidal'): proj = ccrs.Sinusoidal(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'stereographic'): proj = ccrs.Stereographic(central_latitude=central_latitude, central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe, true_scale_latitude=true_scale_latitude, scale_factor=scale_factor) elif (proj_name == 'transversemercator'): proj = ccrs.TransverseMercator( central_longitude=central_longitude, central_latitude=central_latitude, false_easting=false_easting, false_northing=false_northing, globe=globe, scale_factor=1.0, ########## approx=approx) elif (proj_name == 'utm'): proj = ccrs.UTM(zone, southern_hemisphere=southern_hemisphere, globe=globe) elif (proj_name == 'interruptedgoodehomolosine'): proj = ccrs.InterruptedGoodeHomolosine( central_longitude=central_longitude, globe=globe) elif (proj_name == 'rotatedpole'): proj = ccrs.RotatedPole( pole_longitude=pole_longitude, pole_latitude=pole_latitude, globe=globe, central_rotated_longitude=central_rotated_longitude) elif (proj_name == 'osgb'): proj = ccrs.OSGB(approx=approx) elif (proj_name == 'europp'): proj = ccrs.EuroPP elif (proj_name == 'geostationary'): proj = ccrs.Geostationary(central_longitude=central_longitude, satellite_height=satellite_height, false_easting=false_easting, false_northing=false_northing, globe=globe, sweep_axis=sweep_axis) elif (proj_name == 'nearsideperspective'): proj = ccrs.NearsidePerspective(central_longitude=central_longitude, central_latitude=central_latitude, satellite_height=satellite_height, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckerti'): proj = ccrs.EckertI(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertii'): proj = ccrs.EckertII(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertiii'): proj = ccrs.EckertIII(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertiv'): proj = ccrs.EckertIV(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertv'): proj = ccrs.EckertV(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'eckertvi'): proj = ccrs.EckertVI(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'equalearth'): proj = ccrs.EqualEarth(central_longitude=central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) elif (proj_name == 'gnomonic'): proj = ccrs.Gnomonic(central_latitude=central_latitude, central_longitude=central_longitude, globe=globe) elif (proj_name == 'lambertazimuthalequalarea'): proj = ccrs.LambertAzimuthalEqualArea( central_longitude=central_longitude, central_latitude=central_latitude, globe=globe, false_easting=false_easting, false_northing=false_northing) elif (proj_name == 'northpolarstereo'): proj = ccrs.NorthPolarStereo(central_longitude=central_longitude, true_scale_latitude=true_scale_latitude, globe=globe) elif (proj_name == 'osni'): proj = ccrs.OSNI(approx=approx) elif (proj_name == 'southpolarstereo'): proj = ccrs.SouthPolarStereo(central_longitude=central_longitude, true_scale_latitude=true_scale_latitude, globe=globe) else: # This is same as "Geographic coordinates" proj = ccrs.PlateCarree(central_longitude=central_longitude, globe=globe) return proj
fnl_vwnd = units('m/s') * ndimage.gaussian_filter(vwnd_vars, sigma=2, order=0) lon = hght_data.variables['lon'][:] lat = hght_data.variables['lat'][:] time = hght_data.variables[ hght_data.variables['Geopotential_height_isobaric'].dimensions[0]] vtime = num2date(time[:], time.units) ntime = vtime[0] datatime = ntime.strftime("%H:%M" + "Z") # Use MetPy to parse the wind data. wndspeed = mpcalc.wind_speed(fnl_uwnd, fnl_vwnd).to('kt') # Define the projection. ax = plt.axes(projection=ccrs.LambertConformal( central_latitude=35, central_longitude=-101, standard_parallels=(30, 60))) # Create the map figure. fig = plt.figure(1, figsize=(10, 10)) ax.set_extent([-125, -89, 25, 50], ccrs.PlateCarree()) # Create the map features. ax.add_feature(cfeature.OCEAN.with_scale('50m'), facecolor='#F2F2F2', edgecolor='black', zorder=0, linewidth=.5) ax.add_feature(cfeature.LAND.with_scale('50m'), edgecolor='black', facecolor='#E1E1E1', zorder=1)
plt.text(ny_lon - 3, ny_lat - 12, 'Delaware', horizontalalignment='right', transform=ccrs.Geodetic()) plt.text(delhi_lon + 3, delhi_lat - 12, 'Seoul', horizontalalignment='left', transform=ccrs.Geodetic()) # Cartopy Fundamentals - Features (cfeatures) # 5th figure import cartopy.feature as cf plt.figure() ax = plt.axes(projection = ccrs.LambertConformal()) ax.add_feature(cf.COASTLINE) ax.set_title("Title") # 6th figure import numpy as np import cartopy.feature as cf central_lat = 37.5 central_lon = -96 extent = [-120, -70, 24, 50.5] central_lon = np.mean(extent[:2]) central_lat = np.mean(extent[2:]) plt.figure(figsize=(12, 6)) ax = plt.axes(projection=ccrs.AlbersEqualArea(central_lon, central_lat))
def main(): ax = plt.axes([0, 0, 1, 1], projection=ccrs.LambertConformal()) ax.set_extent([-125, -66.5, 20, 50], ccrs.Geodetic()) shapename = 'admin_1_states_provinces_lakes_shp' states_shp = shpreader.natural_earth(resolution='110m', category='cultural', name=shapename) lons, lats = sample_data() # to get the effect of having just the states without a map "background" # turn off the outline and background patches ax.background_patch.set_visible(False) ax.outline_patch.set_visible(False) plt.title('US States which intersect the track ' 'of Hurricane Katrina (2005)') # turn the lons and lats into a shapely LineString track = sgeom.LineString(list(zip(lons, lats))) # buffer the linestring by two degrees (note: this is a non-physical # distance) track_buffer = track.buffer(2) for state in shpreader.Reader(states_shp).geometries(): # pick a default color for the land with a black outline, # this will change if the storm intersects with our track facecolor = [0.9375, 0.9375, 0.859375] edgecolor = 'black' if state.intersects(track): facecolor = 'red' elif state.intersects(track_buffer): facecolor = '#FF7E00' ax.add_geometries([state], ccrs.PlateCarree(), facecolor=facecolor, edgecolor=edgecolor) ax.add_geometries([track_buffer], ccrs.PlateCarree(), facecolor='#C8A2C8', alpha=0.5) ax.add_geometries([track], ccrs.PlateCarree(), facecolor='none') # make two proxy artists to add to a legend direct_hit = mpatches.Rectangle((0, 0), 1, 1, facecolor="red") within_2_deg = mpatches.Rectangle((0, 0), 1, 1, facecolor="#FF7E00") labels = [ 'State directly intersects\nwith track', 'State is within \n2 degrees of track' ] plt.legend([direct_hit, within_2_deg], labels, loc='lower left', bbox_to_anchor=(0.025, -0.1), fancybox=True) plt.show()
def draw_total_precipitation(prep, map_extent=(107., 112, 23.2, 26.5), back_image='terrain-background', back_image_zoom=8, title="降水量实况图", draw_station=True, station_info='cities', station_size=22, just_contourf=False): """ 该程序用于显示多日的累积降水量分布特征, 2020/6/7按业务要求制作. Args: ax (matplotlib.axes.Axes): the `Axes` instance used for plotting. prep (dictionary): precipitation, dictionary: {'lon': 1D array, 'lat': 1D array, 'data': 2D array} map_extent (tuple, optional): (lonmin, lonmax, latmin, latmax),. Defaults to (107., 112, 23.2, 26.5). back_image (str, opional): the background image name. Default is stamen 'terrain-background', else is arcgis map server 'World_Physical_Map' (max zoom level is 8) back_image_zoom (int, optional): the zoom level for background image. Defaults to 8. draw_station (bool, optional): draw station name. Defaults to True. station_info (str, optional): station information, 'cities' is 260 city names, or province captial shows. station_size (int, optional): station font size. Defaults to 22. title (str, optional): title string. Defaults to "降水量实况图". Example: import pandas as pd from nmc_met_graphics.plot.precipitation import draw_total_precipitation from nmc_met_io.retrieve_micaps_server import get_model_grids # read data times = pd.date_range(start = pd.to_datetime('2020-06-02 08:00'), end = pd.to_datetime('2020-06-07 08:00'), freq='1H') dataset = get_model_grids("CLDAS/RAIN01_TRI_DATA_SOURCE", times.strftime("%y%m%d%H.000")) data = dataset.sum(dim="time") data['data'].values[data['data'].values > 2400.0] = np.nan prep = {'lon': data['lon'].values, 'lat': data['lat'].values, 'data': data['data'].values} # draw the figure draw_total_precipitation(prep); """ # set figure size fig = plt.figure(figsize=(16, 14.5)) # set map projection datacrs = ccrs.PlateCarree() mapcrs = ccrs.LambertConformal( central_longitude=np.mean(map_extent[0:1]), central_latitude=np.mean(map_extent[2:3]), standard_parallels=(30, 60)) ax = plt.axes((0.1, 0.08, 0.85, 0.92), projection=mapcrs) ax.set_extent(map_extent, crs=datacrs) # add map background add_china_map_2cartopy(ax, name='province', edgecolor='k', lw=1) add_china_map_2cartopy(ax, name='river', edgecolor='cyan', lw=1) if back_image == 'terrain-background': stamen_terrain = cimg.Stamen('terrain-background') ax.add_image(stamen_terrain, back_image_zoom) else: image = cimg.GoogleTiles(url="https://server.arcgisonline.com/arcgis/rest/services/World_Physical_Map/MapServer/tile/{z}/{y}/{x}.jpg") ax.add_image(image, back_image_zoom) # set colors and levels clevs = [50, 100, 200, 300, 400, 500, 600] colors = ['#6ab4f1', '#0001f6', '#f405ee', '#ffa900', '#fc6408', '#e80000', '#9a0001'] linewidths = [1, 1, 2, 2, 3, 4, 4] cmap, norm = mpl.colors.from_levels_and_colors(clevs, colors, extend='max') # draw precipitation contour map x, y = np.meshgrid(prep['lon'], prep['lat']) if just_contourf: _ = ax.contourf( x, y, np.squeeze(prep['data']), clevs, norm=norm, cmap=cmap, transform=datacrs, extend='max', alpha=0.5) else: _ = ax.contourf( x, y, np.squeeze(prep['data']), clevs, norm=norm, cmap=cmap, transform=datacrs, extend='max', alpha=0.1) con2 = ax.contour( x, y, np.squeeze(prep['data']), clevs, norm=norm, cmap=cmap, transform=datacrs, linewidths=linewidths) # add path effects plt.setp(con2.collections, path_effects=[ path_effects.SimpleLineShadow(), path_effects.Normal()]) # add title and legend font = FontProperties(family='Microsoft YaHei', size=32) ax.set_title('降水量实况图(累计降水: 6月02日—6月06日)', loc='center', fontproperties=font) font = FontProperties(family='Microsoft YaHei', size=16) plt.legend([mpatches.Patch(color=b) for b in colors],[ '50~100 毫米', '100~200 毫米', '200-300 毫米', '300~400 毫米', '400~500 毫米', '500~600 毫米', '>=600毫米'], prop=font) # add city information if draw_station: if station_info == 'cities': cities = pd.read_csv(pkg_resources.resource_filename( 'nmc_met_graphics', "resources/stations/cma_city_station_info.dat"), delimiter=r"\s+") else: cities = pd.read_csv(pkg_resources.resource_filename( 'nmc_met_graphics', "resources/stations/provincial_capital.csv")) font = FontProperties(family='SimHei', size=22, weight='bold') geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) for _, row in cities.iterrows(): text_transform = offset_copy(geodetic_transform, units='dots', x=-5) ax.plot(row['lon'], row['lat'], marker='o', color='white', markersize=8, alpha=0.7, transform=datacrs) ax.text(row['lon'], row['lat'], row['city_name'], clip_on=True, verticalalignment='center', horizontalalignment='right', transform=text_transform, fontproperties=font, color='white', path_effects=[ path_effects.Stroke(linewidth=1, foreground='black'),path_effects.Normal()]) return fig
# Copyright (c) 2018 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """ US Counties =========== Demonstrate how to plot US counties at all three available resolutions. """ import cartopy.crs as ccrs import matplotlib.pyplot as plt from metpy.plots import USCOUNTIES ########################################### proj = ccrs.LambertConformal(central_longitude=-85.0, central_latitude=45.0) fig = plt.figure(figsize=(12, 9)) ax1 = fig.add_subplot(1, 3, 1, projection=proj) ax2 = fig.add_subplot(1, 3, 2, projection=proj) ax3 = fig.add_subplot(1, 3, 3, projection=proj) for scale, axis in zip(['20m', '5m', '500k'], [ax1, ax2, ax3]): axis.set_extent([270.25, 270.9, 38.15, 38.75], ccrs.Geodetic()) axis.add_feature(USCOUNTIES.with_scale(scale), edgecolor='black')
v = ltm_JJA_mean.vwnd_500 - ltm_JJA_mean.vwnd_surf shear = np.sqrt(u**2 - v**2) ltm_JJA_mean['bulk_shear'] = shear # calc seasonal anomaly fields seasonal_anomaly = (daily_select_mean - ltm_JJA_mean) / daily_select_std import cartopy.crs as ccrs from cartopy.mpl.geoaxes import GeoAxes from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import AxesGrid import numpy as np import cartopy.feature as cfeature crs = ccrs.LambertConformal(central_longitude=-100.0, central_latitude=45.0) def plot_background(ax): ax.set_extent([235., 290., 20., 55.]) ax.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidth=0.5) ax.add_feature(cfeature.STATES, linewidth=0.5) ax.add_feature(cfeature.BORDERS, linewidth=0.5) return ax fig = plt.figure(figsize=(10, 5)) fig.set_facecolor('w') ax = fig.add_subplot(1, 1, 1, projection=crs) plot_background(ax) lon = (360. - 88.2434)
monthly_t2m_mask.t2m.mean(dim=('longitude','latitude')).to_dataframe() dataDIR = './test.nc' monthly_t2m_mask.to_netcdf(dataDIR) # load plotting libraries import matplotlib.pyplot as plt import cartopy.crs as ccrs ax = plt.axes(projection=ccrs.Orthographic(-80, 35)) monthly_t2m_mask.t2m.plot.contourf(ax=ax, transform=ccrs.PlateCarree()); ax.set_global(); ax.coastlines(); # choose a good projection for regional maps proj=ccrs.LambertConformal(central_longitude=-100) ax = plt.subplot(111, projection=proj) monthly_t2m_mask.t2m.plot.pcolormesh(ax=ax, transform=ccrs.PlateCarree()) ax.coastlines(); monthly_t2m.plot() shapes = gpd.read_file("D:/Utilisateurs/guillaume/Documents/GitHub/InSIGHT-PHAC/Countries/Countries_Final-polygon.shp") list(shapes.columns.values) for name in shapes['NAME']: print(name) # first features shapes.head(3)
def main(): fig = plt.figure() # to get the effect of having just the states without a map "background" # turn off the background patch and axes frame ax = fig.add_axes([0, 0, 1, 1], projection=ccrs.LambertConformal(), frameon=False) ax.patch.set_visible(False) ax.set_extent([-125, -66.5, 20, 50], ccrs.Geodetic()) shapename = 'admin_1_states_provinces_lakes_shp' states_shp = shpreader.natural_earth(resolution='110m', category='cultural', name=shapename) lons, lats = sample_data() ax.set_title('US States which intersect the track of ' 'Hurricane Katrina (2005)') # turn the lons and lats into a shapely LineString track = sgeom.LineString(zip(lons, lats)) # buffer the linestring by two degrees (note: this is a non-physical # distance) track_buffer = track.buffer(2) def colorize_state(geometry): facecolor = (0.9375, 0.9375, 0.859375) if geometry.intersects(track): facecolor = 'red' elif geometry.intersects(track_buffer): facecolor = '#FF7E00' return {'facecolor': facecolor, 'edgecolor': 'black'} ax.add_geometries(shpreader.Reader(states_shp).geometries(), ccrs.PlateCarree(), styler=colorize_state) ax.add_geometries([track_buffer], ccrs.PlateCarree(), facecolor='#C8A2C8', alpha=0.5) ax.add_geometries([track], ccrs.PlateCarree(), facecolor='none', edgecolor='k') # make two proxy artists to add to a legend direct_hit = mpatches.Rectangle((0, 0), 1, 1, facecolor="red") within_2_deg = mpatches.Rectangle((0, 0), 1, 1, facecolor="#FF7E00") labels = [ 'State directly intersects\nwith track', 'State is within \n2 degrees of track' ] ax.legend([direct_hit, within_2_deg], labels, loc='lower left', bbox_to_anchor=(0.025, -0.1), fancybox=True) plt.show()
header=0, usecols=(1, 2, 3, 4, 5, 6, 7, 17, 18, 19), names=[ 'stid', 'lat', 'lon', 'slp', 'air_temperature', 'cloud_fraction', 'dew_point_temperature', 'weather', 'wind_dir', 'wind_speed' ], na_values=-99999) ########################################### # This sample data has *way* too many stations to plot all of them. The number # of stations plotted will be reduced using `reduce_point_density`. # Set up the map projection proj = ccrs.LambertConformal(central_longitude=-95, central_latitude=35, standard_parallels=[35]) # Use the cartopy map projection to transform station locations to the map and # then refine the number of stations plotted by setting a 300km radius point_locs = proj.transform_points(ccrs.PlateCarree(), data['lon'].values, data['lat'].values) data = data[reduce_point_density(point_locs, 300000.)] ########################################### # Now that we have the data we want, we need to perform some conversions: # # - Get wind components from speed and direction # - Convert cloud fraction values to integer codes [0 - 8] # - Map METAR weather codes to WMO codes for weather symbols
def get_proj_LambertConformal(cls): lccproj = ccrs.LambertConformal(central_longitude=cls.ref_lon, central_latitude=cls.ref_lat, standard_parallels=(cls.truelat1, cls.truelat2), globe=None, cutoff=10) return lccproj
.. _this discussion: https://github.com/pydata/xarray/issues/1397#issuecomment-299190567 """ # noqa from __future__ import division import xarray as xr import cartopy.crs as ccrs import matplotlib.pyplot as plt # Load the data ds = xr.tutorial.load_dataset('air_temperature') air = ds.air.isel(time=[0, 724]) - 273.15 # This is the map projection we want to plot *onto* map_proj = ccrs.LambertConformal(central_longitude=-95, central_latitude=45) p = air.plot(transform=ccrs.PlateCarree(), # the data's projection col='time', col_wrap=1, # multiplot settings aspect=ds.dims['lon'] / ds.dims['lat'], # for a sensible figsize subplot_kws={'projection': map_proj}) # the plot's projection # We have to set the map's options on all four axes for ax in p.axes.flat: ax.coastlines() ax.set_extent([-160, -30, 5, 75]) # Without this aspect attributes the maps will look chaotic and the # "extent" attribute above will be ignored ax.set_aspect('equal', 'box-forced') plt.show()
for s in range(0,1,1): for t in range(0,1,1): ######################## OUVERTURE DU CHAMPS A LIRE ######## rep1='K:/PROJETS/PROJET_CORDEX/CORDEX-NAM44/MOYENNE_ENSEMBLE/ANNEE/Mean_tasmax/' rep2='MOYENNE_ENSEMBLE_'+nb_model[s]+'_RCMs_Pilotes_GCMs_'+scenario[s]+'_Mean_tasmax_'+period[t]+'.nc' filename=rep1+rep2 nc_fid=Dataset(filename,'r') lats = nc_fid.variables['lat'][:] # Extrait et copie les données du fichier NetCDF lons = nc_fid.variables['lon'][:] time = nc_fid.variables['time'][:] Vals = nc_fid.variables['Mean_tasmax'][:].squeeze() ########################################################## fig = plt.figure(figsize=(28,16)) crs=ccrs.LambertConformal() # crs=ccrs.PlateCarree() ax = plt.axes(projection=crs) plot_background(ax) ax.plot(-69.72, 48.15, "bo", markersize=7, transform=ccrs.Geodetic()) ax.text(-69.5, 48.17, "Tadoussac", color='blue', fontsize=20, fontweight='bold', transform=ccrs.Geodetic()) ax.plot(-66.4, 50.21, "bo", markersize=7, color='blue', transform=ccrs.Geodetic()) ax.text(-66.2, 50.22, "Sept-îles", color='blue', fontsize=20, fontweight='bold', transform=ccrs.Geodetic()) mycmap=colbar # mycmap = mpl.cm.get_cmap('jet', 40) mm = ax.contourf(lons,\ lats,\