def test(projections): coords = [(-0.08, 51.53), (132.00, 43.17)] # London to Vladivostock orig_line_string = sgeom.LineString(coords) n_rows = math.ceil(math.sqrt(len(projections))) n_cols = math.ceil(len(projections) / n_rows) figure, axes_grid = plt.subplots(int(n_rows), int(n_cols)) if n_rows == 1 and n_cols == 1: axes_list = [axes_grid] else: axes_list = axes_grid.flat for projection, axes in zip(projections, axes_list): plt.sca(axes) colors = itertools.cycle(['b', 'g', 'r', 'c', 'm', 'y', 'k']) bits = ( #'contour', #'contourf', 'boundary', #'line', #'grid', 'coastline', #'polygons', 'continents', ) if 'contour' in bits: # Contours - placeholder for MPL integration cs = plt.contour(*wave_data()) plt.cla() for c in cs.collections: #for c in cs.collections[2:3]: for p in c.get_paths(): #for p in c.get_paths()[1:]: xy = [segment[0] for segment in p.iter_segments()] line_string = sgeom.LineString(xy) #line_string = sgeom.LineString(xy[:3]) draw_line_string(projection, line_string, color=c.get_color()[0]) if 'contourf' in bits: # Filled contours - placeholder for MPL integration cs = plt.contourf(*wave_data()) plt.cla() for c in cs.collections: #for i, c in enumerate(cs.collections[2:3]): for p in c.get_paths(): #for j, p in enumerate(c.get_paths()[1:2]): xy = [segment[0] for segment in p.iter_segments()] xy = filter(lambda xy: xy[1] > -90, xy) polygon = sgeom.Polygon(xy) #polygon = sgeom.Polygon(xy[53:56]) draw_polygon(projection, polygon, color=c.get_facecolor()[0]) if 'boundary' in bits: plt.plot(*zip(*projection.boundary.coords), marker='') if 'line' in bits: draw_line_string(projection, orig_line_string, color='red') polygon = sgeom.LineString([(-50, -80), (90, -80)]) draw_line_string(projection, polygon) if 'grid' in bits: # Grid lines step = 15 lons = range(0, 360, step) for lon in lons: line_string = sgeom.LineString( [(lon, -75), (lon, 0), (lon, 75)]) draw_line_string(projection, line_string, linestyle=':') lons = lons + [lons[0]] lats = range(-90 + step, 90, step) for lat in lats: line_string = sgeom.LineString([(lon, lat) for lon in lons]) draw_line_string(projection, line_string, linestyle=':') if 'coastline' in bits: reader = shapereader.Reader(COASTLINE_PATH) print 'Reading coastline ...' all_geometries = list(reader.geometries()) print ' ... done.' geometries = [] geometries += all_geometries #geometries += all_geometries[48:52] # Aus & Taz #geometries += all_geometries[72:73] # GB #for geometry in geometries: for i, geometry in enumerate(geometries): for line_string in geometry: try: draw_line_string(projection, line_string) except ValueError: print i print geometry raise import sys sys.stdout.write('.') sys.stdout.flush() if 'polygons' in bits: # Square over pole (CW) polygon = sgeom.Polygon( [(0, 75), (-90, 75), (-180, 75), (-270, 75)]) draw_polygon(projection, polygon) # Square (CW) polygon = sgeom.Polygon( [(150, 75), (-150, 75), (-150, 55), (150, 55)]) draw_polygon(projection, polygon) # Wedge - demonstrates removal of interior when split (CW) polygon = sgeom.Polygon([(-5, 10), (20, 0), (-5, -10), (10, 0)]) draw_polygon(projection, polygon) # "Antarctica" (incl. non-physical boundary segments) (CW) polygon = sgeom.Polygon([(-50, -80), (90, -80), (160, -70), (160, -90), (-160, -90), (-160, -70)]) draw_polygon(projection, polygon) # Wedge polygon = sgeom.Polygon([(-10, 30), (10, 60), (10, 50)]) draw_polygon(projection, polygon) if 'continents' in bits: reader = shapereader.Reader(LAND_PATH) print 'Reading continents ...' all_geometries = list(reader.geometries()) print ' ... done.' geometries = [] geometries += all_geometries #geometries += all_geometries[7:8] # Antarctica #geometries += all_geometries[16:17] # Some E-equatorial island #geometries += all_geometries[93:94] # Some NE island #geometries += all_geometries[112:113] # Africa & Asia #geometries += all_geometries[95:96] # North and South America #geometries += all_geometries[126:] # Greenland #geometries += all_geometries[0:7] #geometries += all_geometries[8:] #geometries += all_geometries[8:16] #geometries += all_geometries[17:93] #geometries += all_geometries[94:112] #geometries += all_geometries[113:] for i, multi_polygon in enumerate(geometries): for polygon in multi_polygon: polygon = sgeom.Polygon(filter( lambda xy: xy[1] > -90, polygon.exterior.coords)) draw_polygon(projection, polygon, color=colors.next()) #draw_line_string(projection, polygon) import sys sys.stdout.write('.') sys.stdout.flush() plt.title(type(projection).__name__) plt.xlim(projection.x_limits) plt.ylim(projection.y_limits)
#------------------------------------------------------------------------------------------------------ # Choose the plot size (width x height, in inches) fig = plt.figure(figsize=(data1.shape[1]/float(plot_config["dpi"]), data1.shape[0]/float(plot_config["dpi"])), dpi=plot_config["dpi"]) # Define the projection proj = ccrs.Geostationary(central_longitude=longitude, satellite_height=h) img_extent = (x.min(), x.max(), y.min(), y.max()) # Use the Geostationary projection in cartopy ax = plt.axes([0, 0, 1, 1], projection=proj) # Plot the image img = ax.imshow(RGB, origin='upper', extent=img_extent, zorder=3) # Add countries shapefile = list(shpreader.Reader('ne_50m_admin_0_countries.shp').geometries()) ax.add_geometries(shapefile, ccrs.PlateCarree(), edgecolor=plot_config["countries_color"],facecolor='none', linewidth=plot_config["countries_width"], zorder=4) # Add continents shapefile = list(shpreader.Reader('ne_10m_coastline.shp').geometries()) ax.add_geometries(shapefile, ccrs.PlateCarree(), edgecolor=plot_config["continents_color"],facecolor='none', linewidth=plot_config["continents_width"], zorder=5) # Add coastlines, borders and gridlines ax.gridlines(color=plot_config["grid_color"], alpha=0.5, linestyle='--', linewidth=plot_config["grid_width"], xlocs=np.arange(-180, 180, plot_config["grid_interval"]), ylocs=np.arange(-180, 180, plot_config["grid_interval"]), draw_labels=False, zorder=6) # Remove the outline border ax.outline_patch.set_visible(False) # Add a title plt.annotate(plot_config["title_text"] + " " + date_formated , xy=(plot_config["title_x_offset"], plot_config["title_y_offset"]), xycoords='figure pixels', fontsize=plot_config["title_size"], fontweight='bold', color='white', bbox=dict(boxstyle="round",fc=(0.0, 0.0, 0.0), ec=(1., 1., 1.)), zorder=7)
def setUp(self): self.reader = shp.Reader(LAKES_PATH)
# Set shape name of map (which depicts the United States) shapename = 'admin_1_states_provinces_lakes_shp' states_shp = shpreader.natural_earth(resolution='110m', category='cultural', name=shapename) # Set title and title fontsize of plot using gvutil function instead of matplotlib function call gvutil.set_titles_and_labels( ax, maintitle= "Average Annual Precipiation \n Computed for the period 1899-1999 \n NCDC climate division data \n", maintitlefontsize=18) # Add outlines of each state within the United States for state in shpreader.Reader(states_shp).geometries(): facecolor = 'white' edgecolor = 'black' ax.add_geometries([state], ccrs.PlateCarree(), facecolor=facecolor, edgecolor=edgecolor) # For each variable (climate division) in data set, create outline on map and fill with random color for varname, da in ds.data_vars.items(): # This condition is included because first item in xarray only has one attribute, 'current date' if hasattr(da, 'state_name'): # Get number of years of data by dividing number of months recorded (length of array) by 12 (12 months per year)
def market_change_map(country_market): """ Takes a dictionary of format Country: Return and prints a color gradient map ranging from 5% to -5% as blue to red, respectively """ # Getting the base figure set up fig, ax = plt.subplots(figsize=(12, 6), subplot_kw={'projection': ccrs.PlateCarree()}) ax.add_feature(cartopy.feature.OCEAN) ax.set_extent([-150, 60, -25, 60]) shpfilename = shpreader.natural_earth(resolution='110m', category='cultural', name='admin_0_countries') # Reader and countries both are "generator objects" which can be iterated reader = shpreader.Reader(shpfilename) countries = reader.records() for country in countries: # 'soverignt' is the attribute with full country names name = country.attributes['sovereignt'] # So it is used to match the key of country name in the dictionary if name in country_market: # facecolor is normalized to a 0,1 gradient assuming daily returns capped at -5,5 ax.add_geometries(country.geometry, ccrs.PlateCarree(), facecolor=mpl.cm.bwr_r( (country_market[name] + 5) / 10), label=country.attributes['adm0_a3']) else: ax.add_geometries(country.geometry, ccrs.PlateCarree(), facecolor='0.75', label=country.attributes['adm0_a3']) # mm/dd/yyyy format and hour:minute for time stamps to indicate when the map was created/what # data was used date = time.strftime("%m/%d/%Y") hour = time.strftime("%H:%M") # Add the color bar for a legend norm = mpl.colors.Normalize(vmin=-5, vmax=5) cax = fig.add_axes([0.95, 0.2, 0.02, 0.6]) cb = mpl.colorbar.ColorbarBase(cax, cmap=mpl.cm.bwr_r, norm=norm, spacing='proportional') cb.set_label('One Day % Change', rotation=270, labelpad=16) cb.ax.yaxis.set_ticks_position('left') ax.set_title( "Daily Change in National Stock Markets\n(Taken on %s at %s)" % (date, hour)) ax.annotate( 'Source: Quandl at https://www.quandl.com/c/markets/global-stock-markets', (0, 0), (0, -20), xycoords='axes fraction', textcoords='offset points', va='top') plt.savefig('Daily_Change_%s.pdf' % time.strftime("%m_%d_%Y"), bbox_inches='tight')
def DrawingMini(filename, dataName, lonMin, lonMax, latMin, latMax, cbarticks, savePath, month): plt.rcParams.update({'font.size': 15}) fig = plt.figure(figsize=(10, 9)) ax = fig.add_subplot(111) plt.xticks([]) plt.yticks([]) plt.axis('off') fh = Dataset(filename, mode='r') lons = fh.variables['lon'][:] lats = fh.variables['lat'][:] data = fh.variables[dataName][:] # data=data*10**3 # data=data*10**3 if month != 0: data = data * 2.63 * 0.73461 * (10**(-9)) / 3600 else: data = data * 10**3 # data = data * (10 ** -16) fh.close() nx = data.shape[1] ny = data.shape[0] proj = ccrs.PlateCarree() ax = fig.subplots(1, 1, subplot_kw={'projection': proj}) chinaProvince = shpreader.Reader( resolvePath('./Data_ipynb/cn_province.dbf')).geometries() # 绘制中国国界省界九段线等等 ax.add_geometries(chinaProvince, proj, facecolor='none', edgecolor='black', linewidth=1.5, zorder=1) extent = [lonMin, lonMax, latMin, latMax] ax.set_extent(extent, proj) # gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, # linewidth=0.6, color='k', alpha=0.5, linestyle='--') # #正常程序 # gl.xlabels_top = False # gl.ylabels_right = False # gl.xformatter = LONGITUDE_FORMATTER # gl.yformatter = LATITUDE_FORMATTER norm = mpl.colors.Normalize(vmin=cbarticks[0], vmax=cbarticks[-1]) im = ax.pcolormesh(lons, lats, data, transform=ccrs.PlateCarree(), cmap=cm.Spectral_r, norm=norm) # position=fig.add_axes([0.7, 0.17, 0.15, 0.012]) # position=fig.add_axes([0.2, 0.05, 0.5, 0.012]) cb = plt.colorbar(im, aspect=35, shrink=0.6) # aspect左右缩进,越小越宽 font = { 'size': 16, } # cb.set_label('×$\mathregular{10^{16}}$ kg/s', fontdict=font) cb.set_ticks(cbarticks) cb.ax.tick_params(labelsize=18) plt.rcParams['font.sans-serif'] = ['Times New Roman'] plt.subplots_adjust(top=1, bottom=0, left=0, right=1.1, hspace=0, wspace=0) plt.margins(0, 0) # plt.savefig(savePath, dpi=600) # , bbox_inches='tight') pic_IObytes = io.BytesIO() # plt.savefig(savePath, dpi=600, format='jpg') plt.savefig(pic_IObytes, dpi=600, format='jpg') pic_IObytes.seek(0) pic_hash = base64.b64encode(pic_IObytes.read()).decode('ascii') # plt.show() return pic_hash
def add_cntry_names(axis, extent, projection=ccrs.PlateCarree()): """Add country names. Parameters: axis (cartopy.mpl.geoaxes.GeoAxesSubplot): cartopy axis. extent (list): geographical limits. projection (cartopy.crs projection, optional): geographical projection, PlateCarree default. """ shp_file = shapereader.natural_earth(resolution='10m', \ category='cultural', name='admin_0_countries') shp = shapereader.Reader(shp_file) for rec, point in zip(shp.records(), shp.geometries()): point_x = point.centroid.xy[0][0] point_y = point.centroid.xy[1][0] if (point_x <= extent[1]) and (point_x > extent[0]): if (point_y <= extent[3]) and (point_y > extent[2]): if 'Turks' in rec.attributes['NAME']: axis.text(point_x-0.18, point_y-0.15, rec.attributes['NAME'], \ horizontalalignment='left', verticalalignment='top', \ transform=projection, fontsize=12) elif 'Anguilla' in rec.attributes['NAME']: axis.text(point_x-0.05, point_y+0.05, rec.attributes['NAME'], \ horizontalalignment='center', verticalalignment='bottom', \ transform=projection, fontsize=12) elif 'Barth' in rec.attributes['NAME']: axis.text(point_x-0.05, point_y-0.02, rec.attributes['NAME'], \ horizontalalignment='right', verticalalignment='center', \ transform=projection, fontsize=12) elif 'Briti' in rec.attributes['NAME']: axis.text(point_x, point_y+0.05, rec.attributes['NAME'], \ horizontalalignment='center', verticalalignment='bottom', \ transform=projection, fontsize=12) elif 'U.S.' in rec.attributes['NAME']: axis.text(point_x+0.15, point_y+0.02, rec.attributes['NAME'], \ horizontalalignment='center', verticalalignment='bottom', \ transform=projection, fontsize=12) elif 'Martin' in rec.attributes['NAME']: axis.text(point_x+0.3, point_y, rec.attributes['NAME'], \ horizontalalignment='center', verticalalignment='center', \ transform=projection, fontsize=12) elif 'Maarten' in rec.attributes['NAME']: axis.text(point_x-0.4, point_y-0.05, rec.attributes['NAME'], \ horizontalalignment='center', verticalalignment='center', \ transform=projection, fontsize=12) elif 'Nev' in rec.attributes['NAME']: axis.text(point_x-0.4, point_y+0.01, 'St. Kitts', \ horizontalalignment='center', verticalalignment='center', \ transform=projection, fontsize=12) axis.text(point_x-0.15, point_y-0.13, 'Nevis', \ horizontalalignment='center', verticalalignment='center', \ transform=projection, fontsize=12) elif 'Antigua' in rec.attributes['NAME']: axis.text(point_x-0.1, point_y, 'Antigua', \ horizontalalignment='center', verticalalignment='center', \ transform=projection, fontsize=12) axis.text(point_x-0.34, point_y+0.35, 'Barbuda', \ horizontalalignment='center', verticalalignment='center', \ transform=projection, fontsize=12) if extent[2] < 18.0 < extent[3]: axis.text(-63.5, 17.65, 'Saba', \ horizontalalignment='center', verticalalignment='center', \ transform=projection, fontsize=12) axis.text(-63.4, 17.5, 'St. Eustatius', \ horizontalalignment='center', verticalalignment='center', \ transform=projection, fontsize=12)
""" import unittest import numpy as np import scipy.sparse as sparse import shapely from cartopy.io import shapereader from climada.entity.exposures.black_marble import country_iso_geom, \ _cut_country, fill_econ_indicators, _set_econ_indicators, _fill_admin1_geom, \ _cut_admin1, _resample_land from climada.entity.exposures.litpop.nightlight import NOAA_BORDER, NOAA_RESOLUTION_DEG SHP_FN = shapereader.natural_earth(resolution='10m', category='cultural', name='admin_0_countries') SHP_FILE = shapereader.Reader(SHP_FN) ADM1_FILE = shapereader.natural_earth(resolution='10m', category='cultural', name='admin_1_states_provinces') ADM1_FILE = shapereader.Reader(ADM1_FILE) class TestCountryIso(unittest.TestCase): """Test country_iso function.""" def test_che_kos_pass(self): """CHE, KOS""" country_name = ['Switzerland', 'Kosovo'] iso_name, _ = country_iso_geom(country_name, SHP_FILE) self.assertEqual(len(iso_name), len(country_name))
'iswr': 'W m-2', 'U_2m_above_srf': 'm/s', 'vw_dir': 'degrees true north', 'swe': 'm', 'snowdepthavg': 'm' } file_in = os.path.join(data_dir, 'QC', 'Hourly_QC.nc') # CRHO and other data # Load all obs OBS_data = xr.open_dataset(file_in, engine='netcdf4') #.load() # Rename obs variable names to model variable names OBS_data.rename(vars_all, inplace=True) p_file = os.path.join(data_dir, 'Static_data', 'CAN_adm1.shp') # Provences p_sh = list(shpreader.Reader(p_file).geometries()) # Cities/Towns to plot t_lat = [51.089682, 51.177924, 51.426574, 51.268964, 51.394761] t_lon = [-115.360909, -115.570507, -116.18042, -115.919495, -116.49353] t_name = ['Canmore', 'Banff', 'Lake Louise', 'Castle Junction', 'Field'] # Make fig dir if not os.path.isdir(fig_dir): os.mkdir(fig_dir) # General plotting functions # Plot setup def make_map(projection=ccrs.PlateCarree()): fig, ax = plt.subplots(subplot_kw=dict(projection=projection))
gdf_df_stats = gdf.merge(df_stats, on='FID') gdf_df_stats.set_index('FID', inplace=True) # get column names ax1_head = gdf_df_stats.columns[10] # P00082014 ax2_head = gdf_df_stats.columns[11] # P10082014 ax3_head = gdf_df_stats.columns[12] # P20082014 ax4_head = gdf_df_stats.columns[13] # P30082014 ax5_head = gdf_df_stats.columns[8] # MEAN ax6_head = gdf_df_stats.columns[6] # DC0082014 print ax1_head, ax2_head, ax3_head, ax4_head, ax5_head, ax6_head columns_shp = [ax1_head, ax2_head, ax3_head, ax4_head, ax5_head, ax6_head] # drop NaN values for axis gdf_df_stats.dropna(inplace=True, subset=columns_shp) #gdf_df_stats.head(50) #gdf_df_stats = gpd.pd.concat(frames, axis=1, join='inner') #gdf_df_stats.index.rename('FID', inplace=True) #gdf_df_stats.geometry = gdf_df_stats.geometry.astype(gpd.geoseries.GeoSeries) # overcome bug #gdf_df_stats.head(2) # if necessary save to shapefile out_filename = r'D:\GitHub\pynotebook\ipymodules\GDMA//world_NDAI'+date_str+'.shp' gdf_df_stats.to_file(out_filename) china_adm3 = out_filename china_adm3_shp = shapereader.Reader(china_adm3) # rasterize the data gdma.rasterize(date_str = date_str, in_shp = out_filename) gdma.plot_map(date_str = date_str, date=date, extent = extent)
points = poissonDisc(points, pRad, 30) end = time.time() print(str(len(points)) + " points in " + str(round(end - start)) + " seconds") ## Clean up data for point in points: point['land'] = False point['lon'] = point['lon'] % 360.0 if point['lon'] > 180.0: point['lon'] -= 360.0 ## Determine if they're Land or Water shpfilename = shapereader.natural_earth(resolution='110m', category='physical', name='land') reader = shapereader.Reader(shpfilename) countries = reader.records() for country in countries: for ii in range(len(points)): if country.geometry.contains( shp.Point(points[ii]['lon'], points[ii]['lat'])): points[ii]['land'] = True ## For each point build a little circle for ii in range(len(points)): pLat = points[ii]['lat'] pLon = points[ii]['lon'] vLats = [] vLons = [] #vP = [] gJ = []
from matplotlib import colors import matplotlib.font_manager as fm filename1 = 'F:/data/micaps/ecmwf_thin/CAPE/999/18051208.006' filename2 = 'F:/data/micaps/ecmwf_thin/ki/18051208.006' # filename1 = 'Y:/MICAPS/ecmwf_thin/CAPE/999/19090320.021' # filename2 = 'Y:/MICAPS/ecmwf_thin/ki/19090320.021' intimestr = '20' + filename1[-12:-4] dt = int(filename1[-3:]) intime = datetime.datetime.strptime(intimestr, '%Y%m%d%H') #初始场时间 ftime = intime + datetime.timedelta(hours=dt) #预报场时间 cape = micaps.micaps4(filename1) ki = micaps.micaps4(filename2) shpname1 = './shpfiles/bou2_4p.shp' sr1 = shpreader.Reader(shpname1) proshp1 = list(sr1.geometries()) shpname2 = './shpfiles/continents_lines.shp' sr2 = shpreader.Reader(shpname2) proshp2 = list(sr2.geometries()) fig = plt.figure(figsize=(8.5, 6), dpi=150) ax = plt.axes(projection=ccrs.PlateCarree(), aspect='auto') #ax.add_feature(cfeature.LAKES, alpha=1) ax.add_geometries(proshp1, ccrs.PlateCarree(), edgecolor='dimgrey', facecolor='none', alpha=1, linewidth=0.5) ax.add_geometries(proshp2,
def main(): # Parse the arguments from the command line parser = argparse.ArgumentParser() parser.add_argument('-m', '--map', help='Which type of map to be generated.') parser.add_argument('-t', '--time', nargs='+', help='Access and plot weather data X hours from now.', type=int, default=0) args = parser.parse_args() if args.map == 'verywide': map_ = map_utils.VeryWide() elif args.map == 'regional': map_ = map_utils.Regional() elif args.map == 'local': map_ = map_utils.Local() elif args.map == 'tropical': map_ = map_utils.Tropical() else: print("Invalid Map Type Requested.") return # Create maps for each time declared on command line for t in args.time: # Acquire the datasets from the GFS Global Catalog GFS_data = TDSCatalog( 'http://thredds.ucar.edu/thredds/catalog/grib/NCEP/GFS/' 'Global_0p25deg/catalog.xml?dataset=grib/NCEP/GFS/Global_0p25deg/Best' ) # Pull out our dataset and get the NCSS access point used to query data from the dataset dataset = GFS_data.datasets[0] ncss = dataset.subset() # Use the `ncss` object to create a new query object query = ncss.query() time = (datetime.utcnow() + timedelta(hours=t) ) # Time of data requested query.time(time) query.accept('netcdf4') query.variables('Temperature_surface') # Set the lat lon box for which specific area of the dataset to query if map_.map_type is not 'tropical': query.lonlat_box(north=map_.NorthSouthEastWest[0], south=map_.NorthSouthEastWest[1], east=map_.NorthSouthEastWest[2], west=map_.NorthSouthEastWest[3]) else: query.lonlat_box(north=map_.NorthSouthEastWest[0] + 10, south=map_.NorthSouthEastWest[1], east=map_.NorthSouthEastWest[2], west=map_.NorthSouthEastWest[3]) data = ncss.get_data(query) # Grab the keys from the data we want temperatures = data.variables['Temperature_surface'] latitudes = data.variables['lat'] longitudes = data.variables['lon'] # Remove 1d arrays from data for plotting temperatures = temperatures[:].squeeze() latitudes = latitudes[:].squeeze() longitudes = longitudes[:].squeeze() # Convert temps to Fahrenheit from Kelvin temperatures = convert_temperature_to_fahrenheit(temperatures) # Combine 1D latitude and longitudes into a 2D grid of locations lon_2d, lat_2d = np.meshgrid(longitudes, latitudes) # Create figure for plotting fig = plt.figure(figsize=(15, 9)) ax = fig.add_subplot(1, 1, 1, projection=ccrs.Mercator()) ax.set_extent(map_.NorthSouthEastWest[::-1], crs=ccrs.Geodetic()) # Add map features depending on map type ax.add_feature(cfeature.STATES.with_scale('50m'), linewidth=0.5) if map_.map_type == 'regional' or map_.map_type == 'local': reader = shpreader.Reader('../county_data/countyl010g.shp') counties = list(reader.geometries()) COUNTIES = cfeature.ShapelyFeature(counties, ccrs.PlateCarree()) ax.add_feature(COUNTIES, facecolor='none', edgecolor='black', linewidth=0.3) elif map_.map_type == 'tropical': countries = cfeature.NaturalEarthFeature(category='cultural', name='admin_0_countries', scale='50m', facecolor='none') ax.add_feature(cfeature.LAND) ax.add_feature(countries, edgecolor='black', linewidth=0.5) # Contour temperature value at each lat/lon cf = ax.contourf(lon_2d, lat_2d, temperatures, 40, extend='both', transform=ccrs.PlateCarree(), cmap='coolwarm') # Plot a colorbar to show temperature values colorbar = plt.colorbar(cf, ax=ax, fraction=0.032) colorbar.set_label('Temperature (\u00b0F)') # Plot all the cities if map_.map_type is not 'tropical': for city in map_.cities: for lat in range(len(latitudes)): for lon in range(len(longitudes)): if round_temps( city.lat) == latitudes[lat] and round_temps( city.lon) == (longitudes[lon] - 360): cityTemp_latlon = Utils.plot_latlon_cityTemp_by_maptype( lat=city.lat, lon=city.lon, map_type=map_.map_type) ax.text(cityTemp_latlon[1], cityTemp_latlon[0], int(round(temperatures[lat][lon])), fontsize='10', fontweight='bold', transform=ccrs.PlateCarree()) ax.plot(city.lon, city.lat, 'ro', zorder=9, markersize=2.00, transform=ccrs.Geodetic()) cityName_latlon = Utils.plot_latlon_cityName_by_maptype( lat=city.lat, lon=city.lon, map_type=map_.map_type) ax.text(cityName_latlon[1], cityName_latlon[0], city.city_name, fontsize='small', fontweight='bold', transform=ccrs.PlateCarree()) # Create a title with the time value ax.set_title('Temperature forecast (\u00b0F) for {} UTC'.format( str(time)[:-7]), fontsize=12, loc='left') # Company copyright text = AnchoredText(r'$\mathcircled{{c}}$ NickelBlock Forecasting', loc=4, prop={'size': 9}, frameon=True) ax.add_artist(text) # Data model data_model = AnchoredText('GFS 12z model', loc=3, prop={'size': 9}, frameon=True) ax.add_artist(data_model) # Add logo logo = Utils.get_logo() if map_.map_type is not 'tropical': ax.figure.figimage(logo, 1105, 137, zorder=1) else: ax.figure.figimage(logo, 1105, 181, zorder=1) plt.savefig('{}_Temperature_Hour_{}.png'.format(map_.map_type, t))
def plot_map(countries, reference_location, measure, shapefile_record_names_df, num_agebrackets=85): """ Plot map of states colored by distance from reference location. Args: countries (list) : list of countries reference_location (str) : name of reference location measure (str) : name of distance measure used shapefile_record_names_df (pandas DataFrame) : dataframe of shapefile record names and the associated locations num_agebrackets (int) : number of age brackets for the matrices used to calculate the distances Returns: Matplotlib figure. """ fig = plt.figure(figsize=(10, 5)) fig.subplots_adjust(bottom=0.08, top=0.99, left=0.04, right=0.96) ax = fig.add_subplot(111, projection=ccrs.PlateCarree()) ax.coastlines(resolution='110m', color='k', lw=0.4) country_codes = { 'United_States': 'USA', 'China': 'CHN', 'Australia': 'AUS', 'Canada': 'CAN', 'India': 'IND', 'South_Africa': 'ZAF', 'Japan': 'JPN', 'Russia': 'RUS', 'Europe': 'EUR', 'Israel': 'ISR' } shpfilename = shpreader.natural_earth(resolution='110m', category='cultural', name='admin_0_countries') reader = shpreader.Reader(shpfilename) ne_countries = reader.records() for nec in ne_countries: ax.add_geometries([nec.geometry], crs=ccrs.PlateCarree(), facecolor='#cccccc', edgecolor='k', lw=0.4) distance_df = read_in_distance(measure, num_agebrackets) shapefiledir = os.path.join( '/Users', 'dina', 'Dropbox (MOBS)', 'shapefiles') # change this before pushing to repo shapefiles = {} country_categories = {} country_categories[1] = [] country_categories[2] = [ 'China', 'Australia', 'Canada', 'India', 'United_States' ] country_categories[3] = ['South_Africa', 'Japan', 'Russia'] country_categories[4] = ['Europe'] country_categories[5] = ['Israel'] locations_not_included = set([ 'Dadra_and_Nagar_Haveli', 'Lakshadweep', 'Chandigarh', 'Ashmore_and_Cartier_Islands', 'Coral_Sea_Islands', 'Jervis_Bay_Territory', 'Albania', 'Armenia', 'Azerbaijan', 'Belarus', 'Belgium', 'Bosnia and Herzegovina', 'Croatia', 'Faroe Islands', 'Iceland', 'Kosovo', 'Macedonia', 'Moldova', 'Montenegro', 'Northern Cyprus', 'Poland', 'Russia', 'Serbia', 'Turkey', 'Ukraine', 'Russian_Federation', 'Ryazan', "Ryazan'" ]) for country in countries: if country in country_categories[1]: shpf = os.path.join(shapefiledir, 'USA_Qian', 'states_PRI.shp') elif country in country_categories[2]: shpf = os.path.join(shapefiledir, country_codes[country] + '_adm_shp', country_codes[country] + '_adm1.shp') elif country in country_categories[3]: shpf = os.path.join(shapefiledir, 'gadm36_' + country_codes[country] + '_shp', 'gadm36_' + country_codes[country] + '_1.shp') elif country in country_categories[4]: shpf = os.path.join(shapefiledir, country, country + '.shp') elif country in country_categories[5]: shpf = os.path.join(shapefiledir, 'gadm36_' + country_codes[country] + '_shp', 'gadm36_' + country_codes[country] + '_1.shp') shapefiles[country] = shpf p = [] distance_list = [] min_x = 0 max_x = 2500 reader = shpreader.Reader(shpf) cmap = cmocean.cm.matter distance_dic = {} for country in countries: locations = set(get_locations_by_country(locations_df, country)) if country != 'Israel' and country in locations: locations.remove(country) locations = locations - locations_not_included for location in sorted(locations): dist = get_distance(distance_df, reference_location, location) distance_dic[(country, location)] = dist for country in countries: reader = shpreader.Reader(shapefiles[country]) for shapefile_record in reader.records(): location = map_location_from_shapefile_record_name( shapefile_record, country, country_categories, shapefile_record_names_df) if country == 'Europe' and location == 'Georgia': pass poly = shapefile_record.geometry try: if country == 'Japan': if location in shapefile_record_names_df.location: x = distance_dic[(country, location)] else: try: x = distance_dic[(country, location + '-to')] except: try: x = distance_dic[(country, location + '-ken')] except: x = distance_dic[(country, location + '-fu')] elif country == 'Russia': if location in shapefile_record_names_df.location: x = distance_dic[(country, location)] else: try: x = distance_dic[(country, location + '_Oblast')] except: x = distance_dic[(country, location)] else: x = distance_dic[(country, location)] x = rescale_x(x, min_x, max_x) if poly.geom_type == 'MultiPolygon': for pol in poly: p.append(PolygonPatch(pol)) distance_list.append(x) else: p.append(PolygonPatch(poly)) distance_list.append(x) except: continue ax.add_geometries([shapefile_record.geometry], ccrs.PlateCarree(), facecolor=cmap(x), edgecolor='k', lw=0.2) ax.set_extent([-180, 180, -57, 110], crs=ccrs.PlateCarree()) ax2 = fig.add_axes( [-0.08, -0.14, 0.84, 0.01]) # don't show the axis itself, just need the colorbar L = 200 cbrange = np.zeros((8, L + 1)) for i in range(L + 1): cbrange[:, i] = float(i) / (L + 0) * max_x im = ax2.imshow(cbrange, cmap=cmap) cax, kw = mplt.colorbar.make_axes(ax, location='bottom', pad=0.05, aspect=33) cbar = fig.colorbar(im, cax=cax, **kw) cbar.ax.tick_params(labelsize=20) cbar.set_label(measure.replace('_distance_M', ' ').title() + ' Distance from ' + reference_location.replace('_', ' ').replace('-', ' '), fontsize=24) ax.set_frame_on(False) # fig_path = os.path.join(figdir, 'fig_5b.pdf') # fig.savefig(fig_path, format='pdf') # use at your own peril - pdfs are gigantic for this figure fig_path = os.path.join(figdir, 'fig_5b.png') fig.savefig(fig_path, format='png', dpi=450)
geoDs, maxDs, Slopes = zip(*sorted(zip(geoDs, maxDs, Slopes))) clr = randcolor() return [list(geoDs), list(maxDs), list(Slopes), clr] def is_land(x, y): return land.contains(sgeom.Point(x, y)) ######################### GET LAT-LONS FOR MAP ################################ land_shp_fname = shpreader.natural_earth(resolution='50m', category='physical', name='land') land_geom = unary_union(list(shpreader.Reader(land_shp_fname).geometries())) land = prep(land_geom) #m = plt.axes(projection=ccrs.PlateCarree()) img = io.imread('EnvData/SeaIceConcAndSnow.tif', as_gray=True) data = plt.imread('EnvData/SeaIceConcAndSnow.tif') map_lons = np.linspace(-180, 180, data.shape[1] - 1) map_lats = np.linspace(90, -90, data.shape[0] - 1) ######################### LOAD ENV DATA ########################################### TopoDat = io.imread('EnvData/Topography.tif', as_gray=True) LandDat = io.imread('EnvData/LandSurfaceTemp.tif', as_gray=True) VegDat = io.imread('EnvData/Vegetation.tif', as_gray=True) SeaDat = io.imread('EnvData/SeaSurfaceTemp.tif', as_gray=True)
def plot_France_WGS84(): ##{{{ ## Path path = os.path.dirname(os.path.realpath(__file__)) ## Load mask dataF = xr.open_dataset( os.path.join(path, "../output", "mask_France_WGS84.nc")) dataO = xr.open_dataset( os.path.join(path, "../output", "mask_France_Occitanie_WGS84.nc")) ## Data to plot lon, lat = dataF.lon, dataF.lat _, ny, nx = dataF.mask.shape X, Y = np.meshgrid(np.linspace(-np.pi, np.pi, nx), np.linspace(-np.pi, np.pi, ny)) Z = np.sin(X**2 + Y**2) ZF = np.where(dataF.mask[0, :, :] > 0, Z, np.nan) ZO = np.where(dataO.mask[0, :, :] > 0, Z, np.nan) Zc = np.ones_like(Z) ZFc = np.where(dataF.mask[0, :, :] > 0, np.nan, Zc) ZOc = np.where(dataO.mask[0, :, :] > 0, np.nan, Zc) ## Cartopy features shfileF = os.path.join(path, "../cnmask/data/gadm36_FRA_shp/gadm36_FRA_0.shp") featuresF = cf.ShapelyFeature(shpreader.Reader(shfileF).geometries(), ccrs.PlateCarree(), facecolor='none') shfileO = os.path.join(path, "../cnmask/data/gadm36_FRA_shp/gadm36_FRA_1.shp") featuresO = cf.ShapelyFeature(shpreader.Reader(shfileO).geometries(), ccrs.PlateCarree(), facecolor='none') ## Plot itself fig = plt.figure(figsize=(2 * 9, 10)) gs = gridspec.GridSpec(2, 2, height_ratios=[1, 0.03]) levels = np.linspace(-1, 1, 50) ## Plot of the france ax = fig.add_subplot(gs[0, 0], projection=ccrs.Mercator()) im = ax.contourf(lon, lat, ZF, cmap=plt.cm.turbo, levels=levels, zorder=1, transform=ccrs.PlateCarree()) ax.contourf(lon, lat, ZFc, cmap=plt.cm.Blues, levels=1, alpha=0.4, zorder=1, transform=ccrs.PlateCarree()) ax.add_feature(featuresF, edgecolor="black", zorder=2) ax.set_extent([-6, 11, 40, 52]) ax.set_title("Mask France (WGS84)") ## Plot of Occitanie ax = fig.add_subplot(gs[0, 1], projection=ccrs.Mercator()) im = ax.contourf(lon, lat, ZO, cmap=plt.cm.turbo, levels=levels, zorder=1, transform=ccrs.PlateCarree()) ax.contourf(lon, lat, ZOc, cmap=plt.cm.Blues, levels=1, alpha=0.4, zorder=1, transform=ccrs.PlateCarree()) ax.add_feature(featuresO, edgecolor="black", zorder=2) ax.set_extent([-6, 11, 40, 52]) ax.set_title("Mask Occitanie, in France (WGS84)") ## And now colorbar cax = fig.add_subplot(gs[1, :]) plt.colorbar(mappable=im, cax=cax, orientation="horizontal", ticks=[-1, -0.5, 0, 0.5, 1]) fig.subplots_adjust(top=0.95, bottom=0.03, left=0.03, right=0.97, hspace=0.05, wspace=0.01) plt.savefig(os.path.join(path, "France_WGS84.png")) plt.close(fig)
var = [] skew = [] num_sites = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000] kinds = ['global', 'hemi', 'land', 'water'] for kind in kinds: land = 'none' if kind == 'land' or kind == 'water': land_shp_fname = shpreader.natural_earth(resolution='10m', category='physical', name='land') land_geom = unary_union([record.geometry for record in shpreader.Reader(land_shp_fname).records() if record.attributes.get('featurecla') != "Null island"]) land = prep(land_geom) for sites in num_sites: for sim in range(1000): lons_lats = fxns.get_pts(sites, loc1, ed, method, kind, land) Ds = [] lats = [] lons = [] for lon_lat in lons_lats: lons.append(lon_lat[0])
def main(): config = load_config() regions = ['Lao Cai', 'Binh Dinh', 'Thanh Hoa'] styles = OrderedDict([ ('National_Road', Style(color='#ba0f03', zindex=6, label='National')), ('Provincial_Road', Style(color='#e0881f', zindex=5, label='Provincial')), ('Local_Road', Style(color='#1f99e0', zindex=4, label='Local')), ('Other', Style(color='#777777', zindex=3, label='Other')), ]) for region in regions: region_file = os.path.join( config['paths']['data'], 'Results', 'Flow_shapefiles', 'weighted_edges_commune_center_flows_' + region.lower().replace(' ', '') + '_5_tons.shp') plot_settings = get_region_plot_settings(region) ax = get_axes(plot_settings['bbox'], figsize=plot_settings['figure_size']) if region == 'Binh Dinh': plot_basemap(ax, config['paths']['data'], country_border='none', plot_states=False) else: plot_basemap(ax, config['paths']['data'], country_border='none', plot_states=True) scale_bar(ax, location=(0.8, 0.05), length=plot_settings['scale_legend']) proj_lat_lon = ccrs.PlateCarree() road_geoms_by_category = { 'National_Road': [], 'Provincial_Road': [], 'Local_Road': [], 'Other': [] } road_geoms_by_category_keys = list(road_geoms_by_category.keys()) for record in shpreader.Reader(region_file).records(): geom = record.geometry val = record.attributes['level'] if val > 3 or val < 0: val = 3 road_geoms_by_category[road_geoms_by_category_keys[val]].append( geom) for cat, geoms in road_geoms_by_category.items(): cat_style = styles[cat] ax.add_geometries(geoms, crs=proj_lat_lon, linewidth=1, edgecolor=cat_style.color, facecolor='none', zorder=cat_style.zindex) legend_from_style_spec(ax, styles) # output output_file = os.path.join( config['paths']['figures'], 'province_roads-{}.png'.format(region.lower().replace(' ', ''))) save_fig(output_file) plt.close()
def main(): config = load_config() inland_edge_file = os.path.join( config['paths']['data'], 'Results', 'Flow_shapefiles', 'weighted_edges_flows_national_inland.shp') color = '#0689d7' color_by_type = {'Inland Line': color} crop_cols = [ 'max_rice', 'max_cash', 'max_cass', 'max_teas', 'max_maiz', 'max_rubb', 'max_swpo', 'max_acof', 'max_rcof', 'max_pepp' ] ind_cols = [ 'max_sugar', 'max_wood', 'max_steel', 'max_constr', 'max_cement', 'max_fertil', 'max_coal', 'max_petrol', 'max_manufa', 'max_fisher', 'max_meat', 'max_tons' ] columns = crop_cols + ind_cols column_label_divisors = {c: 1 for c in columns} legend_label = "AADF (tons/day)" title_cols = [ 'Rice', 'Cashew', 'Cassava', 'Teas', 'Maize', 'Rubber', 'Sweet Potatoes', 'Coffee Arabica', 'Coffee Robusta', 'Pepper', 'Sugar', 'Wood', 'Steel', 'Construction materials', 'Cement', 'Fertilizer', 'Coal', 'Petroleum', 'Manufacturing', 'Fishery', 'Meat', 'Total tonnage' ] remove_routes_ids = [ ('watern_149', 'watern_429'), ('watern_429', 'watern_520'), ('watern_700', 'watern_520'), ('watern_210', 'watern_700'), ('watern_209', 'watern_210'), ('watern_1057', 'watern_1050'), ('watern_1050', 'watern_1051'), ('watern_1051', 'watern_183'), ('watern_183', 'watern_354'), ('watern_176', 'watern_354'), ] for c in range(len(columns)): ax = get_axes() plot_basemap(ax, config['paths']['data']) scale_bar(ax, location=(0.8, 0.05)) plot_basemap_labels(ax, config['paths']['data']) proj_lat_lon = ccrs.PlateCarree() column = columns[c] weights = [ record.attributes[column] for record in shpreader.Reader(inland_edge_file).records() ] max_weight = max(weights) width_by_range = generate_weight_bins(weights) geoms_by_range = {} for value_range in width_by_range: geoms_by_range[value_range] = [] for record in shpreader.Reader(inland_edge_file).records(): val = record.attributes[column] geom = record.geometry edge_id = (record.attributes['from_node'], record.attributes['to_node']) if val > 0 and (edge_id not in remove_routes_ids ): # only add edges that carry this commodity for nmin, nmax in geoms_by_range: if nmin <= val and val < nmax: geoms_by_range[(nmin, nmax)].append(geom) # plot for range_, width in width_by_range.items(): ax.add_geometries( [geom.buffer(width) for geom in geoms_by_range[range_]], crs=proj_lat_lon, edgecolor='none', facecolor=color, zorder=2) x_l = 102.3 x_r = x_l + 0.4 base_y = 14 y_step = 0.4 y_text_nudge = 0.1 x_text_nudge = 0.1 ax.text(x_l, base_y + y_step - y_text_nudge, legend_label, horizontalalignment='left', transform=proj_lat_lon, size=10) divisor = column_label_divisors[column] for (i, ((nmin, nmax), width)) in enumerate(width_by_range.items()): y = base_y - (i * y_step) line = LineString([(x_l, y), (x_r, y)]) ax.add_geometries([line.buffer(width)], crs=proj_lat_lon, linewidth=0, edgecolor=color, facecolor=color, zorder=2) if nmin == max_weight: label = '>{:.2f}'.format(max_weight / divisor) else: label = '{:.2f}-{:.2f}'.format(nmin / divisor, nmax / divisor) ax.text(x_r + x_text_nudge, y - y_text_nudge, label, horizontalalignment='left', transform=proj_lat_lon, size=10) plt.title(title_cols[c], fontsize=14) output_file = os.path.join(config['paths']['figures'], 'inland_flow-map-{}.png'.format(column)) save_fig(output_file) plt.close()
wrf_local_time = ( rh2.Time.to_index().tz_localize("UTC").tz_convert("America/Sao_Paulo")) # rh2.Time.to_series().tz_localize("UTC").tz_convert("America/Sao_Paulo") cet_df_mean = cetesb_aqs_pol_mean_df(CET, pol_params, cetesb_dom) no_aqs = filter_pol_mean_aqs(cet_df_mean, "no") import cartopy.crs as ccrs import cartopy.feature as cfeature import cartopy.io.shapereader as shpreader import matplotlib.colors from mpl_toolkits.axes_grid1 import make_axes_locatable #loading MASP shapefile reader_masp = shpreader.Reader("masp_shp/masp_shp.shp") masp = list(reader_masp.geometries()) MASP = cfeature.ShapelyFeature(masp, ccrs.PlateCarree()) def plot_spatial_wrf_cet_points(wrf_pol, cet_df_mean, pol, label_name, ax=None): wrf_mean = (wrf_pol.sel( Time=slice("2014-10-06 03:00", "2014-10-13 00:00")).mean(dim="Time")) cet_aqs = filter_pol_mean_aqs(cet_df_mean, pol) pol_min, pol_max = get_wrf_mean_cet_mean_range(cet_aqs, wrf_mean, pol) norm = matplotlib.colors.Normalize(0, pol_max)
import xarray as xr import numpy as np import matplotlib.pyplot as plt import pandas as pd import geopandas as gpd import cartopy.crs as ccrs import cartopy.io.shapereader as shpreader from scipy import signal from pylab import * from mask_shape_border import mask_shape_border from failure_probability import failure_probability # Crop space to either US or soy states usa = gpd.read_file('gadm36_USA_1.shp', crs="epsg:4326") us1_shapes = list(shpreader.Reader('gadm36_USA_1.shp').geometries()) state_names = [ 'Iowa', 'Illinois', 'Minnesota', 'Indiana', 'Nebraska', 'Ohio', 'South Dakota', 'North Dakota', 'Missouri', 'Arkansas' ] soy_us_states = usa[usa['NAME_1'].isin(state_names)] # Crop space to either BR or soy states bra = gpd.read_file('gadm36_BRA_1.shp', crs="epsg:4326") br1_shapes = list(shpreader.Reader('gadm36_BRA_1.shp').geometries()) state_br_names = ['Mato Grosso', 'Rio Grande do Sul', 'Paraná'] soy_br_states = bra[bra['NAME_1'].isin(state_br_names)] ############### calendar # mirca_2000 = xr.open_dataset("Soybeans.crop.calendar.nc") # # plot
def main(): fig = plt.figure() ax = fig.add_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) 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) 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', 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()
label2 = ax.clabel(cs2, fontsize=6, colors='white', inline=1, inline_spacing=2, fmt='%i', rightside_up=True, use_clabeltext=False) for l in label1+label2: l.set_rotation(0) b1 = ax.barbs(lon, lat, fnl_uwnd.to('knots').m, fnl_vwnd.to('knots').m, color='black', length=4.5, regrid_shape=15, pivot='middle',linewidth=1.5, zorder=103, transform=ccrs.PlateCarree()) b2 = ax.barbs(lon, lat, fnl_uwnd.to('knots').m, fnl_vwnd.to('knots').m, color='white', length=4.5, regrid_shape=15, pivot='middle',linewidth=0.5, zorder=104, transform=ccrs.PlateCarree()) # Use the cartopy shapefile reader to import FORECAST AREA. reader = shpreader.Reader('/home/victoraalvarez/Documents/pythonScripts/' 'pythonPlayground/mapFiles/fa/fa3.shp') fa = list(reader.geometries()) FA = cfeature.ShapelyFeature(fa, ccrs.PlateCarree()) ax.add_feature(FA,linewidth=1.5,facecolor='none',edgecolor='black',zorder=6) ax.add_feature(FA,linewidth=.5,facecolor='none',edgecolor='white',zorder=7) # Add title & colorbar. df = '%m/%d/%Y %H:%M' plt.title("500MB ANALYSIS",loc='left',fontsize=8,fontweight='bold', y=-0.07) timestamp = datetime.utcnow().strftime(df)+"Z" plt.title(timestamp,loc='right',fontsize=8,fontweight='bold', y=-0.07) plt.suptitle("DATA VALID: " + datatime,fontsize=6,ha='right',fontweight='bold',
col_mines = raw_data.min(axis=1) data = (raw_data - col_mines[:, np.newaxis]) / ((col_maxes-col_mines)[:, np.newaxis]) net = (b-a) * np.random.random((net_dims[0], net_dims[1], nFeatures)) + a print("*** net ***") print(net) fig_size = plt.rcParams["figure.figsize"] print("Current size of plot:", fig_size) fig_size[0]=18 fig_size[1]=8 plt.rcParams["figure.figsize"] = fig_size fig = plt.figure() gs = gridspec.GridSpec(1,2,width_ratios = [3,5]) axes[0] = fig.add_subplot(gs[0], aspect='equal') axes[0].set_xlim((0, net.shape[0]+1)) axes[0].set_ylim((0, net.shape[1]+1)) axes[1] = fig.add_subplot(gs[1],projection=ccrs.PlateCarree()) axes[1].add_feature(cartopy.feature.OCEAN) axes[1].set_extent([-150, 60, -25, 60]) shpfilename = './cartopy/shapefiles/natural_earth/cultural/110m_admin_0_countries.shp' print("shpfilename: ", shpfilename) reader = shpreader.Reader(shpfilename) plt.tight_layout() qInit = True ani = animation.FuncAnimation(fig, animate, nCnt, repeat=False, blit=False) plt.show()
''' box,lon,lat receptor,-102.14119642699995,31.902587319000077 receptor,-102.06890715999998,31.928683642000067 receptor,-102.03957186099996,31.873156213000073 receptor,-102.11577420099997,31.85033867900006 receptor,-102.14119642699995,31.902587319000077 emitter,-102.1346819997111,31.80019199958484 emitter,-102.0045175208385,31.83711037948465 emitter,-102.046423081171,31.94509160994673 emitter,-102.1790300003915,31.90254999960113 emitter,-102.1346819997111,31.80019199958484 '''.strip())) receptor_corners = df_corners.loc[df_corners['box'] == 'receptor', ['lon','lat']].values shp_soft = shpreader.Reader('data/SoftLaunch_alt.shp') plotter_options = { 'background_manager': BackgroundManager( add_image_options=[cimgt.GoogleTiles(style='satellite'), 13], ), 'title': title, 'contour_options': { 'levels': bndry, 'cmap': cmap, 'norm': norm, 'alpha': .5, 'extend': 'max', }, 'colorbar_options': { 'label': r'$CH_4$ (ppbV)',
def main(): config = load_config() output_file = os.path.join(config['paths']['figures'], 'coastal-map.png') coastal_edge_file = os.path.join( config['paths']['data'], 'Results', 'Flow_shapefiles', 'weighted_edges_flows_national_coastal.shp') coastal_node_file = os.path.join(config['paths']['data'], 'Waterways', 'waterways', 'ports_nodes.shp') color_by_type = { 'Coastal route': '#045a8d', 'Domestic hub': '#d95f0e', 'International hub': '#d90e23' } ax = get_axes() plot_basemap(ax, config['paths']['data']) scale_bar(ax, location=(0.8, 0.05)) plot_basemap_labels(ax, config['paths']['data']) proj_lat_lon = ccrs.PlateCarree() for record in shpreader.Reader(coastal_edge_file).records(): flow = record.attributes['max_tons'] if flow > 0: geom = record.geometry ax.add_geometries(geom, crs=proj_lat_lon, linewidth=1.5, edgecolor='#045a8d', facecolor='none', zorder=3) # Stations xs_domestic = [] ys_domestic = [] xs_international = [] ys_international = [] for record in shpreader.Reader(coastal_node_file).records(): port_type = record.attributes['port_class'] if port_type == 'class_1': geom = record.geometry x = geom.x y = geom.y xs_domestic.append(x) ys_domestic.append(y) elif port_type == 'class_1A': geom = record.geometry x = geom.x y = geom.y xs_international.append(x) ys_international.append(y) ax.scatter(xs_domestic, ys_domestic, transform=proj_lat_lon, facecolor='#d95f0e', s=12, zorder=5) ax.scatter(xs_international, ys_international, transform=proj_lat_lon, facecolor='#d90e23', s=12, zorder=5) # Legend legend_handles = [ mpatches.Patch(color=color, label=line) for line, color in color_by_type.items() ] plt.legend(handles=legend_handles, loc='lower left') save_fig(output_file)
def main(): config = load_config() crop_month_fields = [ 'P_Jan', 'P_Feb', 'P_Mar', 'P_Apr', 'P_May', 'P_Jun', 'P_Jul', 'P_Aug', 'P_Sep', 'P_Oct', 'P_Nov', 'P_Dec' ] title_cols = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] for cr in range(len(crop_month_fields)): rice_month_file = os.path.join(config['paths']['data'], 'rice_atlas_vietnam', 'rice_production.shp') ax = get_axes() plot_basemap(ax, config['paths']['data']) scale_bar(ax, location=(0.8, 0.05)) plot_basemap_labels(ax, config['paths']['data']) proj = ccrs.PlateCarree() for record in shpreader.Reader(rice_month_file).records(): geom = record.geometry region_val = 100.0 * record.attributes[ crop_month_fields[cr]] / record.attributes['P_total'] if region_val: if region_val > 0 and region_val <= 20: color = '#ffffcc' # TODO ax.add_geometries([geom], crs=proj, edgecolor='#ffffff', facecolor=color, label='0 to 20') elif region_val > 20 and region_val <= 40: color = '#c2e699' # TODO ax.add_geometries([geom], crs=proj, edgecolor='#ffffff', facecolor=color, label='20 to 40') if region_val > 40 and region_val <= 60: color = '#78c679' # TODO ax.add_geometries([geom], crs=proj, edgecolor='#ffffff', facecolor=color, label='40 to 60') elif region_val > 60 and region_val <= 80: color = '#31a354' # TODO ax.add_geometries([geom], crs=proj, edgecolor='#ffffff', facecolor=color, label='60 to 80') elif region_val > 80 and region_val <= 100: color = '#31a354' # TODO ax.add_geometries([geom], crs=proj, edgecolor='#ffffff', facecolor=color, label='80 to 100') else: ax.add_geometries([geom], crs=proj, edgecolor='#ffffff', facecolor='#ffffcc', label='0 to 20') colors = ['#ffffcc', '#c2e699', '#78c679', '#31a354', '#31a354'] labels = ['0 to 20', '20 to 40', '40 to 60', '60 to 80', '80 to 100'] # Legend legend_handles = [] for c in range(len(colors)): legend_handles.append( mpatches.Patch(color=colors[c], label=labels[c])) ax.legend(handles=legend_handles, title='Percentage production', loc='center left') plt.title(title_cols[cr], fontsize=14) output_file = os.path.join( config['paths']['figures'], 'rice_production_{}.png'.format(title_cols[cr])) save_fig(output_file) plt.close()
#################################################################################### ds = Dataset('/export/home/mbrewer/wrf_out/d02/wrfout_d02_2018-11-09_04:00:00') time = getvar(ds, "times", timeidx=ALL_TIMES) u, v = getvar(ds, 'uvmet10', timeidx=ALL_TIMES) lats, lons = latlon_coords(u) skip = 5 #################################################################################### ############################ RADAR READ-IN ######################################### #################################################################################### rad = glob("/export/home/mbrewer/Documents/radar_files/rad_0904/*") rad2 = glob("/export/home/mbrewer/Documents/radar_files/rad_0905/*") # %% ### Reading in local road shapefiles to be used with the "base map", the roads help to give some spatial scale and awarenes in my opinion reader = shpreader.Reader( '/export/home/mbrewer/wrf_out/shapefiles/tl_2018_06_prisecroads.shp') roads = list(reader.geometries()) ## Most major California roadways roads = cfeature.ShapelyFeature(roads, crs.PlateCarree()) reader = shpreader.Reader( '/export/home/mbrewer/wrf_out/shapefiles/tl_2018_06007_roads.shp') s_roads = list( reader.geometries()) ### All roads in Butte county.... kinda messy s_roads = cfeature.ShapelyFeature(s_roads, crs.PlateCarree()) # Function used to create the "base map for all of the plots" def plot_background(ax): ax.coastlines(resolution='10m', linewidth=2, color='black', zorder=4) political_boundaries = NaturalEarthFeature( category='cultural',
def setUp(self): self.reader = shp.Reader(RIVERS_PATH)
def main(): #---------------------------------------------------- # User Defined Part #---------------------------------------------------- # Result Input File result_in_file = '/home/metctm1/array/workspace/spellcaster-local/json_base/whole_china_prec_full_XY_result.json' sta_meta_file = '/home/metctm1/array/workspace/spellcaster-local/data/station/SURF_CLI_CHN_PRE_MUT_HOMO_STATION.xls' # Province shp file province_shp_file = os.getenv('SHP_LIB') + '/cnmap/cnhimap.dbf' county_shp_file = os.getenv('SHP_LIB') + '/cnmap/county_2004.dbf' #---------------------------------------------------- # Main function #---------------------------------------------------- np.random.seed(19680801) cmap = cmaps.BlAqGrYeOrReVi200 newcolors = cmap(np.linspace(0, 1, 12)) grey = np.array([200 / 256, 200 / 256, 200 / 256, 1]) newcolors[:1, :] = grey newcmap = ListedColormap(newcolors) # read shp files province_shp = shpreader.Reader(province_shp_file).geometries() county_shp = shpreader.Reader(county_shp_file).geometries() # get Sta meta sta_df = get_station_df(sta_meta_file) sta_df = sta_df.filter(['区站号', '省份', '纬度(度分)', '经度(度分)'], axis=1) sta_df['sta_num'] = sta_df['区站号'].transform(lambda x: int(x)) sta_df['lat'] = sta_df['纬度(度分)'].transform(lambda x: conv_deg(x[0:-1])) sta_df['lon'] = sta_df['经度(度分)'].transform(lambda x: conv_deg(x[0:-1])) sta_df['score'] = 0 len_sta = len(sta_df['score']) sta_df['score'] = 0.45 + np.random.random(len_sta) * 0.15 sta_df = sta_df.set_index('sta_num') # get score with open(result_in_file) as f: result_dic = json.load(f) for idx, itm in result_dic.items(): sta_df.at[int(idx), 'score'] = float(itm['sign_score']) # Set figure size proj = ccrs.LambertConformal( central_longitude=105, central_latitude=90, false_easting=400000, false_northing=400000) #,standard_parallels=(46, 49)) fig = plt.figure(figsize=[10, 8], frameon=True) # Set projection and plot the main figure ax = fig.add_axes([0.08, 0.05, 0.8, 0.94], projection=proj) # Set figure extent ax.set_extent([80, 128, 18, 55], crs=ccrs.PlateCarree()) # plot shp boundaries #ax.add_geometries(county_shp, ccrs.PlateCarree(),facecolor='none', edgecolor='gray',linewidth=0.5, zorder = 0) ax.add_geometries(province_shp, ccrs.PlateCarree(), facecolor='none', edgecolor='black', linewidth=1., zorder=1) # Add ocean, land, rivers and lakes ax.add_feature(cfeature.OCEAN.with_scale('50m')) ax.add_feature(cfeature.LAND.with_scale('50m')) # *must* call draw in order to get the axis boundary used to add ticks: fig.canvas.draw() # 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(55, 165, 10).tolist() yticks = np.arange(0, 65, 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) lambert_xticks(ax, xticks) lambert_yticks(ax, yticks) print(sta_df[sta_df['score'] < 0.5].count()) # Marker size in units of points^2 color_range = [ 0, ] color_range.extend(np.linspace(0.5, 1.0, 11).tolist()) sc = ax.scatter(sta_df['lon'], sta_df['lat'], marker='.', c=sta_df['score'], cmap=newcmap, norm=matplotlib.colors.BoundaryNorm( color_range, newcmap.N), s=15, zorder=9, transform=ccrs.Geodetic(), label='pr') ax.scatter(sta_df['lon'], sta_df['lat'], marker='.', c=sta_df['score'].where(sta_df['score'] > 0.8), cmap=newcmap, norm=matplotlib.colors.BoundaryNorm(color_range, newcmap.N), s=25, zorder=99, transform=ccrs.Geodetic(), label='pr') plt.title('Precipitation Pc on Test Set (2009-2018)', fontsize=BIGFONT) cax = fig.add_axes([0.15, 0.02, 0.7, 0.03]) #位置[左,下,右,上] cbar = fig.colorbar(sc, ticks=color_range, cax=cax, orientation='horizontal') # cbar = fig.colorbar(sc) # Show figure plt.savefig('../fig/pr_score.png', dpi=120, bbox_inches='tight')