def get_plot_element(infile): rootgroup = Dataset(infile, 'r') p = wrf.getvar(rootgroup, 'RAINNC') #lats, lons = wrf.latlon_coords(p) cart_proj = wrf.get_cartopy(p) xlim = wrf.cartopy_xlim(p) ylim = wrf.cartopy_ylim(p) rootgroup.close() return cart_proj, xlim, ylim
def prepare_figure(smooth_slp): fig = plt.figure() ax = plt.axes(projection=get_cartopy(smooth_slp)) states = NaturalEarthFeature(category="cultural", scale="10m", facecolor="none", name="admin_1_states_provinces_shp") ax.add_feature(states, linewidth=.5, edgecolor="black") ax.coastlines('10m', linewidth=0.8) ax.set_xlim(cartopy_xlim(smooth_slp)) ax.set_ylim(cartopy_ylim(smooth_slp)) # box containing San Francisco Bay, Monterey Bay ax.set_extent((-123.0, -121.0, 36.2, 38.0)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") return (fig, ax)
def get_plot_element(infile): """get_plot_element .. description: get boxes from geo_em files to draw on plot .. args: infile (str): filename (e.g. geo_em.d01.nc) .. returns: cart_proj xlim ylim """ rootgroup = nc.Dataset(infile, 'r') p = getvar(rootgroup, 'HGT_M') cart_proj = get_cartopy(p) xlim = cartopy_xlim(p) ylim = cartopy_ylim(p) rootgroup.close() return cart_proj, xlim, ylim
def plotdetails(ax, var, theme): ax.add_feature(cfeature.COASTLINE.with_scale('50m')) ax.add_feature(shape_feature) ax.set_extent([100, 130, 15, 45], crs=proj) gl = ax.gridlines(draw_labels=True, linestyle=':', linewidth=0.3, color='k') gl.top_labels = False gl.right_labels = False ax.tick_params(direction='in', length=5) labels = ax.xaxis.get_ticklabels() + ax.yaxis.get_ticklabels() [label.set_fontname('Times New Roman') for label in labels] ax.set_title(theme).set_fontname('Times New Roman') # Set the map bounds ax.set_xlim(cartopy_xlim(var)) ax.set_ylim(cartopy_ylim(var)) ax.spines['bottom'].set_linewidth(0.3) ax.spines['left'].set_linewidth(0.3) ax.spines['top'].set_linewidth(0.3) ax.spines['right'].set_linewidth(0.3)
def plot_domain(nc): """ quick way to plot the WRF simulation domain :param nc: :return: """ # import to work with WRF output import wrf as wrf # wrf-python library https://wrf-python.readthedocs.io/en/latest/ fig = plt.figure(figsize=(12, 6)) # Set the GeoAxes to the projection used by WRF cart_proj = wrf.get_cartopy(wrfin=nc) ax = plt.axes(projection=cart_proj) ax.coastlines('50m', linewidth=0.8) # Set the map bounds ax.set_xlim(wrf.cartopy_xlim(wrfin=nc)) ax.set_ylim(wrf.cartopy_ylim(wrfin=nc)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") return fig, ax
transform=crs.PlateCarree()) plt.clabel(contours, inline=1, fontsize=10, fmt="%i") # Add the wind speed contours levels = [25, 30, 35, 40, 50, 60, 70, 80, 90, 100, 110, 120] wspd_contours = plt.contourf(to_np(lons), to_np(lats), to_np(wspd_500), levels=levels, cmap=get_cmap("rainbow"), transform=crs.PlateCarree()) plt.colorbar(wspd_contours, ax=ax, orientation="horizontal", pad=.05) # Add the 500 hPa wind barbs, only plotting every 125th data point. plt.barbs(to_np(lons[::125, ::125]), to_np(lats[::125, ::125]), to_np(u_500[::125, ::125]), to_np(v_500[::125, ::125]), transform=crs.PlateCarree(), length=6) # Set the map bounds ax.set_xlim(cartopy_xlim(ht_500)) ax.set_ylim(cartopy_ylim(ht_500)) ax.gridlines() plt.title("1000 MB Height (dm), Wind Speed (kt), Barbs (kt)") plt.show()
fig = plt.figure(figsize=(12, 9)) ax = plt.axes(projection=cart_proj) # Download and add the states and coastlines states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_1_states_provinces_shp') ax.add_feature(states, linewidth=0.5) ax.coastlines('50m', linewidth=0.8) # Add the 950 hPa wind barbs, only plotting every 'thin'ed barb. Adjust thin # as needed. Also, no scaling is done for the arrows, so you might need to # mess with the scale argument. thin = 50 plt.quiver(to_np(lons[::thin, ::thin]), to_np(lats[::thin, ::thin]), to_np(u_950[::thin, ::thin]), to_np(v_950[::thin, ::thin]), transform=crs.PlateCarree()) # Set the map bounds ax.set_xlim(cartopy_xlim(u_950)) ax.set_ylim(cartopy_ylim(v_950)) ax.gridlines() plt.title("Arrows") plt.show()
# Download and add the states and coastlines. states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none',name='admin_0_countries') ax.coastlines('50m', linewidth=1.7) ax.add_feature(cfeature.BORDERS,linewidth=1.7) # Make the contour outlines and filled contours for the smoothed Sea Level Pressure. clevs1 = np.arange(980,1040.,2.) c1 = ax.contour(lons, lats, to_np(smooth_slp), levels=clevs1, colors="white",transform=crs.PlateCarree(), linewidths=1.3) # Make the contour outlines and filled contours for the Latent Heat Flux. clevs2 = np.arange(-100,650.,5.) c2 = plt.contourf(to_np(lons), to_np(lats), to_np(lh), clevs2, transform=crs.PlateCarree(),cmap=cm.thermal) plt.colorbar(ax=ax, shrink=.62,orientation='horizontal',aspect=20,fraction=0.046, pad=0.04) # Plot the wind barbs for the U10 and V10 from UVMET10. c3 = plt.barbs(to_np(lons[::75,::75]), to_np(lats[::75,::75]), to_np(u10[::75, ::75]), to_np(v10[::75, ::75]),color='black',transform=crs.PlateCarree(), length=6) # Set the map limits. Not really necessary, but used for demonstration. ax.set_xlim(cartopy_xlim(smooth_slp)) ax.set_ylim(cartopy_ylim(smooth_slp)) # Add the gridlines. g1 = ax.gridlines(color="gray", linestyle="--",draw_labels=True,linewidth=0.2) g1.xlabels_top = False g1.ylabels_right= False # Save. plt.title("COA_WRS (ROMS+WRF+SWAN)") plt.savefig('/home/uesleisutil/Documentos/IntegraI/slp_200.png',dpi=200,bbox_inches='tight')
def main(folder, wrffolder, append, sourceid, plotmap, plotcurves, plotcontour, plotcontourf, plotbarbs, resol): #z_unit = 'km' z_unit = 'dm' z_unitStr = 'dam' #u_unit = 'm s-1' u_unit = 'kt' w_unit = u_unit w_unitStr = 'm/s' w_unitStr = 'kt' p_unit = 'hPa' df_obs = pd.read_csv(folder + sourceid + '_json.txt', delimiter='\t') df_obs['time'] = pd.to_datetime(df_obs['CurrentTime'], unit='s') df_obs['air_temperature'] = df_obs['Temperature'] df_obs['pressure'] = df_obs['Barometric Pressure'] df_obs['wind_speed'] = df_obs[ 'Wind Speed'] * 1.852 / 3.6 # Convert from knots to m/s if z_unit == "km": feetScale = 0.3048 / 1000 elif z_unit == "m": feetScale = 0.3048 elif z_unit == "dm": feetScale = 0.3048 / 10 df_obs['z'] = df_obs['Alt'].to_numpy( ) * feetScale # Convert from feet to decameters (dam) # Get data from WRF file i_domain = 10 isOutside = True while isOutside: if i_domain < 0: print('Parts of the flightpath for ' + str(sourceid) + ' is not inside the solution domain') break i_domain -= 1 try: ncfile = Dataset(wrffolder + '/wrfout_d0' + str(i_domain) + '.nc') except: continue fields = ['T', 'wind_speed', 'wind_from_direction'] lat_e = df_obs['Latitude'].to_numpy() lon_e = df_obs['Longitude'].to_numpy() z_e = df_obs['z'].to_numpy() time_e = df_obs['time'].to_numpy() dummy = pd.DataFrame( {'time': wrf.getvar(ncfile, 'Times', wrf.ALL_TIMES)}) time = dummy['time'].to_numpy() indices = (time[0] <= time_e) & (time_e <= time[-1]) if not np.any(indices): raise OutOfRange('The mode-S data is out of range') lat_e = lat_e[indices] lon_e = lon_e[indices] z_e = z_e[indices] time_e = time_e[indices] x = np.zeros((lat_e.shape[0], 4)) xy = wrf.ll_to_xy(ncfile, lat_e, lon_e, as_int=False, meta=False) if ncfile.MAP_PROJ_CHAR == 'Cylindrical Equidistant' and i_domain == 1: xy[0] += 360 / 0.25 x[:, 0] = xy[0] x[:, 1] = xy[1] e_we = ncfile.dimensions['west_east'].size e_sn = ncfile.dimensions['south_north'].size if np.any(xy < 0) or np.any(xy[0] > e_we - 1) or np.any( xy[1] > e_sn - 1): print('Flight path is outside domain d0' + str(i_domain)) continue else: print('Extracting WRF-data from domain d0' + str(i_domain)) if plotcurves: xy2 = np.zeros(xy.T.shape) xy2[:, :] = xy[:, :].T #zgrid = wrf.interp2dxy(wrf.getvar(ncfile,'z',units=z_unit),xy2,meta=False) zgrid = wrf.interp2dxy(wrf.g_geoht.get_height(ncfile, units=z_unit), xy2, meta=False) # Get geopotential height for i in range(0, len(z_e)): f_time = interp1d(zgrid[:, i], range(0, zgrid.shape[0]), kind='linear') x[i, 2] = f_time(z_e[i]) f_time = interp1d(time.astype('int'), range(0, len(time)), kind='linear') x[:, 3] = f_time(time_e.astype('int')) df_wrf = pd.DataFrame() df_wrf['time'] = time_e df_wrf['air_temperature'] = linInterp( wrf.getvar(ncfile, 'tc', wrf.ALL_TIMES, meta=False), x) df_wrf['pressure'] = linInterp( wrf.g_pressure.get_pressure(ncfile, wrf.ALL_TIMES, meta=False, units=p_unit), x) df_wrf['wind_speed'] = linInterp( wrf.g_wind.get_destag_wspd(ncfile, wrf.ALL_TIMES, meta=False), x) df_wrf['wind_from_direction'] = linInterp( wrf.g_wind.get_destag_wdir(ncfile, wrf.ALL_TIMES, meta=False), x) if df_wrf.isnull().values.any(): print('Some points are outside the domain ' + str(i_domain)) continue else: isOutside = False else: isOutside = False if plotcurves: # Plot data sharex = True #fields = np.array([['air_temperature','wind_speed','pressure'], # ['windDirX', 'windDirY','z']]) #ylabels = np.array([['Temperature [°C]', 'Wind speed [m/s]', 'Pressure ['+p_unit+']'], # ['Wind direction - X','Wind direction - Y', 'Altitude ['+z_unitStr+']']]) fields = np.array([['air_temperature', 'wind_speed'], ['windDirX', 'windDirY']]) ylabels = np.array([['Temperature [°C]', 'Wind speed [m/s]'], ['Wind direction - X', 'Wind direction - Y']]) df_obs['windDirX'] = np.cos(np.radians(df_obs['Wind Direction'])) df_obs['windDirY'] = np.sin(np.radians(df_obs['Wind Direction'])) df_wrf['windDirX'] = np.cos(np.radians(df_wrf['wind_from_direction'])) df_wrf['windDirY'] = np.sin(np.radians(df_wrf['wind_from_direction'])) df_wrf['z'] = z_e fig, axs = plt.subplots(fields.shape[0], fields.shape[1], sharex=sharex) mng = plt.get_current_fig_manager() #mng.resize(*mng.window.maxsize()) #mng.frame.Maximize(True) mng.window.showMaximized() title = 'Comparison between Mode-S data and WRF simulations for flight ' + sourceid if plotcurves: title += '. WRF data from domain d0' + str( i_domain) + ' with grid resolution {:.1f} km'.format( max(ncfile.DX, ncfile.DY) / 1000) fig.suptitle(title) for i in range(0, fields.shape[0]): for j in range(0, fields.shape[1]): axs[i, j].plot(df_wrf.time.to_numpy(), df_wrf[fields[i, j]].to_numpy(), 'b', label='WRF forecast') axs[i, j].plot(df_obs.time.to_numpy(), df_obs[fields[i, j]].to_numpy(), 'r', label='Observation data') axs[i, j].legend() axs[i, j].set(xlabel='Time', ylabel=ylabels[i, j]) axs[i, j].set_xlim(time_e[0], time_e[-1]) axs[1, 0].set_ylim(-1, 1) axs[1, 1].set_ylim(-1, 1) plt.show() fig.savefig(folder + '/' + sourceid + '_curves.png', dpi=400) if plotmap: # Extract the pressure, geopotential height, and wind variables ncfile = Dataset(wrffolder + '/wrfout_d01.nc') p = wrf.g_pressure.get_pressure(ncfile, units=p_unit) #p = getvar(ncfile, "pressure",units=p_unit) z = getvar(ncfile, "z", units=z_unit) ua = getvar(ncfile, "ua", units=u_unit) va = getvar(ncfile, "va", units=u_unit) wspd = getvar(ncfile, "wspd_wdir", units=w_unit)[0, :] # Interpolate geopotential height, u, and v winds to 500 hPa ht_500 = interplevel(z, p, 500) u_500 = interplevel(ua, p, 500) v_500 = interplevel(va, p, 500) wspd_500 = interplevel(wspd, p, 500) # Get the lat/lon coordinates lats, lons = latlon_coords(ht_500) # Get the map projection information cart_proj = get_cartopy(ht_500) # Create the figure fig = plt.figure(figsize=(12, 9)) ax = plt.axes(projection=cart_proj) # Download and add the states and coastlines name = 'admin_0_boundary_lines_land' #name = 'admin_1_states_provinces_lines' #name = "admin_1_states_provinces_shp" bodr = cfeature.NaturalEarthFeature(category='cultural', name=name, scale=resol, facecolor='none') land = cfeature.NaturalEarthFeature('physical', 'land', \ scale=resol, edgecolor='k', facecolor=cfeature.COLORS['land']) ocean = cfeature.NaturalEarthFeature('physical', 'ocean', \ scale=resol, edgecolor='none', facecolor=cfeature.COLORS['water']) lakes = cfeature.NaturalEarthFeature('physical', 'lakes', \ scale=resol, edgecolor='b', facecolor=cfeature.COLORS['water']) rivers = cfeature.NaturalEarthFeature('physical', 'rivers_lake_centerlines', \ scale=resol, edgecolor='b', facecolor='none') ax.add_feature(land, facecolor='beige', zorder=0) ax.add_feature(ocean, linewidth=0.2, zorder=0) ax.add_feature(lakes, linewidth=0.2, zorder=1) ax.add_feature(bodr, edgecolor='k', zorder=1, linewidth=0.5) #ax.add_feature(rivers, linewidth=0.5,zorder=1) if plotcontour: # Add the 500 hPa geopotential height contour levels = np.arange(100., 2000., 10.) contours = plt.contour(to_np(lons), to_np(lats), to_np(ht_500), levels=levels, colors="forestgreen", linewidths=1, transform=ccrs.PlateCarree(), zorder=3) plt.clabel(contours, inline=1, fontsize=10, fmt="%i") if plotcontourf: try: with open(home + '/kode/colormaps/SINTEF1.json') as f: json_data = json.load(f) SINTEF1 = np.reshape(json_data[0]['RGBPoints'], (-1, 4)) cmap = ListedColormap(fill_colormap(SINTEF1)) except: print( 'SINTEF1 colormap not found (can be found at https://github.com/Zetison/colormaps.git)' ) cmap = get_cmap("rainbow") # Add the wind speed contours levels = np.linspace(20, 120, 101) wspd_contours = plt.contourf(to_np(lons), to_np(lats), to_np(wspd_500), levels=levels, cmap=cmap, alpha=0.7, antialiased=True, transform=ccrs.PlateCarree(), zorder=2) cbar_wspd = plt.colorbar(wspd_contours, ax=ax, orientation="horizontal", pad=.05, shrink=0.5, aspect=30, ticks=range(10, 110, 10)) cbar_wspd.ax.set_xlabel('Wind speeds [' + w_unitStr + '] at 500 mbar height') # Add the 500 hPa wind barbs, only plotting every nthb data point. nthb = 10 if plotbarbs: plt.barbs(to_np(lons[::nthb, ::nthb]), to_np(lats[::nthb, ::nthb]), to_np(u_500[::nthb, ::nthb]), to_np(v_500[::nthb, ::nthb]), transform=ccrs.PlateCarree(), length=6, zorder=3) track = sgeom.LineString( zip(df_obs['Longitude'].to_numpy(), df_obs['Latitude'].to_numpy())) fullFlightPath = ax.add_geometries([track], ccrs.PlateCarree(), facecolor='none', zorder=4, edgecolor='red', linewidth=2, label='Flight path') track = sgeom.LineString(zip(lon_e, lat_e)) flightPath = ax.add_geometries([track], ccrs.PlateCarree(), facecolor='none', zorder=4, linestyle=':', edgecolor='green', linewidth=2, label='Extracted flight path') #plt.legend(handles=[fullFlightPath]) #blue_line = mlines.Line2D([], [], color='red',linestyle='--', label='Flight path',linewidth=2) #plt.legend(handles=[blue_line]) # Set the map bounds ax.set_xlim(cartopy_xlim(ht_500)) ax.set_ylim(cartopy_ylim(ht_500)) #ax.gridlines(draw_labels=True) ax.gridlines() startdate = pd.to_datetime(str( time_e[0])).strftime("%Y-%m-%d %H:%M:%S") plt.title('Flight ' + sourceid + ', with visualization of WRF simulation (' + startdate + ') at 500 mbar Height (' + z_unitStr + '), Wind Speed (' + w_unitStr + '), Barbs (' + w_unitStr + ')') # Plot domain boundaries infile_d01 = wrffolder + '/wrfout_d01.nc' cart_proj, xlim_d01, ylim_d01 = get_plot_element(infile_d01) infile_d02 = wrffolder + '/wrfout_d02.nc' _, xlim_d02, ylim_d02 = get_plot_element(infile_d02) infile_d03 = wrffolder + '/wrfout_d03.nc' _, xlim_d03, ylim_d03 = get_plot_element(infile_d03) infile_d04 = wrffolder + '/wrfout_d04.nc' _, xlim_d04, ylim_d04 = get_plot_element(infile_d04) # d01 ax.set_xlim([ xlim_d01[0] - (xlim_d01[1] - xlim_d01[0]) / 15, xlim_d01[1] + (xlim_d01[1] - xlim_d01[0]) / 15 ]) ax.set_ylim([ ylim_d01[0] - (ylim_d01[1] - ylim_d01[0]) / 15, ylim_d01[1] + (ylim_d01[1] - ylim_d01[0]) / 15 ]) # d01 box textSize = 10 colors = ['blue', 'orange', 'brown', 'deepskyblue'] linewidth = 1 txtscale = 0.003 ax.add_patch( mpl.patches.Rectangle((xlim_d01[0], ylim_d01[0]), xlim_d01[1] - xlim_d01[0], ylim_d01[1] - ylim_d01[0], fill=None, lw=linewidth, edgecolor=colors[0], zorder=10)) ax.text(xlim_d01[0], ylim_d01[0] + (ylim_d01[1] - ylim_d01[0]) * (1 + txtscale), 'd01', size=textSize, color=colors[0], zorder=10) # d02 box ax.add_patch( mpl.patches.Rectangle((xlim_d02[0], ylim_d02[0]), xlim_d02[1] - xlim_d02[0], ylim_d02[1] - ylim_d02[0], fill=None, lw=linewidth, edgecolor=colors[1], zorder=10)) ax.text(xlim_d02[0], ylim_d02[0] + (ylim_d02[1] - ylim_d02[0]) * (1 + txtscale * 3), 'd02', size=textSize, color=colors[1], zorder=10) # d03 box ax.add_patch( mpl.patches.Rectangle((xlim_d03[0], ylim_d03[0]), xlim_d03[1] - xlim_d03[0], ylim_d03[1] - ylim_d03[0], fill=None, lw=linewidth, edgecolor=colors[2], zorder=10)) ax.text(xlim_d03[0], ylim_d03[0] + (ylim_d03[1] - ylim_d03[0]) * (1 + txtscale * 3**2), 'd03', size=textSize, color=colors[2], zorder=10) # d04 box ax.add_patch( mpl.patches.Rectangle((xlim_d04[0], ylim_d04[0]), xlim_d04[1] - xlim_d04[0], ylim_d04[1] - ylim_d04[0], fill=None, lw=linewidth, edgecolor=colors[3], zorder=10)) ax.text(xlim_d04[0], ylim_d04[0] + (ylim_d04[1] - ylim_d04[0]) * (1 + txtscale * 3**3), 'd04', size=textSize, color=colors[3], zorder=10) plt.show() fig.savefig(folder + '/' + sourceid + '_map.png', dpi=400)
# Download and add the states and coastlines states = NaturalEarthFeature(category="cultural", scale="50m",\ facecolor="none", name="admin_1_states_provinces_shp") ax.add_feature(states, linewidth=.5, edgecolor="black") ax.coastlines('50m', linewidth=0.8) #plt.contour(to_np(lons), to_np(lats), to_np(var2D), colors="black",\ # transform=crs.PlateCarree()) plt.contourf(to_np(lons), to_np(lats), to_np(var2D), \ transform=crs.PlateCarree(),cmap=get_cmap("jet")) # Add a color bar plt.colorbar(ax=ax, shrink=.98) # Set the map bounds ax.set_xlim(cartopy_xlim(var2D)) ax.set_ylim(cartopy_ylim(var2D)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") plt.title(var2D.attrs['description'] + ' (' + var2D.attrs['units'] + '), 2015-05-05:00:00:00') plt.show() fig.savefig('./Figures/' + var2D_str[i_var] + '.png', dpi=500, transparent=True, bbox_inches='tight')
ax.coastlines('50m', linewidth=0.8) ax.add_feature( cfe.NaturalEarthFeature('physical', 'antarctic_ice_shelves_lines', '50m', linewidth=1.0, edgecolor='k', facecolor='none')) # Plot contours plt.contourf(wrf.to_np(lons), wrf.to_np(lats), wrf.to_np(t2), 10, transform=crs.PlateCarree(), cmap=mpl_cm.Reds) # Add a color bar cbar = plt.colorbar(ax=ax, shrink=.62) cbar.set_label(t2.units) # Set the map limits. Not really necessary, but used for demonstration. ax.set_xlim(wrf.cartopy_xlim(t2)) ax.set_ylim(wrf.cartopy_ylim(t2)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") plt.title(t2.description + '\n' + str(t2.Time.values)) plt.show()
# Make filled contours of dewpoint plt.contourf(to_np(lons), to_np(lats), to_np(td2), levels=td2_levels, cmap=td2_cmap, norm=td2_norm, extend="both", transform=crs.PlateCarree()) # Plot the wind barbs, but only plot ~10 barbs in each direction. thin = [int(x / 10.) for x in lons.shape] plt.barbs(to_np(lons[::thin[0], ::thin[1]]), to_np(lats[::thin[0], ::thin[1]]), to_np(u_sfc[::thin[0], ::thin[1]]), to_np(v_sfc[::thin[0], ::thin[1]]), transform=crs.PlateCarree()) # Add contour labels for pressure plt.clabel(slp_contours, fmt="%i") # Add a color bar. The shrink often needs to be set # by trial and error. plt.colorbar(ax=geo_axes, shrink=1.0, extend="both") # Set the map bounds plt.xlim(cartopy_xlim(slp)) plt.ylim(cartopy_ylim(slp)) plt.title('dewpoint (colour), slp (contours), surface windspeed (barbs)') plt.savefig(dom + 'overview.png')
to_np(smooth_var_plot), 10, colors="black", transform=ccrs.PlateCarree()) ax.contourf(to_np(lons), to_np(lats), to_np(smooth_var_plot), 10, transform=ccrs.PlateCarree(), cmap=get_cmap("jet")) # Add a color bar # Set the map limits. Not really necessary, but used for demonstration. ax.set_xlim(cartopy_xlim(smooth_var_plot)) ax.set_ylim(cartopy_ylim(smooth_var_plot)) # cartopy_xlim(smooth_var_plot) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") ax.set_title("WRF results") ax.figure # plt.show() # try some more plots ax = plt.axes(projection=cart_proj) fig_res = ax.figure fig_res = res_plot[1:17].plot.imshow(col='Time', col_wrap=4, robust=True) dir(fig_res)
# Make the contour outlines and filled contours for the smoothed sea level pressure. plt.contour(to_np(lons), to_np(lats), to_np(T2[160, :, :]), 10, colors="black", transform=crs.PlateCarree()) plt.contourf(to_np(lons), to_np(lats), to_np(T2[160, :, :]), 10, transform=crs.PlateCarree(), cmap=get_cmap("jet")) # Add a color bar plt.colorbar(ax=ax, shrink=.92) # Set the map limits. Not really necessary, but used for demonstration. ax.set_xlim(cartopy_xlim(T2)) ax.set_ylim(cartopy_ylim(T2)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") plt.title("TEMP at 2M (K)") plt.savefig('t2.png') # plt.show()
ax.quiverkey(q, 0.9, 1.01, 15, r'$10 \frac{m}{s}$', coordinates='axes', fontproperties={ 'size': 30, 'weight': 'bold' }) # ax.scatter(-121.6219, 39.7596, s =400, marker = 'X', label = 'Paradise, California', transform = crs.PlateCarree(), color = '#ff0000',edgecolors = 'black') # legend = ax.legend(fontsize = 30, loc = 3) # legend.get_frame().set_facecolor('#cccfd1') # Set the map bounds ax.set_xlim(cartopy_xlim(cf_var[0])) ax.set_ylim(cartopy_ylim(cf_var[0])) # ax.gridlines() # Add a title # plt.title('WRF %0.1f m'%(ds.DX), loc='left', fontweight='bold', fontsize = 35) # plt.title('Color Fill: %s \n Barbs: %s'%(cf_var.description.title(), u.description) , loc='center', fontweight='bold', fontsize = 25) # plt.title('%s'%(cf_var.description.title()) , loc='center', fontweight='bold', fontsize = 25) plt.title('Valid Time: %s PST\nRadar Scan: %s PST' % (ts, pd.to_datetime(radar.time['units'][14:-1], format='%Y-%m-%dT%H:%M:%S').tz_localize('UTC'). tz_convert('US/Pacific').strftime("%Y-%m-%d %H:%M:%S")), loc='left', fontweight='bold', fontsize=25) plt.savefig('/export/home/mbrewer/wrf_out/%s.png' %
# Download and add the states and coastlines states = NaturalEarthFeature(category="cultural", scale="50m",\ facecolor="none", name="admin_1_states_provinces_shp") ax.add_feature(states, linewidth=.5, edgecolor="black") ax.coastlines('50m', linewidth=0.8) #plt.contour(to_np(lons), to_np(lats), to_np(var3D_500), colors="black",\ # transform=crs.PlateCarree()) plt.contourf(to_np(lons), to_np(lats), to_np(var3D_500), \ transform=crs.PlateCarree(),cmap=get_cmap("jet")) # Add a color bar plt.colorbar(ax=ax, shrink=.98) # Set the map bounds ax.set_xlim(cartopy_xlim(var3D_500)) ax.set_ylim(cartopy_ylim(var3D_500)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") plt.title(var3D.attrs['description'] + ' (' + var3D.attrs['units'] + '),500hPa,2015-05-05:00:00:00') plt.show() fig.savefig('./Figures/' + var3D_str[i_var] + '.500hPa.png', dpi=500, transparent=True, bbox_inches='tight')
# plotando isoterma de 10 graus para membro 01 #print( 'Plotando isoterma do membro 1 ...' ) ax = plt.axes( projection=projecaoWRF ) if nt==1: ax.contour( wrf.to_np(lons), wrf.to_np(lats), wrf.to_np( t2m[ 0, :, :]-273.15 ), [5,10,20], colors=['black','blue','red'], transform=ccrs.PlateCarree() ) else: ax.contour( wrf.to_np(lons), wrf.to_np(lats), wrf.to_np( t2m[ 0, tPrev, :, :]-273.15 ), [5,10,20], colors=['black','blue','red'], transform=ccrs.PlateCarree() ) ax.coastlines( '50m', linewidth=0.8 ) ax.set_title('T [C] - PCWRF - CPPMet/FAMET/UFPel \n Início: '+strIniPrev+' Validade: '+strTempoPrev[ tPrev ] ) ax.set_xlim( wrf.cartopy_xlim( t2m ) ) ax.set_ylim( wrf.cartopy_ylim( t2m )) ax.gridlines( color='black', linestyle='dotted') ax.add_feature( estados, linewidth=.5, edgecolor='black' ) for membro in range( 1, nmembros ): #print( 'Plotando isoterma do membro '+str(membro+1)+'...' ) if nt==1: ax.contour( wrf.to_np(lons), wrf.to_np(lats), wrf.to_np( t2m[ membro, :, :]-273.15 ), [5,10,20], colors=['black','blue','red'], transform=ccrs.PlateCarree() ) else: ax.contour( wrf.to_np(lons), wrf.to_np(lats), wrf.to_np( t2m[ membro, tPrev, :, :]-273.15 ), [5,10,20], colors=['black','blue','red'], transform=ccrs.PlateCarree() ) plt.savefig( 'spaghetti_t2m_'+strIniPrev+'_'+strTempoPrev[ tPrev ]+'.png' )
lon = lons[:, :].squeeze() u_wind = u10[0, :, :].squeeze() v_wind = v10[0, :, :].squeeze() # Add the 500 hPa wind barbs, only plotting every 125th data point. q = ax.quiver(to_np(lon[::3]), to_np(lat[::3]), to_np(u_wind[::3]), to_np(v_wind[::3]), color='blue', scale=500, width=0.001, headwidth=5, headlength=1., transform=crs.PlateCarree()) ax.quiverkey(q, X=0.3, Y=1.1, U=10, label='Quiver key, length = 10', labelpos='E') # Set the map bounds ax.set_xlim(cartopy_xlim(u10)) ax.set_ylim(cartopy_ylim(u10)) ax.gridlines() plt.title("500 MB Height (dm), Wind Speed (kt), Barbs (kt)") plt.show()
to_np(lats), to_np(HGT), cmap='terrain', vmin=1, vmax=to_np(HGT).max(), alpha=0.8, transform=crs.PlateCarree(), zorder=1) ax.add_feature(OCEAN, edgecolor='k', facecolor=COLORS['water'], zorder=2) ax.add_feature(LAKES, edgecolor='k', zorder=2) ax.add_feature(COASTLINE, edgecolor='k', linewidth=5) ax.add_feature(BORDERS, edgecolor='k', linewidth=3, linestyle='--') ax.add_feature(RIVERS, edgecolor='b', linewidth=3, zorder=2) # Set the map bounds ax.set_xlim(cartopy_xlim(HGT)) ax.set_ylim(cartopy_ylim(HGT)) ax.set_title('topography for d0' + str(i + 1), fontweight='bold', fontsize=12) # Add the gridlines fig.suptitle("Topography of 3 domains", fontsize=32, fontweight='bold') fig.canvas.draw() cax = plt.subplot(gs[4, 1:5]) cbar = fig.colorbar(mappable=p, cax=cax, shrink=0.95, orientation='horizontal', extend='both') cbar.ax.set_xlabel('GMTED2010 30-arc-second topography height (m)', fontsize=16, labelpad=10)
colors='black', levels=np.arange(950, 1040, 3), linewidths=2., transform=ccrs.PlateCarree()) plt.clabel(campo1, fmt='%1.0f') campo2 = ax.contourf(wrf.to_np(lons), wrf.to_np(lats), wrf.to_np(pnmm_dp[tPrev, :, :]), levels=limites, extend='neither', cmap=mapa_cores, norm=mapa_cores_norma, transform=ccrs.PlateCarree()) plt.colorbar(campo2, ticks=limites, norm=mapa_cores_norma, boundaries=[0] + limites + [15]) ax.coastlines('50m', linewidth=0.8) ax.set_title( 'Média (contorno) e DP (colorido) - PNMM [hPa] \n PCWRF/CPPMet/FAMET/UFPel \n Início: ' + strIniPrev + ' Validade: ' + strTempoPrev[tPrev]) ax.set_xlim(wrf.cartopy_xlim(pnmm)) ax.set_ylim(wrf.cartopy_ylim(pnmm)) ax.gridlines(color='black', linestyle='dotted') ax.add_feature(estados, linewidth=.5, edgecolor='black') plt.savefig('pnmm_media_dp_' + strIniPrev + '_' + strTempoPrev[tPrev] + '.png') plt.close()
# Set the GeoAxes to the projection used by WRF ax = plt.axes(projection=cart_proj) # Download and add the states and coastlines states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_1_states_provinces_shp') ax.add_feature(states, linewidth=.5) ax.coastlines('50m', linewidth=0.8) # Make the contour outlines and filled contours for the smoothed sea level pressure. plt.contour(to_np(lons), to_np(lats), to_np(LH[160,:,:]), 10, colors="black", transform=crs.PlateCarree()) plt.contourf(to_np(lons), to_np(lats), to_np(LH[160,:,:]), 10, transform=crs.PlateCarree(), cmap=get_cmap("jet")) # Add a color bar plt.colorbar(ax=ax, shrink=.92) # Set the map limits. Not really necessary, but used for demonstration. ax.set_xlim(cartopy_xlim(LH)) ax.set_ylim(cartopy_ylim(LH)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") plt.title("LATENT HEAT FLUX AT THE SURFACE (W m-2)") plt.savefig('LH.png') # plt.show()
lat_formatter = LatitudeFormatter(number_format='.1f') ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) ax.tick_params(axis='both', which='major', labelsize=SMFONT) #for tick in ax.xaxis.get_major_ticks(): # tick.label.set_fontsize(SMFONT) # 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) #mct_xticks(ax, xticks) #mct_yticks(ax, yticks) # Set the map bounds ax.set_xlim(cartopy_xlim(lsmask)) ax.set_ylim(cartopy_ylim(lsmask)) ax.plot(df_hko_obv['lon']/10., df_hko_obv['lat']/10., color='black', marker='o', linewidth=2, markersize=5, transform=ccrs.Geodetic(), label='HKO bestTrack') ax.plot(df_cma_obv['lon']/10., df_cma_obv['lat']/10., color='dimgray', marker='*', linewidth=2, linestyle='dashed', markersize=8, transform=ccrs.Geodetic(), label='CMA bestTrack') dateparse = lambda x: datetime.datetime.strptime(x, '%Y%m%d%H%M%S') for (line_type,casename) in zip(line_libs,cases): sen_path='/home/metctm1/array/data/1911-COAWST/'+casename+'/trck.'+casename+'.d02' df_sen=pd.read_csv(sen_path,parse_dates=True,index_col='timestamp', sep='\s+', date_parser=dateparse) df_sen_period=df_sen df_sen_period.replace(0, np.nan, inplace=True) # replace 0 by nan df_sen_period=df_sen_period.dropna()
# Define gridline locations and draw the lines using cartopy's built-in gridliner: # xticks = np.arange(80,130,10) # yticks = np.arange(15,55,5) xticks = np.arange(100, 135, 5).tolist() yticks = np.arange(5, 40, 5).tolist() #ax.gridlines(xlocs=xticks, ylocs=yticks,zorder=1,linestyle='--',lw=0.5,color='gray') # 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) mct_xticks(ax, xticks) mct_yticks(ax, yticks) # Set the map bounds ax.set_xlim(cartopy_xlim(slp)) ax.set_ylim(cartopy_ylim(slp)) ax.scatter(lon_arr[:, ii], lat_arr[:, ii], marker='.', color='blue', s=5, zorder=10, alpha=0.3, transform=ccrs.Geodetic(), label='Mass Points') print('%04d finished.' % ii) plt.title('Universial Mass Points and SLP @%s' % slp[ii, :, :].Time.dt.strftime('%Y-%m-%d %H:%M:%S').values, fontsize=MIDFONT)
ax.add_feature(states, linewidth=.5) ax.coastlines('50m', linewidth=0.8) # Make the contour outlines and filled contours for the smoothed sea level pressure. ax.contour(to_np(lons), to_np(lats), to_np(smooth_slp), 10, colors="black", transform=crs.PlateCarree()) ax.contourf(to_np(lons), to_np(lats), to_np(smooth_slp), 10, transform=crs.PlateCarree(), cmap=get_cmap("jet")) # Add a color bar ax.add_colorbar(ax=ax, shrink=.62) # Set the map limits. Not really necessary, but used for demonstration. ax.set_xlim(cartopy_xlim(smooth_slp)) ax.set_ylim(cartopy_ylim(smooth_slp)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") ax.set_title("Sea Level Pressure (hPa)") ax.figure # plt.show()
2) + '/' # zfill preenche esquerda com zeros, 2 dígitos if membro == 0: #print( '\t acessando membro 1' ) arq = nc.Dataset(dirArq + arqPrev) chuvac = wrf.getvar(arq, 'RAINC', wrf.ALL_TIMES) chuvanc = wrf.getvar(arq, 'RAINNC', wrf.ALL_TIMES) varMet = chuvac + chuvanc varMet = varMet.rename('chuva') if deltaDia == 0: projecaoWRF = wrf.get_cartopy( wrfin=arq) # projeção dos dados -> para plotagem dominioLimsX = wrf.cartopy_xlim(wrfin=arq) dominioLimsY = wrf.cartopy_ylim(wrfin=arq) arq.close() else: #print( '\t acessando membro '+str( membro+1 ) ) arq = nc.Dataset(dirArq + arqPrev) chuvac = wrf.getvar(arq, 'RAINC', wrf.ALL_TIMES) chuvanc = wrf.getvar(arq, 'RAINNC', wrf.ALL_TIMES) d2 = chuvac + chuvanc del chuvac, chuvanc arq.close()
] cmap_name = 'dbz' n_bins = np.arange(-5, 80, 5) cmap = LinearSegmentedColormap.from_list(cmap_name, colors, N=16) cm.register_cmap(name=cmap_name, cmap=cmap) #define levels levels = np.arange(-5, 70, 5) #plot the filled contours for the dbz plt.contourf(to_np(lons), to_np(lats), to_np(dbz_ht), levels, transform=crs.PlateCarree(), cmap=get_cmap('dbz')) #add a color bar plt.colorbar(ax=ax, shrink=.98, label='dbz') #set the map bounds ax.set_xlim(cartopy_xlim(dbz_ht)) ax.set_ylim(cartopy_ylim(dbz_ht)) #add title plt.title('Radar Reflectivity From Similation' + '\n' + BJT) #save picture plt.savefig('./dbz.png')
ax = plt.axes(projection=cart_proj) # Download and add the states and coastlines states = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_1_states_provinces_shp') ax.add_feature(states, linewidth=.5) ax.coastlines('50m', linewidth=0.8) # Make the contour outlines and filled contours for the smoothed sea level # pressure. plt.contour(to_np(lons), to_np(lats), to_np(ctt), 10, colors="black", transform=crs.PlateCarree()) plt.contourf(to_np(lons), to_np(lats), to_np(ctt), 10, transform=crs.PlateCarree(), cmap=get_cmap("jet")) # Add a color bar plt.colorbar(ax=ax, shrink=.62) # Set the map limits. Not really necessary, but used for demonstration. ax.set_xlim(cartopy_xlim(ctt)) ax.set_ylim(cartopy_ylim(ctt)) # Add the gridlines ax.gridlines(color="black", linestyle="dotted") plt.title("Cloud Top Temperature") plt.show()
ax = plt.axes(projection=cart_proj) # Aniadiendo los sombreados #levels = [25, 30, 35, 40, 50, 60, 70, 80, 90, 100, 110, 120] levels = np.arange(-1.5, 1.5, 0.25) wspd_contours = plt.contourf(to_np(lons), to_np(lats), to_np(w), levels=levels, cmap="bwr", transform=crs.PlateCarree()) plt.colorbar(wspd_contours, ax=ax) ht_fill = plt.contourf(to_np(lons), to_np(lats), to_np(ter), np.arange(3000, 9000, 100),colors=['saddlebrown'], transform=crs.PlateCarree()) # Set the map bounds ax.set_xlim(cartopy_xlim(p)) ax.set_ylim(cartopy_ylim(p)) # Agregamos la línea de costas ax.coastlines(resolution='10m',linewidth=0.6) # Agregamos los límites de los países ax.add_feature(countries,linewidth=0.9) # Agregamos los límites de las provincias ax.add_feature(states_provinces,linewidth=0.9) # Le damos formato a las etiquetas de los ticks ax.set_yticks(np.arange(-29, -19, 2), crs=crs.PlateCarree()) ax.set_xticks(np.arange(-70, -59, 2), crs=crs.PlateCarree()) lon_formatter = LongitudeFormatter(zero_direction_label=True) lat_formatter = LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) # para escribir el titulo
to_np(ter), levels=levels, cmap=cmap, transform=crs.PlateCarree(), alpha=0.8, extend='both') #plt.colorbar(wspd_contours, ax=ax, orientation="vertical", pad=.05) # Add the 60 hPa wind barbs, only plotting every 40th data point. q = plt.quiver(to_np(lons[::2, ::2]), to_np(lats[::2, ::2]), to_np(u_60[::2, ::2]), to_np(v_60[::2, ::2]), width=0.0015, transform=crs.PlateCarree()) ax.quiverkey(q, 0.1, -0.045, 5, '5 ms-1', labelpos='W') # Set the map bounds ax.set_xlim(cartopy_xlim(wspd_60)) ax.set_ylim(cartopy_ylim(wspd_60)) xtime = getvar(ncfiles, "times", timeidx=i, meta=False) xtime = datetime.datetime.fromtimestamp(xtime.astype('O') / 1e9) fig.text(.5, 0.48, xtime, ha='center') plt.subplots_adjust(bottom=0.5) plt.savefig(str(xtime.month) + str(xtime.day) + str(xtime.hour) + ".png", bbox_inches='tight', dpi=200)
fmt="%i") # los labels de los contornos # Aniadiendo los sombreados #levels = [25, 30, 35, 40, 50, 60, 70, 80, 90, 100, 110, 120] levels = np.arange(25, 120, 5) wspd_contours = plt.contourf(to_np(lons), to_np(lats), to_np(wspd), levels=levels, cmap="rainbow", transform=crs.PlateCarree()) plt.colorbar(wspd_contours, ax=ax) # Set the map bounds ax.set_xlim(cartopy_xlim(ht)) ax.set_ylim(cartopy_ylim(ht)) # Agregamos la línea de costas ax.coastlines(resolution='10m', linewidth=0.6) # Agregamos los límites de los países ax.add_feature(countries, linewidth=0.4) # Agregamos los límites de las provincias ax.add_feature(states_provinces, linewidth=0.4) # Le damos formato a las etiquetas de los ticks #print(lons) #exit() ax.set_yticks(np.arange(-29, -19, 2), crs=crs.PlateCarree()) ax.set_xticks(np.arange(-70, -59, 2), crs=crs.PlateCarree()) lon_formatter = LongitudeFormatter(zero_direction_label=True) lat_formatter = LatitudeFormatter()
# obtendo LON,LAT dos pontos de grade obtidos acima # lat_lon_gridpoints[0,...] -> valores latitude # lat_lon_gridpoints[1,...] -> valores longitude lat_lon_gridpoints = wrf.xy_to_ll(arq, estacoes_met_wrf[0, :], estacoes_met_wrf[1, :]) # criando mapa com pontos de grade usados para extração e coordenadas das estações INMET projWRF = wrf.get_cartopy(wrfin=arq) estados = cfeature.NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_1_states_provinces_shp') # limites X e Y das coordenadas projetadas xlims = wrf.cartopy_xlim(wrfin=arq) ylims = wrf.cartopy_ylim(wrfin=arq) # criando gráfico ax = plt.axes(projection=projWRF) ax.coastlines('50m', linewidth=0.8) ax.gridlines(color='black', linestyle='dotted') ax.add_feature(estados, linewidth=0.5, edgecolor='black') # obtendo domínio em torno do estado do RS RS = wrf.GeoBounds(wrf.CoordPair(lat=-35.0, lon=-60.0), wrf.CoordPair(lat=-26.0, lon=-48.0)) ax.set_xlim(wrf.cartopy_xlim(wrfin=arq, geobounds=RS)) ax.set_ylim(wrf.cartopy_ylim(wrfin=arq, geobounds=RS)) ax.set_title( 'Comparação INMET (vermelho) x WRF (verde)\n PCWRF/CPMet/FAMET/UFPel')