def ResearchRegion_surface(): """ 在地图上画出柱表面混合比图 :return: """ fig = plt.figure(figsize=(11, 8), facecolor="white") # data = np.loadtxt('seasonAvr_data/SurfaceMixingRatio/1_seasonAvr.txt') data = np.loadtxt("allYearAvr_data/SurfaceMixingRatio/allYearAvr.txt") arr = np.zeros((180, 360)) for i in range(180): arr[i, :] = data[179 - i, :] longitude = np.loadtxt("lonlat_data/longitude.txt") latitude = np.loadtxt("lonlat_data/latitude.txt") m = Basemap(llcrnrlon=70, llcrnrlat=15, urcrnrlon=138, urcrnrlat=55, projection="mill", resolution="h") m.drawparallels(np.arange(5.5, 90.5, 1.0), color="w", linewidth=0.5, dashes=[1, 1], labels=[0, 0, 0, 0]) m.drawmeridians(np.arange(60.5, 181.5, 1.0), color="w", linewidth=0.5, dashes=[1, 1], labels=[0, 0, 0, 0]) m.drawmapboundary(fill_color="0.3") m.readshapefile("shp/CHINA", "CHINA", drawbounds=1, color="black") topo = maskoceans(longitude, latitude, arr) im = m.pcolormesh(longitude, latitude, topo, shading="flat", cmap=plt.cm.jet, latlon=True, vmin=0, vmax=500) m.drawlsmask(ocean_color="w", lsmask=0) cbar = m.colorbar() cbar.ax.set_ylabel("SurfaceMixingRatio", color="black", fontsize="14", rotation=90) plt.show()
def load_basemap_shapefile(shapefile, shapefile_reference_name, **kwargs): ''' Creates a basemap, then loads a shapefile into it. If an axis is not specified, it creates a new figure with a single axis. Arguments: shapefile: The filename of the shapefile (as a string). shapefile_reference_name: The name to give the shapefile in Basemap. **kwargs: arguments to the Basemap constructor. Returns: bmap: The Basemap instance. shapefile_shapes: The shape reference of the shapefile in the Basemap instance. shapefile_info: The reference for the shape information in the shapefile Basemap instance. ax: The axis the Basemap instance was loaded into. ''' #Basemap needs shapefile paths with no extensions, because #apparently doing this one-liner inside the code would be #too much effort. shapefile_no_ext = os.path.splitext(shapefile)[0] #Create an axis object if one wasn't passed as a kwarg: if 'ax' not in kwargs: ax = plt.figure().add_subplot(111) kwargs['ax'] = ax bmap = Basemap(**kwargs) bmap.readshapefile(shapefile_no_ext,shapefile_reference_name) shapefile_shapes = getattr(bmap,shapefile_reference_name) shapefile_info = getattr(bmap,shapefile_reference_name+'_info') return bmap, shapefile_shapes, shapefile_info, kwargs['ax']
def create_map(): poverty_data, error = world_bank_api.most_recent_poverty_data() if error is not None: print(error) return poverty_data = utils.dictify_list_of_dicts(poverty_data, 'country_code') world_map = Basemap() world_map.readshapefile('borders', 'countries') country_to_color, country_names = decide_colors_and_countries(world_map, poverty_data) axes = plt.gca() # get current axes instance for nshape, seg in enumerate(world_map.countries): country_name = country_names[nshape] if country_name not in country_to_color: print('could not find: ' + country_name) continue color = country_to_color[country_name] poly = Polygon(seg, facecolor=color, edgecolor=color) axes.add_patch(poly) add_legend() fig = plt.gcf() fig.set_size_inches(30, 15) plt.axis('off') fig.savefig('countries_by_poverty_rate_world_bank_data.png', dpi=100, bbox_inches='tight', pad_inches=0)
class Mapper: def __init__(self, state): with open(state_boundries_file_loc) as f: for line in f: line = line.rstrip().split(',') if line[0].lower() == state.lower(): ur_lon, ll_lat = float(line[1]), float(line[3]) ll_lon, ur_lat = float(line[2]), float(line[4]) center_lon = ll_lon + ur_lon if math.copysign(1, ll_lon) != math.copysign(1, ur_lon): center_lon = -180 + center_lon else: center_lon = center_lon / 2 center_lat = (ll_lat + ur_lat) / 2 self.m = Basemap(llcrnrlon = ll_lon, llcrnrlat = ll_lat, urcrnrlon = ur_lon, urcrnrlat = ur_lat, projection = 'lcc', lat_1 = center_lat, lon_0 = center_lon) def setBorders(self): self.m.readshapefile(states_shapefile_loc, 'states', drawbounds = True) def plotPoint(self, lat, lon): self.m.plot(lat, lon, latlon=True, marker='o', color='m') def displayMap(self): plt.show()
def main(): m = Basemap( projection='merc', ellps='WGS84', llcrnrlon=lower_left[0], llcrnrlat=lower_left[1], urcrnrlon=upper_right[0], urcrnrlat=upper_right[1], lat_ts=0, resolution='i') m.readshapefile( 'taxi_zone/taxi_zones_lat_lon', 'nyc', color='none', zorder=2) predicted_values = read_file("./predict/ground_truth.txt") #pickups = pickle.load(open('data/30_unnormalized.p', 'rb')) #ground_truth = read_file('./predict/ground_truth.txt') gen_heat_map(m, predicted_values) print 'finished'
def build_map_obj(shapefile): shp = fiona.open(shapefile + '.shp') bds = shp.bounds shp.close() extra = 0.01 ll = (bds[0], bds[1]) ur = (bds[2], bds[3]) coords = list(chain(ll, ur)) w, h = coords[2] - coords[0], coords[3] - coords[1] m = Basemap( projection='tmerc', lon_0=(coords[0] + coords[2])/2, lat_0=(coords[1] + coords[3])/2, ellps='helmert', llcrnrlon=coords[0] - w * 0.01, llcrnrlat=coords[1] - extra + 0.01 * h, urcrnrlon=coords[2] + w * 0.01, urcrnrlat=coords[3] + extra + 0.01 * h, resolution='i', suppress_ticks=True ) m.readshapefile(shapefile, 'SF', color='black', zorder=2 ) return m, coords
def plotmap(self,fig,ax): """ This function will plot the map of Alaska. The data will be plotted over it and will use the basemap class to position everything. Input fig - The figure handle for the plots. ax - The axes handle that the map will be plotted over. Output m - This is the handle for the basemap object. """ latlim2 = self.params['latbounds'] lonlim2 = self.params['lonbounds'] m = Basemap(projection='merc',lon_0=sp.mean(lonlim2),lat_0=sp.mean(latlim2),\ lat_ts=sp.mean(latlim2),llcrnrlat=latlim2[0],urcrnrlat=latlim2[1],\ llcrnrlon=lonlim2[0],urcrnrlon=lonlim2[1],\ rsphere=6371200.,resolution='i',ax=ax) # draw coastlines, state and country boundaries, edge of map. #m.drawcoastlines() # m.drawstates() # m.drawcountries() m.readshapefile('st99_d00','states',drawbounds=True) merstep = sp.round_((lonlim2[1]-lonlim2[0])/5.) parstep = sp.round_((latlim2[1]-latlim2[0])/5.) meridians=sp.arange(lonlim2[0],lonlim2[1],merstep) parallels = sp.arange(latlim2[0],latlim2[1],parstep) m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) plt.hold(True) return m
def build_basemap(): shapefile = DUBLIN_DED shp = fiona.open(shapefile+".shp") bds = shp.bounds shp.close() extra = 0.01 ll = (bds[0], bds[1]) ur = (bds[2], bds[3]) coords = list(chain(ll, ur)) w, h = coords[2] - coords[0], coords[3] - coords[1] m = Basemap( projection='tmerc', lon_0=-2., lat_0=49., ellps = 'WGS84', llcrnrlon=coords[0] - extra * w, llcrnrlat=coords[1] - extra + 0.01 * h, urcrnrlon=coords[2] + extra * w, urcrnrlat=coords[3] + extra + 0.01 * h, lat_ts=0, resolution='i', suppress_ticks=True) m.readshapefile( shapefile, 'dublin', color='none', zorder=2) return m, coords
def create_map(): """ create the base map for the choropleth. """ logging.debug('create_map() -- Please wait while I create the world.') degrees_width = 118.0 degrees_height = 55.0 center_lat = 44.5 center_lon = -110.0 my_map = Basemap( # ax=ax, projection='merc', # default is cyl ellps='WGS84', lat_0=center_lat, lon_0=center_lon, llcrnrlat=center_lat - degrees_height / 2.0, llcrnrlon=center_lon - degrees_width / 2.0, urcrnrlat=center_lat + degrees_height / 2.0, urcrnrlon=center_lon + degrees_width / 2.0, resolution='i', # 'c', 'l', 'i', 'h', 'f' ) logging.debug('created map') logging.debug('loading shapes...') for section_name in CONTEST_SECTIONS.keys(): # logging.debug('trying to load shape for %s', section_name) try: my_map.readshapefile('shapes/%s' % section_name, section_name, drawbounds=False) except IOError, err: logging.error('Could not load shape for %s' % section_name)
def graph(data_dict): # normalize data norm_data_dict = normalize_dict(data_dict) # Set up the basic map map = Basemap() map.drawmapboundary(fill_color=WATER_COLOR) # map.fillcontinents(color='#ddaa66',lake_color=WATER_COLOR) # Read in the counties map.readshapefile(SHAPEFILE, 'us_counties', drawbounds = False) for info, shape in zip(map.us_counties_info, map.us_counties): ax.add_patch( Polygon( np.array(shape), True, facecolor=get_color( norm_data_dict.get( (info['STATEFP'], info['COUNTYFP']), -1 ) ), edgecolor='k', linewidth=1. ) ) plt.show()
def generate_willowbase(zoom_in=False, resolution='i'): if zoom_in: width, height = 50000, 40000 lat_0 = 61.8 lon_0 = -150.1 else: width, height = 100000, 80000 lat_0 = 61.8 lon_0 = -149.75 mm = Basemap( width=width, height=height, resolution=resolution, projection='aea', lat_1=55., lat_2=65., lat_0=lat_0, lon_0=lon_0) mm.drawcoastlines() mm.drawrivers(color=water, linewidth=3, zorder=5) mm.drawmeridians(np.arange(-180, 180, 0.25), labels=[False, False, False, 1]) mm.drawparallels(np.arange(0, 80, 0.25), labels=[True, True, False, False]) mm.fillcontinents( color=earth, lake_color=water) mm.drawmapboundary(fill_color=water) mm.readshapefile( primaryroads, 'roads', color="darkslategrey", linewidth=3) return mm
def plot_ppi(sweep_dict, parm, **kwargs): radar_loc=kwargs.get('radar_loc', [-12.2492, 131.0444]) fig_name=kwargs.get('fig_name', 'ppi_'+parm+'_.png') fig_path=kwargs.get('fig_path', getenv('HOME')+'/bom_mds/output/') f=figure() #gp_loc=[-12.2492, 131.0444] Re=6371.0*1000.0 rad_at_radar=Re*sin(pi/2.0 -abs(radar_loc[0]*pi/180.0))#ax_radius(float(lat_cpol), units='degrees') lons=radar_loc[1]+360.0*sweep_dict['xar']/(rad_at_radar*2.0*pi) lats=radar_loc[0] + 360.0*sweep_dict['yar']/(Re*2.0*pi) def_loc_dict={'lat_0':lats.mean(), 'lon_0':lons.mean(),'llcrnrlat':lats.min(), 'llcrnrlon':lons.min(), 'urcrnrlat':lats.max() , 'urcrnrlon':lons.max(), 'lat_ts':lats.mean()} loc_dict=kwargs.get('loc_dict', def_loc_dict) map= Basemap(projection='merc', resolution='l',area_thresh=1., **loc_dict) xx, yy = map(lons, lats) #map.drawcoastlines() #map.drawcountries() map.drawmapboundary() map.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstntcd_r','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) map.drawmeridians(array([129,130,131,132,133]), labels=[1,0,0,1]) map.drawparallels(array([-14,-13,-12,-11,-10]), labels=[1,0,0,1]) levs_dict={'VR':linspace(-15,15,31), 'CZ': linspace(-8,64,10), 'PH': linspace(0,185,255), "RH": linspace(0,1.5,16), "SW":linspace(0, 5, 11), "ZD":linspace(-10,10,21), 'VE':linspace(-30,30,31), 'TI':linspace(-30,30,31), 'KD':linspace(-1.0,6.0,30)} titles_dict={'VR': 'Velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'PH': 'Differential Prop Phase (degrees)', 'RH':'Correlation Co-ef', 'SW':'Spectral Width (m/s)', 'ZD':'Differentail Reflectivity dBz', 'VE':'Edited Velocity (m/s)', 'TI':'Simualated winds,(m/s)', 'KD':'Specific differential Phase (Degrees/m)'} map.contourf(xx,yy,sweep_dict[parm], levels=levs_dict[parm]) p=sweep_dict['date'] dtstr='%(#1)02d-%(#2)02d-%(#3)04d %(#4)02d%(#5)02dZ ' %{"#1":p.day, "#2":p.month, "#3":p.year, "#4":p.hour, '#5':p.minute} title(sweep_dict['radar_name']+' '+dtstr+titles_dict[parm]) colorbar() savefig(fig_path+fig_name) close(f)
def crop(self): cc = [49.4, 2.420480, 51.726419, 6.589545] # belgium x0 = cc[1] y0 = cc[0] x1 = cc[3] y1 = cc[2] bmap = Basemap(resolution='i', llcrnrlat=y0, llcrnrlon=x0, urcrnrlat=y1, urcrnrlon=x1) bmap.land = None for path in self.shapefile_paths: bmap.readshapefile(path, 'land') self.polys += [shape2poly(shape) for shape in bmap.land] with open(self.in_file, 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') header = True for row in csvreader: if header: self.header = ','.join(row) header = False else: p1 = Point(float(row[0]), float(row[1])) p2 = Point(float(row[2]), float(row[3])) self.segments.append((p1, p2, row)) self.segments = [self.fix(segment) for segment in self.segments] # flatten self.segments = [item for sublist in self.segments for item in sublist]
def old_plot_cappi(x,y,data,sweep_dict, **kwargs): radar_loc=kwargs.get('radar_loc', [-12.2492, 131.0444]) parm=kwargs.get('parm','') fig_name=kwargs.get('fig_name', 'cappi_'+parm+'_.png') f=figure() #gp_loc=[-12.2492, 131.0444] Re=6371.0*1000.0 rad_at_radar=Re*sin(pi/2.0 -abs(radar_loc[0]*pi/180.0))#ax_radius(float(lat_cpol), units='degrees') lons=radar_loc[1]+360.0*x/(rad_at_radar*2.0*pi) lats=radar_loc[0] + 360.0*y/(Re*2.0*pi) def_loc_dict={'lat_0':lats.mean(), 'lon_0':lons.mean(),'llcrnrlat':lats.min(), 'llcrnrlon':lons.min(), 'urcrnrlat':lats.max() , 'urcrnrlon':lons.max(), 'lat_ts':lats.mean()} loc_dict=kwargs.get('loc_dict', def_loc_dict) map= Basemap(projection='merc', resolution='l',area_thresh=1., **loc_dict) longr, latgr=meshgrid(lons,lats) xx, yy = map(longr, latgr) #map.drawcoastlines() #map.drawcountries() map.drawmapboundary() map.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstntcd_r','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) map.drawmeridians(array([129,130,131,132,133]), labels=[1,0,0,1]) map.drawparallels(array([-14,-13,-12,-11,-10]), labels=[1,0,0,1]) comp_levs=linspace(-1.,1., 30) levs_dict={'VR':linspace(-15,15,31), 'CZ': linspace(-8,64,10), 'TEST':linspace(((abs(data)+data)/2.0).min(), data.max(), 200), 'i_comp':comp_levs,'j_comp':comp_levs,'k_comp':comp_levs} titles_dict={'VR': 'Velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'TEST':'TEST', 'i_comp':'i component','j_comp':'j component','k_comp':'k component'} map.contourf(xx,yy,data, levels=levs_dict[parm]) p=sweep_dict['date'] dtstr='%(#1)02d-%(#2)02d-%(#3)04d %(#4)02d%(#5)02dZ ' %{"#1":p.day, "#2":p.month, "#3":p.year, "#4":p.hour, '#5':p.minute} title(sweep_dict['radar_name']+' '+dtstr+titles_dict[parm]) colorbar() savefig(getenv('HOME')+'/bom_mds/output/'+fig_name) close(f)
class Mapper: def __init__(self): # Great Bay 43.0669N, 70.8686W self.m = Basemap(llcrnrlon=-70.96,llcrnrlat=43.,urcrnrlon=-70.55,urcrnrlat=43.2, projection='merc', resolution ='f') self.fig = plt.figure() self.ax = self.fig.add_subplot(111) self.m.drawmapboundary(fill_color='#ffffff') self.m.readshapefile('./n130', 'n130') self.m.fillcontinents(color='#cccccc',lake_color='#ffffff') self.patches = [] for info, shape in zip(self.m.n130_info, self.m.n130): self.patches.append(Polygon(np.array(shape), True)) self.ax.add_collection(PatchCollection(self.patches, facecolor= '#ffffff', edgecolor='#ffffff', linewidths=0., zorder=2)) def plot(self, pointA, pointB): self.m.plot([pointA[1], pointB[1]], [pointA[0], pointB[0]], latlon=True, linewidth=1, color='#666666') def trace(self, points): for i, value in enumerate(points): try: self.plot(points[i], points[i+1]) except (IndexError, ValueError) as e: print(e) self.m.plot(points[0][1], points[0][0], latlon=True, label='', marker='*', linewidth=.5, color='k') self.m.plot(points[i][1], points[i][0], latlon=True, label='', marker='8', linewidth=.5, color='k') def display(self, name): # draw coastlines, meridians and parallels. plt.savefig('.'.join([name, 'pdf']), format='pdf')
def shapefile_boundary(boundary_type, region_names): ''' :param boundary_type: The type of spatial subset boundary :type boundary_type: :mod:'string' :param region_names: An array of regions for spatial subset :type region_names: :mod:'list' ''' # Read the shapefile map_read = Basemap() regions = [] shapefile_dir = os.sep.join([os.path.dirname(__file__), 'shape']) map_read.readshapefile(os.path.join(shapefile_dir, boundary_type), boundary_type, drawbounds=False) # Note: The shapefile may contain countries or states with latin letters. # Hence, the output of readshapefile can be a mix of ascii and unicode # strings. Because python 2 and 3 treat them differently, we must # explicitly check. if boundary_type == 'us_states': for region_name in region_names: region_name = _force_unicode(region_name) for iregion, region_info in enumerate(map_read.us_states_info): state1 = _force_unicode(region_info['st'], 'latin-1') state2 = _force_unicode(region_info['state'], 'latin-1') if state1 == region_name or state2 == region_name: regions.append(np.array(map_read.us_states[iregion])) elif boundary_type == 'countries': for region_name in region_names: region_name = _force_unicode(region_name) for iregion, region_info in enumerate(map_read.countries_info): country = _force_unicode(region_info['COUNTRY'], 'latin-1') if (country.replace(" ", "").lower() == region_name.replace(" ", "").lower()): regions.append(np.array(map_read.countries[iregion])) return regions
def draw_samples(self, n_samples, burnin=100, thin=10): if not self.kde_model: self.fit_kde() # pick starting point start_x = np.array([[0., 31.]]) # get region for restricting samples margin = 0.5 m = Basemap(llcrnrlon=self.uganda_data.LONGITUDE.min() - margin, llcrnrlat=self.uganda_data.LATITUDE.min() - margin, urcrnrlon=self.uganda_data.LONGITUDE.max() + margin, urcrnrlat=self.uganda_data.LATITUDE.max() + margin, resolution='l', area_thresh=10000) m.readshapefile("data/regions/UGA_adm0", "regions", drawbounds=True) for xy, info in zip(m.regions, m.regions): p = path.Path(xy) slice_samples, _ = SliceSampler.SliceSampler.mvslice(self.kde_model.pdf, start_x, sample_size=n_samples, burnin=burnin, thin=thin, confirm_region=p) # we get lat, long; we want x, y return np.fliplr(slice_samples)
def making_map(lat_down, lon_down, lat_up, lon_up, shapefile): ### Making the map colours = ['purple','pink', 'red', 'blue', 'yellow', 'green'] from matplotlib import pyplot as plt from matplotlib import cm from matplotlib.collections import LineCollection from matplotlib.patches import Polygon from mpl_toolkits.basemap import Basemap import shapefile # just some standard matplob lib syntax to add a figure and then make a subplot fig = plt.figure(figsize=(15.7,12.3)) ax = plt.subplot(111) # make the map projection. Choose mercator and define upper and lower boundaries # urcrnrlat = upper right corner lattitude, urcrnrlon = upper right corner longitude # llcrnlat = lower left corner lattitude, llcrnrlon = lower left corner longitude # For Pensylvania, use following values: # lat_down = 39, lon_down = -82, lat_up = 43, lon = -74 # For Spain # lat_up = 4, lon_up = 44, lat_down = 9, lon_down = 36 # For Rajistan # m = Basemap(projection='merc', resolution='l',llcrnrlat= lat_down, llcrnrlon = lon_down, urcrnrlat = lat_up, urcrnrlon = -74, area_thresh=10000) m.drawcoastlines() # draw the coastlines m.drawstates() # draw the states m.drawcountries() # draw countries m.drawmapboundary(fill_color='white') # draw the boundary # read in the shapefile and draw them m.readshapefile(shapefile, 'countries_sf', drawbounds=True) print len(m.countries_sf) #number of shapes, so 69 test = [] #for i in range(len(m.countries_sf_info)): # if m.countries_sf_info[i]['NAME'] not in test: # test.append(m.countries_sf_info[i]['NAME']) print m.countries_sf_info[0]['NAME'] # this is how you get the state names # look over the shapes and actual data for shape, countie in zip(m.countries_sf, m.countries_sf_info): # now loop over all the keys and values in the dictionary for lookup in dictionary_colors.items(): # compare the countie name of the data with the countie name in the lookup table if lookup[0] == countie['NAME']: # then choose a country from our list depending on the value of the key color = colours[lookup[1]] poly = Polygon(shape, facecolor=color) plt.gca().add_patch(poly) plt.show()
def generate_map(self, location): path = os.path.join(settings.PROJ_DIR, 'www', 'maps', '%s.png' % location['code']) figprops = { 'dpi': 200, 'facecolor': '#a5bfdd', 'figsize': (8,8), 'frameon': False, } fig = plt.figure(1, **figprops) fig.clear() plt.cla() ax = fig.add_axes((0,0,1,1)) for sp in ax.spines.itervalues(): sp.set_linewidth(0.0) centroid = location['geo']['centroid'] map_config = { 'projection': 'lcc', 'resolution': 'h', 'width': 200000, # map width in meters 'height': 200000, # map height in meters 'lat_0': centroid[0], # latitude center of map 'lon_0': centroid[1], # longitude center of map # 'llcrnrlon': , # lower left longitude # 'llcrnrlat': , # lower left latitude # 'urcrnrlon': , # upper right longitude # 'urcrnrlat': , # upper right latitude } m = Basemap(**map_config) m.drawcoastlines(linewidth=0, color='#6993a6') m.drawmapboundary(fill_color='#a5bfdd') m.drawstates(linewidth=1.0, color='#7f7f7f') m.drawrivers(linewidth=1.0, color='#a5bfdd') m.fillcontinents(color='#f4f3f0', lake_color='#a5bfdd') m.readshapefile('/Users/Jeremy/Downloads/_/in15oc03/in101503', 'roadways', drawbounds=True, color="#999999", linewidth=1.0) # if location['code'] in self.shapes: # for shape in self.shapes[location['code']]: # poly = plt.Polygon(shape, facecolor="g", edgecolor="k", alpha=0.5) # plt.gca().add_patch(poly) if os.path.exists(path): os.unlink(path) #fig.draw() fig.savefig(path, format='png', bbox_inches='tight')
def MapShow_lambert(): m = Basemap(llcrnrlon=82, llcrnrlat=0, urcrnrlon=140, urcrnrlat=55, projection='lcc', lat_1=20, lat_2=40, lon_0=108) # draw boundaries using shapefile with countries boundaries m.readshapefile('/home/water5/lpeng/Masks/Shapefile/china_map/bou1_4m/bou1_4l', 'CHN_adm1', linewidth=2) m.readshapefile('/home/water5/lpeng/Masks/Shapefile/china_map/bou2_4m/bou2_4l', 'CHN_adm2', linewidth=1) # m.etopo() m.drawparallels(np.arange(20, 60, 20), labels=[1, 0, 0, 0]) # only left ytick m.drawmeridians(np.arange(90, 140, 30), labels=[0, 0, 0, 1]) # only bottom xtick plt.show()
def basemap_setup(self,smooth=1,lats=False,lons=False,proj='merc', Nlim=False,Elim=False,Slim=False,Wlim=False, drawcounties=False): """ Needs rewriting to include limited domains based on lats/lons. Currently, assuming whole domain is plotted. """ # Fetch settings basemap_res = self.D.basemap_res if proj=='lcc': width_m = self.W.dx*(self.W.x_dim-1) height_m = self.W.dy*(self.W.y_dim-1) m = Basemap( projection=proj,width=width_m,height=height_m, lon_0=self.W.cen_lon,lat_0=self.W.cen_lat,lat_1=self.W.truelat1, lat_2=self.W.truelat2,resolution=basemap_res,area_thresh=500, ax=self.ax) elif proj=='merc': if self.W and not Nlim and not isinstance(lats,N.ndarray): Nlim,Elim,Slim,Wlim = self.W.get_limits() elif Nlim==False: Nlim = lats.max() Slim = lats.min() Elim = lons.max() Wlim = lons.min() m = Basemap(projection=proj, llcrnrlat=Slim, llcrnrlon=Wlim, urcrnrlat=Nlim, urcrnrlon=Elim, lat_ts=(Nlim-Slim)/2.0, resolution='l', ax=self.ax) m.drawcoastlines() m.drawstates() m.drawcountries() if isinstance(drawcounties,str): # if not drawcounties.endswith('/'): # drawcounties = drawcounties + '/' m.readshapefile(drawcounties,'counties',linewidth=0.3,color='grey') # import pdb; pdb.set_trace() # Draw meridians etc with wrff.lat/lon spacing # Default should be a tenth of width of plot, rounded to sig fig # s = slice(None,None,smooth) if self.W and not isinstance(lats,N.ndarray): x,y = m(self.W.lons,self.W.lats) else: x,y = m(*N.meshgrid(lons,lats)) # pdb.set_trace() return m, x, y
class DataMapper: def __init__(self, data, map_key, map_value, show_plot=True, save_plot=False, plot_name=None): self.data = data self.map_key = map_key self.map_value = map_value self.show_plot = show_plot self.save_plot = save_plot self.plot_name = plot_name self.state_colors = {} # map state abbreviations to state names state_df = pd.read_csv('states.csv') self.state_codes = dict(zip(state_df['Abbreviation'], state_df['State'])) # http://stackoverflow.com/questions/7586384/color-states-with-pythons-matplotlib-basemap # https://github.com/matplotlib/basemap/blob/master/examples/fillstates.py self.map = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49, projection='lcc',lat_1=33,lat_2=45,lon_0=-95) self.map.readshapefile('st99_d00', name='states', drawbounds=True) def plot(self): state_values = dict(zip(self.data[self.map_key], self.data[self.map_value])) state_names = [shape_dict['NAME'] for shape_dict in self.map.states_info] v_min, v_max = 0., 1. cmap = plt.cm.hot ax = plt.gca() for state_code, value in state_values.iteritems(): if state_code not in self.state_codes: continue state_name = self.state_codes[state_code] #seg = self.map.states[state_names.index(state_name)] # calculate state's color on heatmap based on the value color_rgb = cmap(1. - np.sqrt((value - v_min)/(v_max - v_min)))[:3] color_hex = rgb2hex(color_rgb) # get the shape from shape file state_shape = self.map.states[state_names.index(state_name)] # create polygon based on shape and color, add it to plot poly = Polygon(state_shape, facecolor=color_hex, edgecolor=color_hex) ax.add_patch(poly) plt.title('Default rates in' + self.plot_name) plt.legend() if self.save_plot: plt.savefig(self.plot_name or 'plot name') if self.show_plot: plt.show()
def sfc_plot(starttime, endtime, variables, variablest, locations, met, xi, yi, xmin, xmax, ymin, ymax): ''' Script for plotting the mesonet data with wind barbs over a county map in a given time interval ''' interval = int((endtime - starttime).total_seconds()/300) z_max = np.max(met[variablest[1]]) z_min = np.min(met[variablest[1]]) levels = np.arange(z_min, z_max+1, 1) shapefile = 'UScounties/UScounties' if not os.path.exists('%s' %(variables)): os.makedirs('%s' %(variables)) for i in range(interval): time_selection = starttime + dt.timedelta(minutes=5*i) zi = interpolate.griddata((met.ix[time_selection]['Lon'], met.ix[time_selection]['Lat']), met.ix[time_selection][variablest[1]], (xi, yi), method='cubic') maps = Basemap(llcrnrlon=xmin, llcrnrlat=ymin, urcrnrlon=xmax, urcrnrlat=ymax, projection='cyl') maps.readshapefile(shapefile, name='counties') # mzi = np.ma.masked_array(zi,np.isnan(zi)) # levels = np.arange(np.min(mzi), np.max(mzi)+1., 1) if (variables == 'dew_point'): maps.contourf(xi, yi, zi, np.arange(0.,21, 1), cmap=plt.cm.gist_earth_r) # maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth_r) if (variables == 'relative_humidity'): maps.contourf(xi, yi, zi, np.arange(15.,51., 1.), cmap=plt.cm.gist_earth_r) # maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth_r) if ((variables == 'temperature') or (variables== 'theta_e')): maps.contourf(xi, yi, zi, np.arange(24,40.5,0.5), cmap=plt.cm.jet) # maps.contourf(xi, yi, zi, levels, cmap=plt.cm.jet) if variables == 'rainfall': maps.contourf(xi, yi, zi, levels, cmap=plt.cm.YlGn) if ((variables == 'pressure') or (variables == 'wind_speed') or (variables == 'gust_speed')): maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth) c = plt.colorbar() c.set_label(variablest[0]) maps.scatter(met.ix[time_selection]['Lon'], met.ix[time_selection]['Lat'], latlon=True, marker='o', c='b', s=5) maps.barbs(met.ix[time_selection]['Lon'], met.ix[time_selection]['Lat'], met.ix[time_selection]['u'].values*1.94384, met.ix[time_selection]['v'].values*1.94384, latlon=True) maps.drawparallels(np.arange(31.,36,1.), color='0.5', labels=[1,0,0,0], fontsize=10) maps.drawmeridians(np.arange(-104.,-98.,1.), color='0.5', labels=[0,0,0,1], fontsize=10) plt.title(variablest[1]) filename = '%s_%s.png' % (variables, time_selection.strftime('%Y%m%d_%H%M')) plt.tight_layout() plt.savefig(variables + '/' + filename, dpi=150) plt.clf()
def draw_crash_map(shpurl, name, llon, llat, rlon, rlat, lons, lats, data): ''' A function to plot hot spot map for crash rate and crash severity Parameters: @shpurl {string} the shapefile url, without suffix, e.g. '../data/highway/wgs84' @name {float} either 'rate' or 'severity' @llon {float} longitude of the top left corner @llat {float} latitude of the top left corner @rlon {float} longitude of the bottom right corner @rlat {float} latitude of the bottom right corner @lons {a list of float} longitudes of the crash spots @lats {a list of float} latitudes of the crash spots @data {a list of float} data for crash rates or severity Return: Nothing ''' # set up a map canvas map = Basemap(llcrnrlon=llon, llcrnrlat=llat, urcrnrlon=rlon, urcrnrlat=rlat, resolution='i', projection='tmerc', lat_0=(llat+rlat)/2, lon_0=(llon+rlon)/2) # read the shapefile map.readshapefile(shpurl, 'highway') # get the max value from the data to scale the size of the marker max_val = max(data) # plot the hot spots one by one with the marker # size corresponding to the data for index in range(len(data)): x, y = map(lons[index], lats[index]) map.plot(x, y, marker='o', color='r', markersize=((data[index]*15/max_val)+5)) # update the min value that is larger than 0 if data[index] > 0 and data[index] < min_val: min_val = data[index] # create legends # the largest marker and the smallest marker red_dot1, = plt.plot([], "ro", markersize=20) red_dot2, = plt.plot([], "ro", markersize=5) # determine the legend according to the parameter @name if name == 'rate': str1 = 'Max crash rate:' + str(round(max_val, 2)) str2 = 'Min crash rate:' + str(round(min_val, 2)) else: str1 = 'Max crash severity:' + str(round(max_val, 2)) str2 = 'Min crash severity:' + str(round(min_val, 2)) plt.legend([red_dot1, red_dot2], [str1, str2]) # show the map plt.show()
def generate_darwin_plot(**kwargs): ber_loc=[-12.4, 130.85] #location of Berrimah radar gp_loc=[-12.2492, 131.0444]#location of CPOL at Gunn Point box=kwargs.get('box',[130.0, 132.0, -13.0, -11.5])#box for the plot #Set up the map and projection map= Basemap(projection='merc',lat_0=(box[2]+box[3])/2.0, lon_0=(box[0]+box[1])/2.0,llcrnrlat=box[2], llcrnrlon=box[0], urcrnrlat=box[3] , urcrnrlon=box[1], resolution='l',area_thresh=1., lat_ts=(box[2]+box[3])/2.0) #map.drawmapboundary() map.readshapefile(getenv('HOME')+'/bom_mds/shapes/nt_coast','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None) map.drawmeridians(array([129,130,131,132,133]), labels=[1,0,0,1]) map.drawparallels(array([-14,-13,-12,-11,-10]), labels=[1,0,0,1]) return map
def plot(): #LowerLeftCorner,UpperRightCorner map = Basemap(llcrnrlat=40.4961, llcrnrlon=-74.2559, urcrnrlat=40.9556, urcrnrlon=-73.6677, resolution = 'h', epsg=2260) patchesBK = [] patchesBX = [] patchesMN = [] patchesQN = [] patchesSI = [] map.drawmapboundary(fill_color='aqua') #Fill the continents with the land color map.fillcontinents(color='green',lake_color='aqua') map.drawcoastlines() # load the shapefile, use the name 'states' map.readshapefile('geo_export_5d40c3f0-4e17-4f62-b896-8938f11c233f', name='districts', drawbounds=False) ax = plt.gca() # get current axes instance for info, shape in zip(map.districts_info, map.districts): if info['boro'] == 'BK': patchesBK.append( Polygon(np.array(shape), True) ) if info['boro'] == 'BX': patchesBX.append( Polygon(np.array(shape), True) ) if info['boro'] == 'QN': patchesQN.append( Polygon(np.array(shape), True) ) if info['boro'] == 'MN': patchesMN.append( Polygon(np.array(shape), True) ) if info['boro'] == 'SI': patchesSI.append( Polygon(np.array(shape), True) ) ax.add_collection(PatchCollection(patchesBK, facecolor= 'm', edgecolor='k', linewidths=1., zorder=2)) ax.add_collection(PatchCollection(patchesBX, facecolor= 'r', edgecolor='k', linewidths=1., zorder=2)) ax.add_collection(PatchCollection(patchesQN, facecolor= 'b', edgecolor='k', linewidths=1., zorder=2)) ax.add_collection(PatchCollection(patchesMN, facecolor= 'y', edgecolor='k', linewidths=1., zorder=2)) ax.add_collection(PatchCollection(patchesSI, facecolor= 'grey', edgecolor='k', linewidths=1., zorder=2)) Bronx = mpatches.Patch(color='red', label='Bronx') Manhattan = mpatches.Patch(color='yellow', label='Manhattan') Queens = mpatches.Patch(color='blue', label='Queens') Staten_Is = mpatches.Patch(color='grey', label='Staten Is.') Brooklyn = mpatches.Patch(color='magenta', label='Brooklyn') plt.legend(handles=[Bronx,Manhattan,Queens,Brooklyn,Staten_Is],loc=2) plt.title("NYC School Districts by Borough") plt.show()
def scatter_subplots(lons1, lats1, data1, s1, lons2, lats2, data2, s2, title1=None, title2=None): fig = plt.figure() # first subplot ax1 = fig.add_subplot(121) m = Basemap(projection='cyl', llcrnrlat=10, urcrnrlat=35, llcrnrlon=65, urcrnrlon=85) m.drawcoastlines() m.drawcountries() parallels = np.arange(-90,90,15.) m.drawparallels(parallels,labels=[1,0,0,0]) meridians = np.arange(-180,180,15.) m.drawmeridians(meridians,labels=[0,0,0,1]) m.readshapefile(os.path.join('C:\\', 'Users', 'i.pfeil', 'Documents', '0_IWMI_DATASETS', 'shapefiles', 'IND_adm', 'IND_adm2'), 'IN.MH.JN') if title1: plt.title(title1) sc = m.scatter(lons1, lats1, c=data1, edgecolor='None', marker=',', s=s1, vmin=0, vmax=1, cmap='RdYlGn') m.colorbar(sc, 'right', size='5%', pad='2%') # second subplot ax2 = fig.add_subplot(122, sharex=ax1, sharey=ax1) m = Basemap(projection='cyl', llcrnrlat=10, urcrnrlat=35, llcrnrlon=65, urcrnrlon=85) m.drawcoastlines() m.drawcountries() parallels = np.arange(-90,90,15.) m.drawparallels(parallels,labels=[1,0,0,0]) meridians = np.arange(-180,180,15.) m.drawmeridians(meridians,labels=[0,0,0,1]) m.readshapefile(os.path.join('C:\\', 'Users', 'i.pfeil', 'Documents', '0_IWMI_DATASETS', 'shapefiles', 'IND_adm', 'IND_adm2'), 'IN.MH.JN') if title2: plt.title(title2) sc = m.scatter(lons2, lats2, c=data2, edgecolor='None', marker=',', s=s2, vmin=0, vmax=1, cmap='RdYlGn') m.colorbar(sc, 'right', size='5%', pad='2%') plt.show()
def probs_heatmap(probs, state_dict, output_dir='.', verbose=True): try: os.mkdir(output_dir) except OSError: pass for (cluster_i, cluster) in enumerate(probs): if verbose: print('Initializing map for cluster %d/%d...' % (cluster_i+1, len(probs))) fig = plt.figure() ax = fig.add_subplot(111) m = Basemap(width=12000000, height=9000000, projection='lcc', resolution='l', lat_1=45., lat_2=55, lat_0=50, lon_0=-115., ax=ax) m.drawcoastlines() if verbose: print('Reading shapefiles...') m.readshapefile('shapefiles/us', 'us', drawbounds=False) m.readshapefile('shapefiles/canada', 'canada', drawbounds=False) for (abbr, count, n_preds) in cluster: region = state_dict[abbr] # a few hacky fixes for regions if region == 'Newfoundland' or region == 'Labrador': # ignore, no way to do this without regrouping the raw data as # you'll have some in one but not the other and some in both continue elif region == 'Qu\xe9bec': region = 'Quebec' elif region == 'Yukon': region = 'Yukon Territory' prob = count / float(n_preds) for i in range(len(m.canada)): if m.canada_info[i]['NAME'] == region: (x, y) = zip(*m.canada[i]) plt.fill(x, y, color=(1-prob, 1-prob, 1)) for i in range(len(m.us)): if m.us_info[i]['NAME'] == region: (x, y) = zip(*m.us[i]) plt.fill(x, y, color=(1-prob, 1-prob, 1)) ax.set_title('Cluster %d (n = %d)' % (cluster_i, cluster[0][2])) filename = os.path.join(output_dir, 'cluster%d.png' % cluster_i) plt.savefig(filename) if verbose: print('Written to %s.' % filename) plt.close(fig)
def plot_garland(lon_min, lat_min,lon_max,lat_max): """ Create a plot of Texas. """ m = Basemap( llcrnrlon=-lon_min, llcrnrlat=lat_min, urcrnrlon=lon_max, urcrnrlat=lat_max, projection='mill', resolution='f') m.readshapefile(hms_basins,'SubbasinHRAP',drawbounds=True) return m
def ___try_osgeo(): try: from osgeo import ogr except: import ogr import re import os import cpblUtilities reload(cpblUtilities) from cpblUtilities import unique, doSystem,tsvToDict from cpblUtilities.mathgraph import tonumeric, overplotLinFit,xTicksLogIncome from copy import deepcopy from .cpblUtilities_config import defaults import pylab from matplotlib.mlab import prctile_rank import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap as Basemap # cities colored by population rank. m = Basemap() #following fails: no epxlanation. grrrrrrrrrrr! shp_info = m.readshapefile(defaults['inputPath']+'healthRegions/shp/test','HRuid') #woeiur Following fails: needs conversion by mapproj?? shp_info = m.readshapefile(defaults['inputPath']+'healthRegions/shp/HR000b07_PZ','HRuid') woeiur shp_info = m.readshapefile('/home/cpbl/tmp/cities','cities') x, y = zip(*m.cities) pop = [] for item in m.cities_info: population = item['POPULATION'] if population < 0: continue # population missing pop.append(population) popranks = prctile_rank(pop,100) colors = [] for rank in popranks: colors.append(plt.cm.jet(float(rank)/100.)) m.drawcoastlines() m.fillcontinents() m.scatter(x,y,25,colors,marker='o',edgecolors='none',zorder=10) plt.title('City Locations colored by Population Rank') plt.show()
magU = np.sqrt(u_c**2 + v_c**2) coeff = ((p * cos_lat) / (2 * magU.T)).T #x-component of TN-WAF px = (coeff.T / (a * a * cos_lat)).T * (((u_c.T) / cos_lat).T * termxu + v_c * termxv) #y-component of TN-WAF py = (coeff.T / (a * a)).T * (((u_c.T) / cos_lat).T * termxv + v_c * termyv) #end of computation ############################################ fig, ax = plt.subplots() m = Basemap(projection='nplaea', boundinglat=10.5, lon_0=90, resolution='l', round=True) m.readshapefile('D:\\dt\\bou1_4l', 'china', color='crimson') m.drawcoastlines(linewidth=0.3, color='gray') m.drawparallels(np.arange(0., 81., 20.), linewidth=0.4, color='gray') m.drawmeridians(np.arange(0., 360., 60.), linewidth=0.4, color='gray', labels=[True, True, True, True]) my_map = copy(plt.cm.RdBu_r) my_map.set_under((18 / 255, 73 / 255, 132 / 255), 1.0) my_map.set_over((131 / 255, 11 / 255, 37 / 255), 1.0) psi_p1, lon1 = addcyclic(psi_p, lon) lonsn, latsn = np.meshgrid(lon1, lat[0:160]) x_cyc, y_cyc = m(lonsn, latsn)
lat = nc20.latitude lon = nc20.longitude z_500 = (gaussian_filter(z.isel(level=0, time=12), sigma=3.0)) / 98 #地图制作 fig = plt.figure(dpi=300) ax = plt.gca() m5 = Basemap(llcrnrlon=80, llcrnrlat=0, urcrnrlon=140, urcrnrlat=51, projection='lcc', lat_1=33, lat_2=45, lon_0=100) m5.readshapefile("CHN_adm_shp//CHN_adm1", 'china', drawbounds=True) #全国图显示省界 m5.readshapefile( "CHN_adm_shp//china-shapefiles-master//china_nine_dotted_line", 'nine_dotted', drawbounds=True) m5.readshapefile("CHN_adm_shp//CHN_adm2", "states", drawbounds=False) #全国图不显示地级市界(含地级市内容) lon, lat = np.meshgrid(lon, lat) x, y = m5(lon, lat) cs1 = m5.contour(x, y, z_500, np.arange(552, 588, 4), linewidths=0.4, colors='b') #绘制等高线 cs2 = m5.contour(x, y, z_500, levels=[588], colors='purple', linewidths=0.6)
timer = datetime.now() m = Basemap(resolution='i',projection='cyl',\ llcrnrlon=bot_left_lon,llcrnrlat=bot_left_lat,\ urcrnrlon=top_right_lon,urcrnrlat=top_right_lat,) m.drawcoastlines(linewidth=2,color='b') print 'map',datetime.now()-timer timer = datetime.now() x,y = m(lon,lat) print 'convert',datetime.now()-timer timer = datetime.now() BASE = '/uufs/chpc.utah.edu/common/home/u0553130/' # Draw other shape files (selected lakes, Utah roads, county lines) m.readshapefile(BASE+'shape_files/tl_2015_UtahLake_areawater/tl_2015_49049_areawater','lakes', linewidth=1.5) m.readshapefile(BASE+'shape_files/tl_2015_UtahRoads_prisecroads/tl_2015_49_prisecroads','roads', linewidth=.5) print 'shapefile', datetime.now()-timer timer = datetime.now() im = plt.contourf(x,y,speed, np.arange(0,np.max(speed),.25),cmap = plt.cm.Greens) print 'contour',datetime.now()-timer timer = datetime.now() ## Wind Barbs units = 'm/s' if units == 'm/s': HALF = 2.5 FULL = 5 FLAG = 25 if units == 'mph':
projection='lcc', lat_1=33, lat_2=45, lon_0=-95) # draw state boundaries. # data from U.S Census Bureau # http://www.census.gov/geo/www/cob/st2000.html os.chdir("C:/Users/hespo/OneDrive/Documentos/GitHub/Trab2_DataScience") cwd = os.getcwd() print(cwd) pd.options.display.max_columns = 999 pd.options.display.max_rows = 999 shp_info = m.readshapefile( 'C:/Users/hespo/OneDrive/Documentos/GitHub/Trab2_DataScience/st99_d00', 'states', drawbounds=True) # population density by state from # http://en.wikipedia.org/wiki/List_of_U.S._states_by_population_density popdensity = { 'New Jersey': 438.00, 'Rhode Island': 387.35, 'Massachusetts': 312.68, 'Connecticut': 271.40, 'Maryland': 209.23, 'New York': 155.18, 'Delaware': 154.87, 'Florida': 114.43, 'Ohio': 107.05, 'Pennsylvania': 105.80, 'Illinois': 86.27,
#m = Basemap(projection='ortho',lat_0=lats.min(),lon_0=lons.min(), resolution='l') lon, lat =np.meshgrid(lons, lats) XX, YY=m(lon,lat) my_cmap = matplotlib.cm.get_cmap('rainbow') my_cmap.set_under('w') #cmap = cm.s3pcpn_l cmap = cm.StepSeq cmap = plt.get_cmap('gist_ncar') #norm = mpl.colors.Normalize(vmin=5, vmax=10) m.pcolormesh(XX,YY,tmp_day1,shading='flat', cmap=cmap, vmin=16, vmax=35); #m.drawcoastlines(linewidth=0.25) ; m.drawcountries(linewidth=0.25); m.drawstates(linewidth=0.25) m.readshapefile('subdiv/India_subdiv','ind',drawbounds=True, zorder=None, linewidth=1.0, color='k', antialiased=1, ax=None, default_encoding='utf-8') #m.drawmapboundary(fill_color='aqua') ; m.drawparallels(np.arange(0.,40.,10.), labels=[1,0,0,0]) m.drawmeridians(np.arange(60.,100.,10.), labels=[0,0,0,1]) m.drawlsmask(land_color='grey',ocean_color='aqua',lakes=True) cbar=m.colorbar(location='bottom', pad='5%') ; cbar.set_label('degC') ; #m.etopo() #m.drawlsmask(land_color='grey',ocean_color='aqua',lakes=True) m.fillcontinents(color='white',lake_color='white') plt.title('24 hour Sea Surface Temperature(degC)'); savefig('sst_philin.png', dpi=100); plt.close() ############################################################################################################# quit
def us_choropleth(t): import matplotlib.cm from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection from matplotlib.colors import Normalize import shapefile import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import numpy as np import random import pandas as pd from collections import Counter plt.title("NER", fontsize=12) us_locations_map = Basemap(resolution="l", llcrnrlon=-128.94, llcrnrlat=23.52, urcrnrlon=-60.12, urcrnrlat=50.93, lat_0=37.26, lon_0=-94.53) us_locations_map.drawmapboundary( fill_color="#46bcec") # Fills in the oceans us_locations_map.fillcontinents( color="#eabc77", lake_color="#46bcec") # Defines the continents us_locations_map.drawcoastlines() fig = matplotlib.pyplot.gcf() fig.set_size_inches(15.5, 12.5) # Sets the size of the map # Converts the coordinates to map points lons, lats = us_locations_map(t["longitude"], t["latitude"]) us_locations_map.scatter(lons, lats, color="black", zorder=10) # Draws the points on the map # Labels each point with the location name for i in range(t.num_rows): lat_lon = (t.row(i).item("longitude") + .2, t.row(i).item("latitude") - .1) plt.annotate(np.array(t.row(i).item("name")), lat_lon, fontsize=10) # Here we are reading in a shape file, which places state boundary # information for our Basemap us_locations_map.readshapefile("data/us_shapefiles/cb_2016_us_state_20m", "us_states") state_names = [] for shape_dict in us_locations_map.us_states_info: state_names.append(shape_dict['NAME']) ax = plt.gca() # get current axes instance cmap = plt.get_cmap('Reds') names = [] shapes = [] counts = [] state_counts = Counter(t["state"]) for index, state in enumerate(state_names): seg = us_locations_map.us_states[index] poly = Polygon(seg) names.append(state) shapes.append(poly) if state in t['state']: counts.append(state_counts[state]) else: counts.append(0) # Loading our lists into the DataFrame shape_table = pd.DataFrame() shape_table["State Name"] = np.array(names) shape_table["Shapes"] = np.array(shapes) shape_table["Count"] = np.array(counts) pc = PatchCollection(shape_table["Shapes"], zorder=2) norm = Normalize() pc.set_facecolor(cmap(norm(shape_table['Count'].fillna(0).values))) pc.set_edgecolor("black") ax.add_collection(pc) # Adds colorbar showing the scale mapper = matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap) mapper.set_array(shape_table['Count']) plt.colorbar(mapper, shrink=0.4)
def plot_2D_bval_grid(matfile, savefig=None, show=True): """ Take ZMAP generated bvalue workspace and plot 2-D geographic grid in python :param matfile: path to matlab .mat workspace :return: """ from mpl_toolkits.basemap import Basemap from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon # Establish figure and axes fig, ax = plt.subplots() workspace = loadmat(matfile) bval_grid = workspace['mBvalue'] bval_mask = np.ma.masked_invalid(bval_grid) lats = workspace['yvect'] lons = workspace['xvect'] x, y = np.meshgrid(lons, lats) ev_lons = workspace['a'][:, 0] ev_lats = workspace['a'][:, 1] mp = Basemap(projection='cyl', urcrnrlon=np.max(lons), urcrnrlat=np.max(lats), llcrnrlon=np.min(lons), llcrnrlat=np.min(lats), resolution='h', epsg=4326) mp.drawmapboundary(fill_color='white', zorder=-1) mp.fillcontinents(color='beige', lake_color='white', zorder=0) mp.drawcoastlines(color='0.6', linewidth=0.5) mp.drawcountries(color='0.6', linewidth=0.5) mp.pcolormesh(x, y, bval_mask, vmin=0.8, vmax=1.5, cmap='cool', edgecolor='0.6', linewidth=0, latlon=True) # Fixup grid spacing params meridians = np.arange((np.min(lons) + (np.max(lons) - np.min(lons)) * 0.1), np.max(lons), 0.1) parallels = np.arange((np.min(lats) + (np.max(lats) - np.min(lats)) * 0.1), np.max(lats), 0.1) mp.drawmeridians(meridians, fmt='%.2f', labelstyle='+/-', labels=[1, 0, 0, 1], linewidth=0., xoffset=2) mp.drawparallels(parallels, fmt='%.2f', labelstyle='+/-', labels=[1, 0, 0, 1], linewidth=0., yoffset=2) cbar = mp.colorbar() cbar.solids.set_edgecolor("face") cbar.set_label('b-value', rotation=270, labelpad=15) cbar.set_ticks(np.arange(0.8, 1.5, 0.1)) plt.title("B-value map") # Plot epicenters mp.plot(ev_lons, ev_lats, '.', color='k', markersize=1) # Shapefiles! # Wells mp.readshapefile('/home/chet/gmt/data/NZ/RK_tracks_injection', name='rki', color='blue', linewidth=1.) mp.readshapefile('/home/chet/gmt/data/NZ/NM_tracks_injection', name='nmi', color='blue', linewidth=1.) mp.readshapefile('/home/chet/gmt/data/NZ/NZ_faults_clipped', name='faults', color='k', linewidth=0.75) mp.readshapefile('/home/chet/gmt/data/NZ/NM_tracks_production_wgs84', name='nmp', color='firebrick', linewidth=1.) mp.readshapefile('/home/chet/gmt/data/NZ/RK_tracks_production', name='rkp', color='firebrick', linewidth=1.) # Water mp.readshapefile('/home/chet/gmt/data/NZ/taupo_lakes', name='lakes', color='steelblue', linewidth=0.2) mp.readshapefile('/home/chet/gmt/data/NZ/taupo_river_poly', name='rivers', color='steelblue', linewidth=0.2) # Bullshit filling part lakes = [] for info, shape in zip(mp.lakes_info, mp.lakes): lakes.append(Polygon(np.array(shape), True)) ax.add_collection( PatchCollection(lakes, facecolor='steelblue', edgecolor='steelblue', linewidths=0.2, zorder=2)) rivers = [] for info, shape in zip(mp.rivers_info, mp.rivers): rivers.append(Polygon(np.array(shape), True)) ax.add_collection( PatchCollection(rivers, facecolor='steelblue', edgecolor='steelblue', linewidths=0.2, zorder=2)) if show: fig.show() if savefig: fig.tight_layout() fig.savefig(savefig, dpi=720) return
def plot_distribution(): data = catch_distribution() font = FontProperties(fname=cur_dir + '/res/simsun.ttc') lat_min = 0 lat_max = 60 lon_min = 70 lon_max = 140 handles = [ matplotlib.patches.Patch(color='#ffaa85', alpha=1, linewidth=0), matplotlib.patches.Patch(color='#ff7b69', alpha=1, linewidth=0), matplotlib.patches.Patch(color='#bf2121', alpha=1, linewidth=0), matplotlib.patches.Patch(color='#7f1818', alpha=1, linewidth=0) ] labels = ['1-9', '10-99', '100-999', '>1000'] fig = matplotlib.figure.Figure() fig.set_size_inches(10, 8) axes = fig.add_axes([0.1, 0.12, 0.8, 0.8]) m = Basemap(llcrnrlon=lon_min, urcrnrlon=lon_max, llcrnrlat=lat_min, urcrnrlat=lat_max, resolution='l', ax=axes) m.readshapefile(cur_dir + '/res/china-shapefiles/china', 'province', drawbounds=True) m.readshapefile(cur_dir + '/res/china-shapefiles/china_nine_dotted_line', 'section', drawbounds=True) m.drawcoastlines(color='black') m.drawcountries(color='black') m.drawparallels(np.arange(lat_min, lat_max, 10), labels=[1, 0, 0, 1]) m.drawmeridians(np.arange(lon_min, lon_max, 10), labels=[0, 0, 0, 1]) for info, shape in zip(m.province_info, m.province): pname = info['OWNER'].strip('\x00') fcname = info['FCNAME'].strip('\x00') if pname != fcname: continue for key in data.keys(): if key in pname: if data[key] == 0: color = '#f0f0f0' elif data[key] < 10: color = '#ffaa85' elif data[key] < 100: color = '#ff7f69' elif data[key] < 1000: color = '#bf2121' else: color = '#7f1818' break poly = Polygon(shape, facecolor=color, edgecolor=color) axes.add_patch(poly) axes.legend(handles, labels, bbox_to_anchor=(0.5, -0.11), loc='lower center', ncol=4, prop=font) axes.set_title('map for 2019-nCov', fontproperties=font) FigureCanvasAgg(fig) fig.savefig(cur_dir + '/2019-nCov.png')
wget "https://github.com/matplotlib/basemap/blob/master/examples/st99_d00.dbf?raw=true" wget "https://github.com/matplotlib/basemap/blob/master/examples/st99_d00.shx?raw=true" The rename the files to get rid of the ?raw=true """ # Lambert Conformal map of lower 48 states. m = Basemap(llcrnrlon=-119, llcrnrlat=22, urcrnrlon=-64, urcrnrlat=49, projection='lcc', lat_1=33, lat_2=45, lon_0=-95) shp_info = m.readshapefile( 'st99_d00', 'states', drawbounds=True) # No extension specified in path here. pos_data = dict(zip(state_data.state, state_data.Positive)) neg_data = dict(zip(state_data.state, state_data.Negative)) # diff_data = dict(zip(state_data.state, state_data.diff)) # code for positive map pos_colors = {} statenames = [] pos_cmap = plt.cm.Greens # use 'hot' colormap vmin = 0.24 vmax = 0.28 for shapedict in m.states_info: statename = shapedict['NAME'] # skip DC and Puerto Rico. if statename not in ['District of Columbia', 'Puerto Rico']:
DPI = 150 ax = plt.figure(figsize=(2000 / float(DPI), 2000 / float(DPI)), frameon=True, dpi=DPI) # Plota os dados ======================================================================================= # Cria a referência basemap para a projeção retangular bmap = Basemap(llcrnrlon=extent[0], llcrnrlat=extent[1], urcrnrlon=extent[2], urcrnrlat=extent[3], epsg=4326) # Desenha os países e os estados brasileiros bmap.readshapefile('Shapefiles\\BRA_adm1', 'BRA_adm1', linewidth=0.50, color='cyan') bmap.readshapefile('Shapefiles\\ne_10m_admin_0_countries', 'ne_10m_admin_0_countries', linewidth=0.50, color='cyan') # Desenha os paralelos e meridianos bmap.drawparallels(np.arange(-90.0, 90.0, 2.5), linewidth=0.3, dashes=[4, 4], color='white', labels=[False, False, False, False], fmt='%g', labelstyle="+/-", xoffset=-0.80,
marker='o', lw=.25, facecolor='#33ccff', edgecolor='w', antialiased=True) m.scatter(gent_lons, gent_lats, alpha=0.6, marker='o', lw=.25, facecolor='#FF0000', edgecolor='r', antialiased=True) m.readshapefile('char_ct_shapefile', 'ctmap') fig.set_size_inches(10, 8) #plt.savefig('char_bizs.png', dpi=100, alpha=True) # In[10]: m.ctmap_info[3]['NAME'] # In[11]: map_points = pd.Series([ Point(m(mapped_x, mapped_y)) for mapped_x, mapped_y in zip(biz_lons, biz_lats) ])
color=color[ki], alpha=0.5) plt.xlabel('Lattitude') plt.ylabel('Longitude') plt.show() ##################################################### ## EXAMPLE of COLORING MUNICIPALITIES OF COLOMBIA ## ##################################################### # Generate the empty map of the area around Colombia map1 = Basemap(llcrnrlon=-65, llcrnrlat=-6, urcrnrlon=-80, urcrnrlat=15) # Load the shape files. map1.readshapefile('./Data/COL_adm2', name='municipalities', drawbounds=True) # The following checks the shapefile data and makes a list such that we can # reference each municipality by its index. Unfortunately, the shapefiles do NOT # have the actual municipality codes that everyone else uses -- they just have indices # from 1 to 1065. We have provided a csv file lookup table to convert back and forth # NOTE some lookups are missing. If you encounter one, then just leave that municipality uncolored mun_idx1 = [] for shape_dict in map1.municipalities_info: # We will be using the column ID_2 to reference municipalities (see in the shapefile csv) mun_idx1.append(shape_dict['ID_2']) # Read CSV to convert from shapefile ID's to municipality codes ("Cod.Municipio") codebook = pd.read_csv('./Data/COL_adm2_Conversion.csv', delimiter=',')
class GeoPlotter: """Class for plotting geographic objects using matplotlib. The class is largely a wrapper for basemap and associated functions.""" def __init__(self, **kwargs): """Creates the map. kwargs -- arguments to a Basemap object""" defaults = dict(projection='cyl', llcrnrlon=-180, llcrnrlat=-90, urcrnrlon=180, urcrnrlat=90, area_thresh=1000, resolution='c') defaults.update(kwargs) self.zorder = 0 self.m = Basemap(**defaults) # pylab.rc('lines', solid_capstyle='round', solid_joinstyle='bevel', dash_capstyle='round', dash_joinstyle='bevel') def getAxes(self): ax = self.m.ax if ax == None: return pylab.gca() return ax def getFigure(self): return self.getAxes().figure def setAxisSize(self, pos): """Mostly a wrapper for ax.set_position. Sets the size of the axis, relative to the total figure.""" self.getAxes().set_position(pos) def autoSizeAxes(self): xlength = float(self.m.urcrnrx - self.m.llcrnrx) ylength = float(self.m.urcrnry - self.m.llcrnry) maxlen = max(xlength, ylength) xlength = xlength / maxlen ylength = ylength / maxlen self.getAxes().figure.set_figheight(ylength * 10) self.getAxes().figure.set_figwidth(xlength * 10) self.setAxisSize([.05, .05, .9, .9]) def setZoom(self, llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, border=0): x1, y1 = self.m(llcrnrlon - border, llcrnrlat - border) x2, y2 = self.m(urcrnrlon + border, urcrnrlat + border) self.m.llcrnrlon = llcrnrlon - border self.m.llcrnrlat = llcrnrlat - border self.m.llcrnrx = x1 self.m.llcrnry = y1 self.m.urcrnrlon = urcrnrlon + border self.m.urcrnrlat = urcrnrlat + border self.m.urcrnrx = x2 self.m.urcrnry = y2 ax = self.getAxes() ax.set_ylim(y1, y2) ax.set_xlim(x1, x2) self.redraw() def redraw(self): self.getAxes().figure.canvas.draw() def clear(self): self.getAxes().clear() def savefig(self, *arg, **kwarg): """Wrapper for figure.savefig""" defaults = dict(facecolor='lightsteelblue', edgecolor='lightsteelblue') defaults.update(kwarg) self.getAxes().figure.savefig(*arg, **defaults) def _set_zorder(self, args): if 'zorder' not in args: args['zorder'] = self.zorder self.zorder += 1 else: self.zorder = max(self.zorder, args['zorder']) + 1 return args def _get_next_zorder(self): self.zorder += 1 return self.zorder - 1 def drawMapBoundary(self, **kwargs): """Largely a wrapper for Basemap.drawmapboundary. Provides some defaults""" defaults = dict(fill_color='lightsteelblue', linewidth=0) defaults.update(kwargs) defaults = self._set_zorder(defaults) self.m.drawmapboundary(**defaults) def drawCoastLines(self, **kwargs): """Largely a wrapper for Basemap.drawcoastlines. Provides some defaults""" defaults = dict(linewidth=0.5) defaults.update(kwargs) defaults = self._set_zorder(defaults) self.m.drawcoastlines(**defaults) def drawCountries(self, **kwargs): """Largely a wrapper for Basemap.drawcountries. Provides some defaults""" defaults = dict(linewidth=0.5) defaults.update(kwargs) defaults = self._set_zorder(defaults) self.m.drawcountries(**defaults) def drawStates(self, **kwargs): """Largely a wrapper for Basemap.drawstates. Provides some defaults""" defaults = dict(linewidth=0.5) defaults.update(kwargs) defaults = self._set_zorder(defaults) self.m.drawstates(**defaults) def drawWorld(self): """Draws oceans, continents, coastlines, countries, and states.""" self.drawMapBoundary() self.fillContinents() self.drawCoastLines(linewidth=0.7) self.drawCountries(linewidth=1.5) self.drawStates(linewidth=0.7) def drawParallels(self, **kwargs): """Largely a wrapper for Basemap.drawcoastlines. Provides some defaults""" defaults = dict(color='k') defaults.update(kwargs) defaults = self._set_zorder(defaults) self.m.drawparallels(**defaults) def drawMeridians(self, **kwargs): """Largely a wrapper for Basemap.drawcoastlines. Provides some defaults""" defaults = dict(color='k') defaults.update(kwargs) defaults = self._set_zorder(defaults) self.m.drawmeridians(**defaults) def setBBoxZoomShapefile(self, name, idxs, border_perc=0.1): """Set the zoom to a bounding box defined by the polygons in shapefile <name> and indices <idxs>. border_perc -- the percentage of space to leave for a border around the region""" shapes = [] for idx in idxs: shapes.append(getattr(self.m, name)[idx]) self.setBBoxZoom(shapes, border_perc=border_perc) def setBBoxZoom(self, shapes, border_perc=0.1): """Set the zoom to a bounding box defined by the shapes in <shapes>. shapes -- [ [(lat, lon)] ] border_perc -- the percentage of space to leave for a border around the region""" min_lat = scipy.inf max_lat = -scipy.inf min_lon = scipy.inf max_lon = -scipy.inf for sh in shapes: for lat, lon in sh: min_lat = min(lat, min_lat) min_lon = min(lon, min_lon) max_lat = max(lat, max_lat) max_lon = max(lon, max_lon) self.setZoom(min_lat, min_lon, max_lat, max_lon, border=border_perc * min(max_lat - min_lat, max_lon - min_lon)) def readShapefile(self, shapefileLoc, name): """shapefileLoc -- the location of the shapefile. For example 'world_borders/TM_WORLD_BORDERS-0.3.' expects the corresponding .shp .dbf etc files to be there name -- the shapefile will be stored in self.m.name and info in self.m.name_info You can then use that to plot polygons etc on the map""" self.m.readshapefile(shapefileLoc, name, drawbounds=False) def drawShapes(self, name, idxs, **kwargs): """Draw the shapes from shapefile <name> with indices <idxs> using the properties in <kwargs>""" defaults = dict(facecolor='orange', lw=0) defaults.update(kwargs) defaults = self._set_zorder(defaults) collection = [] for i in idxs: poly = matplotlib.patches.Polygon(getattr(self.m, name)[i]) collection.append(poly) collection = matplotlib.collections.PatchCollection( collection, **defaults) self.getAxes().add_collection(collection) def fillContinents(self, **kwargs): """Largely a wrapper for Basemap.fillcontinents. Provides some defaults""" defaults = dict(color=(0.94901960784313721, 0.93725490196078431, 0.97647058823529409), lake_color='lightsteelblue') defaults.update(kwargs) defaults = self._set_zorder(defaults) self.m.fillcontinents(**defaults) def drawPoints(self, lon, lat, **kwargs): """Largely a wrapper for Basemap.scatter. Provides some defaults""" defaults = dict(color='b', marker='o') defaults.update(kwargs) defaults = self._set_zorder(defaults) self.m.scatter(lon, lat, **defaults) def drawLines(self, lines, **kwargs): """Largely a wrapper for LineCollection. Draw lines on the map. lines -- a list of lines [ [(x1, y1), (x2, y2)], [(x1, y1), (x2, y2), (x3, y3)] ]""" defaults = dict(color='g') defaults.update(kwargs) defaults = self._set_zorder(defaults) lc = matplotlib.collections.LineCollection(lines, **defaults) # Getting the path to bevel this way is just too hard, and probably not worth it # Probably the right way to do it is make my own "beveled line collection" class. # Or maybe add a keyword attribute for "bevel" for each line? # if 'linewidth' in defaults: # newparams = defaults.copy() # del newparams['linewidth'] # newparams = self._set_zorder(newparams) # xs = [] # ys = [] # s = [] # for i, line in enumerate(lines): # for point in line: # xs.append(point[0]) # ys.append(point[1]) # s.append( (defaults['linewidth'][i] / 2.0)**2 * scipy.pi ) # self.drawPoints(xs, ys, s=s, **newparams) self.getAxes().add_collection(lc) def figureText(self, x, y, txt, **kwarg): """Largely a wrapper for axes.text. Provides some defaults""" self.getAxes().text(x, y, txt, **kwarg) def annotate(self, text, xy, **kwargs): """Largely a wrapper for axes.annotate. Provides some defaults""" defaults = dict(xycoords='data', xytext=(20, 20), textcoords='offset points', size=18, bbox=dict(boxstyle="round4,pad=.5", fc="0.9"), arrowprops=dict( arrowstyle="fancy", fc="0.6", connectionstyle="angle3,angleA=0,angleB=-90", edgecolor='black', linewidth=1)) if 'bbox' in kwargs: defaults['bbox'].update(kwargs['bbox']) del kwargs['bbox'] if 'arrowprops' in kwargs: defaults['arrowprops'].update(kwargs['arrowprops']) del kwargs['arrowprops'] defaults.update(kwargs) defaults = self._set_zorder(defaults) ax = self.getAxes() try: return ax.annotate(text, xy=xy, **defaults) except ValueError: defaults['arrowprops'] = dict( arrowstyle="->", connectionstyle="angle,angleA=0,angleB=-90,rad=10") return ax.annotate(text, xy=xy, **defaults) def _getNodeLonLat(self, node, node_data): if hasattr(node, 'lon'): lon = node.lon lat = node.lat elif 'lon' in node_data: lon = node_data['lon'] lat = node_data['lat'] elif 'Lon' in node_data: lon = node_data['Lon'] lat = node_data['Lat'] else: raise ValueError('Node does not have lat/lon specs %s' % repr(node)) return lon, lat def drawNetwork(self, net, greatCircle=False): """Draws a network on the map. net should have the following attributes: node_styles -- a dictionary of style dictionaries for nodes, including a 'default' edge_styles -- a dictionary of style dictionaries for edges, including a 'default' Each node/edge data dictionary has a 'style' entry that specifies the style to be looked up in node_styles/edge_styles. If no style is specified the default style is used. Only attributes of the default style are changed in plotting.""" # plot the edges edge_kwargs = {} default_style = net.edge_styles['default'] edge_options = default_style.keys() for name in edge_options: edge_kwargs[name] = [] lines = [] if 'bevel' in edge_options: bevel_lon = [] bevel_lat = [] bevel_kwargs = {} bevel_kwargs['s'] = [] for name in edge_options: bevel_kwargs[name] = [] del bevel_kwargs['bevel'] del edge_kwargs['bevel'] for node1, node2, edge_data in net.edges(data=True): new_line = [] new_line.append(self._getNodeLonLat(node1, net.node[node1])) new_line.append(self._getNodeLonLat(node2, net.node[node2])) lines.append(new_line) line_style = default_style.copy() if 'style' in edge_data: line_style.update(net.edge_styles.get(edge_data['style'], {})) line_style.update(edge_data) if 'bevel' in edge_options: if line_style['bevel']: bevel_lon.append(new_line[0][0]) bevel_lat.append(new_line[0][1]) bevel_lon.append(new_line[1][0]) bevel_lat.append(new_line[1][1]) bevel_kwargs['s'].append( (line_style['linewidth'] / 2.0)**2 * scipy.pi) bevel_kwargs['s'].append( (line_style['linewidth'] / 2.0)**2 * scipy.pi) for name in edge_options: if name == 'bevel': continue bevel_kwargs[name].append(line_style[name]) bevel_kwargs[name].append(line_style[name]) bevel_kwargs['linewidth'][-1] = 0 bevel_kwargs['linewidth'][-2] = 0 for name in edge_options: if name == 'bevel': continue edge_kwargs[name].append(line_style[name]) if not greatCircle: self.drawLines(lines, **edge_kwargs) else: i = 0 for i in range(len(lines)): lon1, lat1 = lines[i][0] lon2, lat2 = lines[i][1] kwargs = {} for name in edge_options: if name == 'bevel': continue kwargs[name] = edge_kwargs[name][i] kwargs = self._set_zorder(kwargs) self.m.drawgreatcircle(lon1, lat1, lon2, lat2, **kwargs) if 'bevel' in edge_options and len(bevel_lon) > 0: self.drawPoints(bevel_lon, bevel_lat, **bevel_kwargs) # plot the nodes node_kwargs = {} default_style = net.node_styles['default'] node_options = default_style.keys() for name in node_options: node_kwargs[name] = [] lon = [] lat = [] for node, node_data in net.nodes(data=True): node_lon, node_lat = self._getNodeLonLat(node, node_data) lon.append(node_lon) lat.append(node_lat) node_style = default_style.copy() if 'style' in node_data: node_style.update(net.node_styles.get(node_data['style'], {})) node_style.update(node_data) for name in node_options: node_kwargs[name].append(node_style[name]) lon = scipy.array(lon) lat = scipy.array(lat) if 'marker' not in node_options: node_kwargs = self._set_zorder(node_kwargs) self.drawPoints(lon, lat, **node_kwargs) else: # Have to plot each type of marker separately markers = scipy.array(node_kwargs['marker']) marker_types = scipy.unique(markers) del node_kwargs['marker'] for m in marker_types: idxs = scipy.where(markers == m)[0] tmp_node_kwargs = {} for k, v in node_kwargs.iteritems(): tmp_node_kwargs[k] = list(scipy.array(v)[idxs]) tmp_node_kwargs['marker'] = m tmp_node_kwargs = self._set_zorder(tmp_node_kwargs) self.drawPoints(lon[idxs], lat[idxs], **tmp_node_kwargs) min_lat = lat.min() max_lat = lat.max() lat_range = max_lat - min_lat min_lon = lon.min() max_lon = lon.max() lon_range = max_lon - min_lon self.setZoom(min_lon - .1 * lon_range, min_lat - .1 * lat_range, max_lon + .1 * lon_range, max_lat + .1 * lat_range)
lat[i, j] = sta_lat + ylocs[i][j] / dy dx = np.cos(np.deg2rad(lat[i][j])) * dy lon[i, j] = sta_lon + xlocs[i][j] / dx fig, ax = plt.subplots(figsize=(10, 10)) width = 2800 lon_0 = sta_lon lat_0 = sta_lat m = Basemap(width=width, height=width, projection='aeqd', lat_0=lat_0, lon_0=lon_0) m.readshapefile('C:\\dt\\county_2004', 'sf', color='w', linewidth=0.6) m.readshapefile('C:\\dt\\dijishi_2004', 'aa', drawbounds=False) for info, shape in zip(m.aa_info, m.aa): if info['LEVEL2_ID'] == 274: x, y = zip(*shape) m.plot(x, y, marker=None, color='red', linewidth=0.8) v_cmap, v_norm = v_color_PUP() lons, lats = m(lon, lat) m.pcolormesh(lons, lats, data_rf, cmap=v_cmap, norm=v_norm) #画距离折叠 cf1 = m.pcolormesh(lons, lats, data, cmap=v_cmap, norm=v_norm) #画速度 for cir in [25, 50, 75, 100, 115]: #画等距离圈 cir_lon = lon[:, np.where(rng == cir)].flatten() cir_lat = lat[:, np.where(rng == cir)].flatten() cir_lon, cir_lat = m(cir_lon, cir_lat)
# cbar = m.colorbar(im,location='bottom',pad="5%") # cbar.set_label('m') # # # cs = m.contour(x,y,topo_val, levels = clevs, colors='0.4', linewidths=0.5) # m.drawmapscale(-46.22, -22.89, -46.22, -22.89,1000, barstyle='fancy',fontsize=10,units='m') # cbar.add_lines(cs) # shapefile='/home/thomas/PhD/obs-lcb/staClim/box/loc_sta/transect_peg_svg/limite_estudo' # m.readshapefile(shapefile, 'limite_estudo', drawbounds=True, linewidth=3, color='0.4') shapefile = '/home/thomas/PhD/obs-lcb/staClim/box/loc_sta/transect_peg_svg/Grande_transecto' m.readshapefile(shapefile, 'Grande_transecto', drawbounds=True, linewidth=3, color='0.4') shapefile = '/home/thomas/PhD/obs-lcb/staClim/box/loc_sta/shapefile_posses/basin' m.readshapefile(shapefile, 'basin', drawbounds=True, linewidth=3, color='0.4') shapefile = '/home/thomas/PhD/obs-lcb/staClim/box/loc_sta/shapefile_brasil_python/BRA_adm1' m.readshapefile(shapefile, 'BRA_adm1', drawbounds=True) AttSta = att_sta( Path_att="/home/thomas/PhD/obs-lcb/staClim/metadata_allnet_select.csv") stanames = AttSta.get_sta_id_in_metadata(all=True) # print stanames.tolist()
os.mkdir(local_folder) for fname in filelist: f_path = os.path.join(local_folder, fname) remote_f_path = os.path.join(remote_folder, fname) #download selected files download_link(remote_f_path, f_path) # <markdowncell> # # Basemap: reading and visualizing shape files # <codecell> bworld = Basemap() shp_file = os.path.join(local_folder, "cntry00") ncountries, _, _, _, linecollection = bworld.readshapefile(shp_file, "country") # <markdowncell> # Reading country polygons (and attributes) from the shape file, necessary imports # ===== # <codecell> import fiona from matplotlib.collections import PatchCollection from shapely.geometry import MultiPolygon, shape from matplotlib.patches import Polygon import shapely import matplotlib.cm as cm
# http://www.gadm.org/country Joao do futuro, lebrar desse site basepath = os.path.abspath(os.path.dirname(__file__)) shapefile = ''.join([basepath, '/mapas/BRA_adm1']) fig, ax = plt.subplots() m = Basemap(projection='merc', llcrnrlat=-35, urcrnrlat=7, llcrnrlon=-77, urcrnrlon=-32, resolution='i') m.ax = ax m.fillcontinents() shp = m.readshapefile(shapefile, 'states', drawbounds=True) for nshape, seg in enumerate(m.states): poly = Polygon(seg, facecolor='0.75', edgecolor='k') ax.add_patch(poly) lats = np.array([-21.2525, -4.8361, -22.725, -24.04309, -14.4041, -22.305, -9.6663, -22.1211, -17.7927, -19.7474]) lons = np.array([-48.3257, -37.7815, -47.6476, -52.37929, -56.4371, -53.8189, -35.7351, -51.393, -50.9197, -47.9392]) x, y = m(lons, lats)
resolution='l', projection='merc', #coordinates of the corners - lower left lat/lon and upper right lat/lon llcrnrlat=57.4, llcrnrlon=21.5, urcrnrlat=59.8, urcrnrlon=28.7) #fill in the background m.drawmapboundary(fill_color='#1c1c1c') m.fillcontinents(color='#1c1c1c', lake_color='#1c1c1c') #I downloaded the .shp.zip archive for Estonia from http://download.geofabrik.de/ #and placed the files in a subfolder "geo" m.readshapefile('geo/gis_osm_water_a_free_1', 'waterways', drawbounds=False, color='#1c1c1c') #Determine polygons to fill in (in this case they will be lakes, rivers, etc) patches = [] for info, shape in zip(m.waterways_info, m.waterways): patches.append(Polygon(np.array(shape), True)) #fill in the polygons ax.add_collection( PatchCollection(patches, facecolor='#5f8999', edgecolor='#5f8999', linewidths=1., zorder=2)) plt.savefig('Estonia_bodies_of_water')
initial_data = pd.read_csv('sample.csv') columns = initial_data.columns fig, ax = plt.subplots() # 创建图形对象 m = Basemap(llcrnrlon=77, llcrnrlat=14, urcrnrlon=140, urcrnrlat=51, projection='lcc', lat_1=33, lat_2=45, lon_0=100) # 读取shapefile m.readshapefile('gadm36_CHN_shp/gadm36_CHN_0', 'china', drawbounds=True, linewidth=0.5) m.readshapefile('gadm36_CHN_shp/gadm36_CHN_1', 'provinces', drawbounds=True, linewidth=0.5) m.readshapefile('gadm36_CHN_shp/gadm36_CHN_2', 'cities', drawbounds=True, linewidth=0.1) m.readshapefile('gadm36_TWN_shp/gadm36_TWN_0', 'taiwan', drawbounds=True, linewidth=0.5) m.readshapefile('gadm36_TWN_shp/gadm36_TWN_1', 'taiwancity',
fig = plt.figure(figsize=(8, 8)) ax1 = fig.add_subplot(211) #map = Basemap(projection ='cyl', llcrnrlat=-15, urcrnrlat=40,llcrnrlon=55, urcrnrlon=145, resolution='c') map = Basemap(llcrnrlon=-121, llcrnrlat=20, urcrnrlon=-62, urcrnrlat=51, projection='lcc', lat_1=32, lat_2=45, lon_0=-95) # load the shapefile, use the name 'states' map.readshapefile('usshape/cb_2017_us_state_5m', name='states', drawbounds=True) lon1, lat1 = N.meshgrid(lona1, lata) x, y = map(lon1, lat1) j = 1988 - 1979 fc, lona1 = shiftgrid(180.5, mai[j, :, :], lona, start=False) aa = (fc - mai_avg) / mai_avg * 100 aa[N.isnan(aa)] = 0 aa[N.isinf(aa)] = 0 aa = ma.masked_where(aa == 0.0, aa) map.drawcoastlines() map.drawcountries()
ax.set_title(title_04) m = Basemap(projection='merc', epsg=cs2cs_args.split(':')[1], llcrnrlon=np.min(glon_04) - 0.0004, llcrnrlat=np.min(glat_04) - 0.0006, urcrnrlon=np.max(glon_04) + 0.0006, urcrnrlat=np.max(glat_04) + 0.0009) x, y = m.projtran(glon_04, glat_04) m.wmsimage(server=wms_url, layers=['3'], xpixels=1000) im = m.contourf(x, y, data_04.T, cmap=c_ramp) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbr = plt.colorbar(im, cax=cax) cbr.set_label(cbr_txt, size=10) #read shapefile and create polygon collections m.readshapefile(geo_shp_04, "layer", drawbounds=False) #sand, gravel, boulders s_patch, g_patch, b_patch = [], [], [] for info, shape in zip(m.layer_info, m.layer): if info['substrate'] == 'sand': s_patch.append(Polygon(np.asarray(shape), True)) if info['substrate'] == 'gravel': g_patch.append(Polygon(np.asarray(shape), True)) if info['substrate'] == 'boulders': b_patch.append(Polygon(np.asarray(shape), True)) del info, shape ax.add_collection( PatchCollection(s_patch,
def plot_map(mobile,other_mobile=False,auto_map_boundaries=True,background='WRF'): print "--plot map--" """ makes a map of the helicopter observations. Also plots MesoWest input: mobile=ksl observations from the get moblie function other_mobile: if set to true will plot truck and trax data if available auto_map_boundaries: will find the location of the helicopter and will set auto boundaries else, will map the salt lake valley or you can change the lat/lon manually background: 'WRF' will use a wrf file to contour the boundary 'sat' will use an old satellite image 'topo' will use a topographical image """ plt.cla() plt.clf() plt.close() width=4 height=4.5 fig, (ax1) = plt.subplots(1,1,figsize=(width,height)) ## ---- Draw map top_right_lat = 40.9+.1 top_right_lon = -111.60 bot_left_lat = 40.4+.05 bot_left_lon = -112.19785-.05 ## Map in cylindrical projection (data points may apear skewed) m = Basemap(resolution='i',projection='cyl',\ llcrnrlon=bot_left_lon,llcrnrlat=bot_left_lat,\ urcrnrlon=top_right_lon,urcrnrlat=top_right_lat,) # -----Set Background images if background == 'WRF': ## ---- Grab terrain data directory = '/uufs/chpc.utah.edu/common/home/horel-group4/model/bblaylock/WRF3.7_spinup/DATA/FULL_RUN_June14-19/' spat = 'auxhist23_d02_2015-06-14_00:00:00' nc_spatial = netcdf.netcdf_file(directory+spat,'r') # This sets the standard grid point structure at full resolution # Converts WRF lat and long to the maps x an y coordinate XLONG = nc_spatial.variables['XLONG'][0] XLAT = nc_spatial.variables['XLAT'][0] HGT = nc_spatial.variables['HGT'][0,:,:] #topography landmask = nc_spatial.variables['LANDMASK'][0,:,:] # Plot Terrain X,Y = m(XLONG,XLAT) plt.contourf(X,Y,HGT,levels=np.arange(1000,4000,500),cmap='binary') # Draw major roads from shapefile m.readshapefile('/uufs/chpc.utah.edu/common/home/u0553130/shape_files/tl_2015_UtahRoads_prisecroads/tl_2015_49_prisecroads','roads', linewidth=.2) ## Contour Lake Outline plt.contour(X,Y,landmask, [0,1], linewidths=1, colors="b") maps = [ 'ESRI_Imagery_World_2D', # 0 'ESRI_StreetMap_World_2D', # 1 'NatGeo_World_Map', # 2 'NGS_Topo_US_2D', # 3 'Ocean_Basemap', # 4 'USA_Topo_Maps', # 5 'World_Imagery', # 6 'World_Physical_Map', # 7 'World_Shaded_Relief', # 8 'World_Street_Map', # 9 'World_Terrain_Base', # 10 'World_Topo_Map' # 11 ] if background == 'sat': ## Instead of using WRF terrain fields you can get a high resolution image from ESRI m.arcgisimage(service=maps[0], xpixels = 3000, verbose= True) if background == 'topo': ## Instead of using WRF terrain fields you can get a high resolution image from ESRI m.arcgisimage(service=maps[8], xpixels = 3000, verbose= True) # Draw major roads from shapefile m.readshapefile('/uufs/chpc.utah.edu/common/home/u0553130/shape_files/tl_2015_UtahRoads_prisecroads/tl_2015_49_prisecroads','roads', linewidth=.2) # can use any other map background from maps list # Plot Mobile Ozone points (KSL) x,y = m(mobile['longitude'],mobile['latitude']) # plot every 30 seconds rather than every 10 seconds (thus the [::3] indexes) m.scatter(x[::3],y[::3],c=ksl_mobile['ozone'][::3],vmax=80,vmin=45.,lw = .3,s=30,cmap=plt.cm.get_cmap('jet'),zorder=50) cbar = plt.colorbar(orientation='horizontal',extend='both',shrink=.8,pad=.03) cbar.ax.set_xlabel('Ozone Concentration (ppb)',fontsize=10) cbar.ax.tick_params(labelsize=8) cbar.set_ticks([45,50,55,60,65,70,75,80,85]) # Plot Other Mobile data if other_mobile == True: # Plot Mobile Ozone points (TRAX01) try: x,y = m(trax_mobile['longitude'],trax_mobile['latitude']) m.scatter(x[:],y[:],c=trax_mobile['ozone'][:],vmax=80,vmin=45.,lw = .3,marker='d',s=30,cmap=plt.cm.get_cmap('jet'),zorder=50) except: print 'no TRAX01 data' # Plot Mobile Truck points (UUTK3) try: x,y = m(trk3_mobile['longitude'],trk3_mobile['latitude']) m.scatter(x[:],y[:],c=trk3_mobile['ozone'][:],vmax=80,vmin=45.,lw = .3,marker='p',s=30,cmap=plt.cm.get_cmap('jet'),zorder=50) except: print 'no UUTK3 data' # Plot Mobile Truck points (UUTK1) try: x,y = m(trk1_mobile['longitude'],trk1_mobile['latitude']) m.scatter(x[:],y[:],c=trk1_mobile['ozone'][:],vmax=80,vmin=45.,lw = .3,marker='p',s=30,cmap=plt.cm.get_cmap('jet'),zorder=50) except: print 'no UUTK1 data' ## Plot MesoWest (top of the hour, +/- 10 mins) # Plot MesoWest wind data mesowest_time = str(request_time.year).zfill(2)+str(request_time.month).zfill(2)+str(request_time.day).zfill(2)+str(request_time.hour).zfill(2)+'00' print 'plotting mesowest observations within 10 minutes of top of the hour',mesowest_time a = get_mesowest_radius_winds(mesowest_time,'10') u,v = wind_spddir_to_uv(a['WIND_SPEED'],a['WIND_DIR']) m.barbs(a['LON'],a['LAT'],u,v, length=4.5, linewidth=.5, barb_increments=dict(half=1, full=2, flag=10), sizes=dict(spacing=0.15, height=0.3, emptybarb=.1)) # ozone m.scatter(a['LON'],a['LAT'],c=a['OZONE'],vmax=80,vmin=45.,lw =.3,s=20, marker='s',cmap=plt.cm.get_cmap('jet'),zorder=50) # Manually plot other Sensor locations by lat/lon """ m.scatter(-111.93,40.9669, s=75, c='w',zorder=40) m.scatter(-112.01448,40.71152, s=75, c='b',zorder=40) # NAA m.scatter(-111.93072,40.95733, s=75, c='darkorange',zorder=40) # O3S02 m.scatter(-111.828211,40.766573, s=75, c='r',zorder=40) # MTMET m.scatter(-111.8717,40.7335, s=75, c='darkgreen',zorder=40) # QHW m.scatter(-111.96503,40.77069, s=75, c='w',zorder=40) # SLC m.scatter(-112.34551,40.89068 , s=75, c='w',zorder=40) # GSLBY """ plt.savefig(FIGDIR+string_time+'_map.png',dpi=500,bbox_inches="tight") print 'saved map' print ""
from matplotlib.collections import PatchCollection import numpy as np # set width, height, and DPI (w, h) = (6.5, 4.5) dpi = 150 # Create the figure fig = plt.figure(1, (w, h), dpi=dpi) ax = fig.add_axes([0, 0, 1, 1]) # Read shapefiles (note that only the line properties can be set here) # use drawbounds=True for shapefiles that should be plotted directly (counties and districts) m.readshapefile('shapefiles/counties_ia', 'county', drawbounds=True, linewidth=0.5, color='0.8', zorder=1) m.readshapefile('shapefiles/usda_districts_ia', 'usda_districts', drawbounds=True, linewidth=2, zorder=3) m.readshapefile('shapefiles/smos_pixels', 'smos_pixels', drawbounds=False) # create a PatchCollection from the SMOS pixels so we can fill them patches = [] for info, shape in zip(m.smos_pixels_info, m.smos_pixels): patches.append(Polygon(np.array(shape), True))
'coordinates': [(node.lon, node.lat) for node in way.nodes] } prop = { 'Name': way.tags.get("name", "n/a"), 'Type': way.tags.get("highway", "n/a") } output.write({'geometry': line, 'properties': prop}) # Dessiner la carte! m = Basemap(projection='tmerc', resolution='f', llcrnrlon=west, llcrnrlat=south, urcrnrlon=east, urcrnrlat=north, lon_0=(east + west) / 2, lat_0=(north + south) / 2) plt.close() fig = plt.figure(figsize=(24.25, 18.25), dpi=300) rect = [0.015, 0.033, 0.97, 0.934] ax = fig.add_axes(rect) m.drawmapboundary(fill_color='#E1E1E1', linewidth=0) m.drawcoastlines(linewidth=0.5, color="#E1E1E1") m.fillcontinents(color="#FFFFFF") m.readshapefile('bretagne_road', 'roads', linewidth=0.45, color="#A0A0A0") m.readshapefile('bretagne_highway', 'highway', linewidth=0.6, color="#202020") m.readshapefile('bretagne_links', 'highway', linewidth=0.3, color="#202020") fig.savefig(os.path.join(wd_output, 'bretagne.pdf'), dpi=300) # fig.savefig(os.path.join(wd_output, 'bretagne.eps'), dpi=300)
x, y = m(lons, lats) #u = np.array(datanumu) #v = np.array(datanumv) #speed = np.sqrt(u*u + v*v) #u = np.ma.masked_where(speed<8,u) #v = np.ma.masked_where(speed<8,v) bondl = 0 bondr = 145 bondu = 73 #m.quiver(x[:bondu,bondl:bondr], y[:bondu,bondl:bondr], u[:bondu,bondl:bondr], v[:bondu,bondl:bondr],speed[:bondu,bondl:bondr], # cmap = 'gray', pivot='mid', scale=1000, zorder = 3) ##shapefile## shapefile = path + '\\map\\CHN_adm0' m.readshapefile(shapefile, 'bbb', drawbounds=False, color='red', linewidth=0.5) #print type(m.bbb_info[0]) patches = [] for info, shape in zip(m.bbb_info, m.bbb): if info['SOVEREIGN'] in ['China', 'Taiwan']: patches.append(Polygon(np.array(shape), True)) ax.add_collection( PatchCollection(patches, facecolor='k', edgecolor='white', linewidths=0.5, zorder=1)) ##draw the province boundaries## shapefilep = path + '\\map\\' + 'CHN_adm1'
def mapasExtremos(fp): """ Función que permite generar los mapas de eventos extremos """ # ********** fecha pronóstico fechaPronostico = fp # fechaPronostico = strftime("%Y-%m-%d") # ********** path # path server # path = "/home/jorge/Documents/work/autoPronosticoSonora" # os.chdir(path) # path local # ********* Lat y Long LONG_MAX = -86.1010 LONG_MIN = -118.2360 LAT_MAX = 33.5791 LAT_MIN = 12.37 # ********** Path path = "/Users/jorgemauricio/Documents/Research/alermapweb" os.chdir(path) # ********** dict de análisis d = {"Rain" : ['20/50', '50/70', '70/150', '150/300', '300/500'], "Tmax":['30/35', '35/40', '40/45', '45/50', '50/60'], "Tmin" : ['-9/-6','-6/-3','-3/0','0/3','3/6'], "Windpro" : ['62/74', '75/88', '89/102', '103/117', '118/150']} # ********** array colores # generar fechas mediante función arrayFechas = generarFechas(fechaPronostico) # leer csv for j in range(1, 6, 1): pathFile = '{}/data/{}/d{}.txt'.format(path,fechaPronostico,j) data = pd.read_table(pathFile, sep=',') for key, value in d.items(): for i in value: # comenzar con el proceso tiempoInicio = strftime("%Y-%m-%d %H:%M:%S") print("Empezar procesamiento {} {} tiempo: {}".format(key, i, tiempoInicio)) # obtener rangos vMin, vMax = i.split('/') vMin = int(vMin) vMax = int(vMax) # título temporal de la columna a procesar tituloTemporalColumna = key dataTemp = data.loc[(data[tituloTemporalColumna] >= vMin) & (data[tituloTemporalColumna] <= vMax)] #obtener valores de x y y lons = np.array(dataTemp['Long']) lats = np.array(dataTemp['Lat']) #%% set up plot plt.clf() fig = plt.figure(figsize=(8,4)) m = Basemap(projection='mill',llcrnrlat=LAT_MIN,urcrnrlat=LAT_MAX,llcrnrlon=LONG_MIN,urcrnrlon=LONG_MAX,resolution='h') # generar xp xp = np.array(dataTemp['Long']) # generar yp yp = np.array(dataTemp['Lat']) # leer archivo shape Estados m.readshapefile('shapes/Estados', 'Estados') # agregar raster # m.bluemarble() # gráficar puntos colorTemporalDelPunto = colorPuntoEnMapa(key, i) m.scatter(xp, yp, latlon=True, s=3, marker='o', color=colorTemporalDelPunto, zorder=25, alpha=0.5) # titulo del mapa tituloTemporalMapa = generarTexto(arrayFechas[j-1], key, vMin, vMax) plt.title(tituloTemporalMapa) tituloTemporalArchivo = "{}/data/{}/{}_{}_{}_{}.png".format(path,fechaPronostico,arrayFechas[j-1],key,vMin, vMax) # crear anotación latitudAnotacion = (LAT_MAX + LAT_MIN) / 2 longitudAnotacion = (LONG_MAX + LONG_MIN) / 2 plt.annotate('@2018 INIFAP', xy=(longitudAnotacion,latitudAnotacion), xycoords='figure fraction', xytext=(0.45,0.45), color='g') # guardar mapa plt.savefig(tituloTemporalArchivo, dpi=300) print('****** Genereate: {}'.format(tituloTemporalArchivo)) # finalizar con el proceso tiempoFinal = strftime("%Y-%m-%d %H:%M:%S") print("Terminar procesamiento {} {} tiempo: {}".format(key, i, tiempoInicio))
m = Basemap(resolution='i',projection='cyl',\ llcrnrlon=bot_left_lon,llcrnrlat=bot_left_lat,\ urcrnrlon=top_right_lon,urcrnrlat=top_right_lat,) m.drawcoastlines() m.drawcountries() m.drawcounties(linewidth=2) m.drawstates(linewidth=5) # Brackground image m.arcgisimage(service='NatGeo_World_Map', xpixels=1200, dpi=1000, verbose=True) ############################################################################### # Fire perimiter perimiter = '160816' p4 = m.readshapefile( '/uufs/chpc.utah.edu/common/home/u0553130/fire_shape/perim_' + perimiter, 'perim', drawbounds=False) patches = [] for info, shape in zip(m.perim_info, m.perim): #if info['FIRENAME'] == 'PIONEER' and info['SHAPENUM']==1772: if info['FIRENAME'] == 'PIONEER' and info['PERDATTIME'] == [ 2016, 8, 6 ] and np.shape(shape)[0] > 6000 and info['SHAPENUM'] == 1914: x, y = zip(*shape) print info['FIRENAME'], info['SHAPENUM'], info['PERDATTIME'], info[ 'DATECRNT'] print 'GIS Acres', info['GISACRES'] #m.plot(x, y, marker=None,color=colors[colorI],linewidth=lw) patches.append(Polygon(np.array(shape), True)) print ""
normsst = colors.Normalize(vmin=sstmin, vmax=sstmax) boundsst = np.arange(sstmin, sstmax + .1, 2.5) level2plotsst = np.arange(10, sstmax + .1, 0.01) lon_interp, lat_interp = np.meshgrid(np.arange(-180, 180.), np.arange(-80, 80.)) yearlist = (2014, 2015) monthlist = range(1, 13) if doplot: fig = plt.figure(figsize=(12, 8)) plt.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.00) m = Basemap(projection='robin', lon_0=0, resolution='c') shp_info = m.readshapefile(landfile, 'scalerank', drawbounds=True) ax = plt.gca() ax.cla() paths = [] for line in shp_info[4]._paths: paths.append(Path(line.vertices, codes=line.codes)) coll = PathCollection(paths, linewidths=0, facecolors='grey', zorder=2) m = Basemap(projection='robin', lon_0=0, resolution='c') # drawing something seems necessary to 'initiate' the map properly m.drawcoastlines(color='white', zorder=0) ax = plt.gca() ax.add_collection(coll)
# Define the size of the saved picture================================================================= #print (data.shape) DPI = 150 fig = plt.figure(figsize=(data.shape[1]/float(DPI), data.shape[0]/float(DPI)), frameon=False, dpi=DPI) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ax = plt.axis('off') #====================================================================================================== # Plot the Data ======================================================================================= # Create the basemap reference for the Rectangular Projection bmap = Basemap(llcrnrlon=extent[0], llcrnrlat=extent[1], urcrnrlon=extent[2], urcrnrlat=extent[3], epsg=4326) # Draw the countries and Brazilian states shapefiles if Band == 2: bmap.readshapefile('/dados/backup_homefazzt/download/ne_10m_admin_0_countries','ne_10m_admin_0_countries',linewidth=0.50,color='#FFFFFF') bmap.readshapefile('/dados/backup_homefazzt/download/shape/Brasil_com_estados','estados_2010',linewidth=0.40,color='#FFFFFF') else: bmap.readshapefile('/dados/backup_homefazzt/download/ne_10m_admin_0_countries','ne_10m_admin_0_countries',linewidth=0.50,color='#000000') bmap.readshapefile('/dados/backup_homefazzt/download/shape/Brasil_com_estados','estados_2010',linewidth=0.40,color='#000000') #Sahpes - Furnas: bmap.readshapefile('/dados/backup_homefazzt/download/KML_to_shape/138kV_2D','138kV',linewidth=1.0,color='#FF0000') bmap.readshapefile('/dados/backup_homefazzt/download/KML_to_shape/230kV_2D','230kV',linewidth=1.0,color='#00FF09') bmap.readshapefile('/dados/backup_homefazzt/download/KML_to_shape/345kV_2D','345kV',linewidth=1.0,color='#FFC400') bmap.readshapefile('/dados/backup_homefazzt/download/KML_to_shape/500kV_2D','500kV',linewidth=1.0,color='#001AFF') bmap.readshapefile('/dados/backup_homefazzt/download/KML_to_shape/600kV_2D','600kV',linewidth=1.0,color='#FF00EF') bmap.readshapefile('/dados/backup_homefazzt/download/KML_to_shape/750kV_2D','750kV',linewidth=1.0,color='#00FFFF')
def Chinese_Map_Drawer(colortype): ''' ''' fig = plt.figure() ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) map = Basemap( projection='mill', llcrnrlat=14, # left corner latitude llcrnrlon=72, # left corner longitude urcrnrlat=55, # right corner latitude urcrnrlon=137, # right corner longitude resolution='h', area_thresh=10000) # map.drawmapboundary(fill_color='aqua') # foreground color map.readshapefile('./gadm36_CHN_shp/gadm36_CHN_1/gadm36_CHN_1', 'NAME_1', drawbounds=True) # mainland China map.drawcountries(linewidth=1.5) map.drawmapboundary() font1 = {'family': 'courier_new', 'weight': 'normal', 'size': 10} # labels = [left,right,top,bottom] map.drawmeridians(np.arange(0, 360, 15), labels=[0, 1, 1, 0]) # 绘制经线 map.drawparallels(np.arange(-90, 90, 15), labels=[0, 1, 1, 0]) # 绘制纬线 df = pd.read_csv('./ChineseMapDrawer/CHN_POP_CASE.csv', encoding='gbk') new_index_list = [] for i in df["NAME_1"]: i = i.replace(" ", "") new_index_list.append(i) new_index = {"regions": new_index_list} new_index = pd.DataFrame(new_index) df = pd.concat([df, new_index], axis=1) df = df.drop(["NAME_1"], axis=1) df.set_index("regions", inplace=True) provinces = map.NAME_1_info statenames = [] colors = {} if colortype == 'YlGn_r': cmap = plt.cm.YlGn_r elif colortype == 'YlGn': cmap = plt.cm.YlGn elif colortype == 'mono': cmap = plt.cm.Greys vmax = 30 vmin = 0 for s in df.index: statenames.append(s) CPM = df['CPM'][s] #get case per million colors[s] = cmap(1 - np.sqrt((CPM - vmin) / (vmax - vmin)))[:3] ax = plt.gca() for nshape, seg in enumerate(map.NAME_1): color = rgb2hex(colors[statenames[nshape]]) poly = Polygon(seg, facecolor=color, edgecolor=color) ax.add_patch(poly) #plt.show() def draw_scatter_map(map, lon, lat, label, save=False, save_format='.svg'): value = np.array(df['cases'], dtype=float) size = (value / np.mean(value)) * 65 x, y = map(lon, lat) map.scatter(x, y, s=size, c='r', alpha=0.7, zorder=10) ax.set_xlabel(label, font1) if save: fig.savefig(label + save_format) plt.show() lon = np.array(df['lon']) lat = np.array(df['lat']) draw_scatter_map(map, lon, lat, "\nCovid-19 cases distribution in Mainland China", save=True, save_format='.png')