def run(FILE_NAME): with h5py.File(FILE_NAME, mode="r") as f: name = "/S1/surfacePrecipitation" data = f[name][:] units = f[name].attrs["Units"] # The attribute says -9999.900391 but data uses -9999.0. # _FillValue = f[name].attrs['CodeMissingValue'] _FillValue = -9999.0 data[data == _FillValue] = np.nan data = np.ma.masked_where(np.isnan(data), data) # Get the geolocation data latitude = f["/S1/Latitude"][:] longitude = f["/S1/Longitude"][:] m = Basemap(projection="cyl", resolution="l", llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180) m.drawcoastlines(linewidth=0.5) m.drawparallels(np.arange(-90, 91, 45)) m.drawmeridians(np.arange(-180, 180, 45), labels=[True, False, False, True]) m.scatter(longitude, latitude, c=data, s=1, cmap=plt.cm.jet, edgecolors=None, linewidth=0) cb = m.colorbar(location="bottom", pad="10%") cb.set_label(units) basename = os.path.basename(FILE_NAME) plt.title("{0}\n{1}".format(basename, name)) fig = plt.gcf() # plt.show() pngfile = "{0}.py.png".format(basename) fig.savefig(pngfile)
def make_stations(network,latmin,latmax,lonmin,lonmax,dlat,dlon,plot=True,**kwargs): head = kwargs.get('head','RM') elev = kwargs.get('elev',0) dep = kwargs.get('dep',0) lats = np.arange(latmin,latmax+dlat,dlat) lons = np.arange(lonmin,lonmax+dlon,dlon) lats_pts,lons_pts = np.meshgrid(lats,lons) if plot: m = Basemap(projection='hammer',lon_0=0,resolution='l') m.drawcoastlines() m.drawmeridians(np.arange(0,351,10)) m.drawparallels(np.arange(-80,81,10)) lons_pts2,lats_pts2 = m(lons_pts,lats_pts) m.scatter(lons_pts2,lats_pts2) plt.show() f = open('STATIONS','w') print 'total number of stations : ',len(lats_pts) st = 1 for i in range(0,len(lats)): for j in range(0,len(lons)): f.write('{}{:04d} {} {:5.2f} {:5.2f} {:5.2f} {:5.2f}'.format(head,st,network,lats[i],lons[j],elev,dep)+'\n') st += 1
def plot(text, size): from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt # setup Lambert Conformal basemap. m = Basemap(width=3000000,height=3000000,projection='lcc', resolution='c',lat_0=18,lon_0=78) m.drawcoastlines() #m.fillcontinents(color='coral',lake_color='aqua') m.shadedrelief() colors = numpy.random.rand(30,3) lat = [17.38,13.08,12.98,19.07,22.57,26.84,26.91,28.63] lon = [78.49,80.28,77.61,72.88,88.34,80.95,75.78,77.25] df_x = [0.5,0,0.5] df_y = [-0.5,0,-0.5] f_lat = [] f_lon = [] f_size = [] f_color = [] for place_id in range(len(lat)): for i in range(3): f_lat.append(lat[place_id] + df_y[i]) f_lon.append(lon[place_id] + df_x[i]) f_size.append(size[place_id][i]*500) f_color.append(colors[text[place_id][i]]) #m.plot(lon[place_id]+df_y[i],lat[place_id]+ df_x[i], 'bo',markersize = size[place_id][i], latlon = True) m.scatter(f_lon, f_lat, s = f_size, c = f_color, alpha = 0.5, latlon = True) m.scatter(lon, lat, s = 8000, c = 'b', alpha = 0.2, latlon = True) #m.scatter(f_lon, f_lat, s = f_size, c = f_color, latlon = True) #m.plot(f_lon,f_lat,'bo',markersize = 5, latlon = True) plt.show()
def run(FILE_NAME): with h5py.File(FILE_NAME, mode='r') as f: name = '/HDFEOS/SWATHS/O3NadirSwath/Data Fields/O3' data = f[name][:, 5] units = f[name].attrs['Units'].decode() longname = f[name].attrs['Title'].decode() fillvalue = f[name].attrs['_FillValue'] data[data == fillvalue] = np.nan # Get the geolocation data latitude = f['/HDFEOS/SWATHS/O3NadirSwath/Geolocation Fields/Latitude'][:] longitude = f['/HDFEOS/SWATHS/O3NadirSwath/Geolocation Fields/Longitude'][:] m = Basemap(projection='cyl', resolution='l', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180) m.drawcoastlines(linewidth=0.5) m.drawparallels(np.arange(-90, 91, 45)) m.drawmeridians(np.arange(-180, 180, 45), labels=[True,False,False,True]) m.scatter(longitude, latitude, c=data, s=1, cmap=plt.cm.jet, edgecolors=None, linewidth=0) cb = m.colorbar() cb.set_label(units) basename = os.path.basename(FILE_NAME) plt.title('{0}\n{1} at nLevels=5'.format(basename, longname)) fig = plt.gcf() # plt.show() pngfile = "{0}.py.png".format(basename) fig.savefig(pngfile)
def Map(self): m = Basemap(projection='cyl', # stere, tmerc, lcc lat_0=39.828127, lon_0=-98.579404, urcrnrlon=-62.208289, urcrnrlat=51.342619, llcrnrlon=-128.936426, llcrnrlat=19.06875) m.drawcoastlines() # draw coastlines m.drawmapboundary() # draw a line around the map region m.drawparallels(np.arange(-90., 120., 30.), labels=[1, 0, 0, 0]) # draw parallels m.drawmeridians(np.arange(0., 420., 60.), labels=[0, 0, 0, 1]) # draw meridians m.drawstates() m.drawcountries() lon = list() lon.append(-80.633333) lon.append(-74.364684) lon.append(-75.387778) lon.append(-84.253333) lat = list() lat.append(28.116667) lat.append(40.715622) lat.append(40.043889) lat.append(30.455) m.scatter(lon, lat, latlon=True, c=np.random.rand(3)) #m.pcolor(lon, lat, latlon=True) plt.title('United States Fair Market Rent') # add a title plt.show()
def plot_pnts(source, ra_0, dec_0, FOV='fullsky', grid_size=15.): ra, dec = np.genfromtxt(source, usecols=(0, 1), unpack=True) ra *= 15. sky = Basemap(projection='ortho', lon_0=-ra_0, lat_0=dec_0, celestial=True) if FOV == 'fullsky': sky.drawmeridians(np.arange(0., 360., grid_size)) sky.drawparallels(np.arange(90, -90, -grid_size)) sky.drawmapboundary(fill_color='White') catx, caty = sky(ra, dec) sky.scatter(catx, caty, 3, marker='o', color='Black') elif isinstance(FOV, float): format_label = lambda deg: '{0:2.0f}h{1:2.0f}m'\ .format(np.floor(deg / 15.), np.remainder(deg, 15.) * 60. / 15.) cnreq = np.array([[ra_0 + FOV / 2., dec_0 - FOV / 2.], [ra_0 - FOV / 2., dec_0 + FOV / 2.]]) cnrxy = np.array(sky(cnreq[:, 0], cnreq[:, 1])).T cenxy = np.array(sky(ra_0, dec_0)) m = Basemap(projection='ortho', lon_0=-ra_0, lat_0=dec_0, celestial=True, llcrnrx=cnrxy[0, 0]-cenxy[0], llcrnry=cnrxy[0, 1]-cenxy[1], urcrnrx=cnrxy[1, 0]-cenxy[0], urcrnry=cnrxy[1, 1]-cenxy[1]) m.drawmeridians(np.arange(cnreq[0, 0], cnreq[1, 0], -grid_size), labels=[0, 0, 0, 1], fmt=format_label) m.drawparallels(np.arange(cnreq[0, 1], cnreq[1, 1], grid_size), labels=[1, 0, 0, 0]) m.drawmapboundary(fill_color='White') catx, caty = m(ra, dec) m.scatter(catx, caty, 3, marker='o', color='Black')
def WorkBook_plotPrisons(self, coords): lons = coords[0] lats = coords[1] print("Graphing image...") m = Basemap(llcrnrlon=-119, llcrnrlat=22, urcrnrlon=-64, urcrnrlat=49, projection='lcc', lat_1=33, lat_2=45, lon_0=-95, resolution='h', area_thresh=10000) x, y = m(lons, lats) m.drawmapboundary(fill_color='white') m.fillcontinents(color='white',lake_color='white') m.scatter(x,y,10,marker='D',color='m') plt.figure(frameon=False) plt.title('US Prison Locations',fontsize=12) plt.savefig("USPrisons.png") background = Image.open("SocioEconomicBackground.png") overlay = Image.open("USPrisons.png") background = background.convert("RGBA") overlay = overlay.convert("RGBA") new_img = Image.blend(background, overlay, 0.5) new_img.save("SocioEconomic_Prison.png","PNG")
def map_trace(tr,ax='None',showpath=True,showplot=True,Lat_0=0.0,Lon_0=60.0): from mpl_toolkits.basemap import Basemap if ax == 'None': m = Basemap(projection='ortho',lat_0=Lat_0,lon_0=Lon_0,resolution='l') m.drawmapboundary() m.drawcoastlines() m.fillcontinents(color='gray',lake_color='white') else: m = ax x1,y1 = m(tr.stats.sac['evlo'],tr.stats.sac['evla']) x2,y2 = m(tr.stats.sac['stlo'],tr.stats.sac['stla']) m.scatter(x1,y1,s=200.0,marker='*',facecolors='y',edgecolors='k',zorder=99) m.scatter(x2,y2,s=20.0,marker='^',color='b',zorder=99) if showpath == True: m.drawgreatcircle(tr.stats.sac['evlo'],tr.stats.sac['evla'], tr.stats.sac['stlo'],tr.stats.sac['stla'], linewidth=1,color='k',alpha=0.5) if showplot == True: plt.show() else: return m
def generate_map(output, latlng, wesn=None): """ Using Basemap and the matplotlib toolkit, this function generates a map and puts a red dot at the location of every IP addresses found in the list. The map is then saved in the file specified in `output`. """ print("Generating map and saving it to {}".format(output)) lats=[] lngs=[] for i in latlng: if i[1]: lats.append(i[1]) lngs.append(i[2]) if wesn: wesn = [float(i) for i in wesn.split('/')] m = Basemap(projection='cyl', resolution='l', llcrnrlon=wesn[0], llcrnrlat=wesn[2], urcrnrlon=wesn[1], urcrnrlat=wesn[3]) else: m = Basemap(projection='cyl', resolution='l') m.bluemarble() x, y = m(lngs, lats) m.scatter(x, y, s=1, color='#ff0000', marker='o', alpha=0.3) plt.savefig(output, dpi=300, bbox_inches='tight')
def plot_grid2D(lons, lats, tec_grid2D, datetime, title_label = ''): LATS, LONS = np.meshgrid(lats, lons) m = Basemap(llcrnrlon=-180, llcrnrlat=-55, urcrnrlon=180, urcrnrlat=75, projection='merc', area_thresh=1000, resolution='i') m.drawstates() m.drawcountries() m.drawcoastlines() parallels = np.arange(-90,90,20) m.drawparallels(parallels,labels=[True,False,False,True]) meridians = np.arange(0,360,40) m.drawmeridians(meridians,labels=[True,False,False,True]) m.scatter(LONS, LATS, c=tec_grid2D, latlon = True, linewidths=0, s=5) m.colorbar() plt.title('%s\n%s' % (title_label, datetime.isoformat(' ')))
def plot_map(lons, lats, c, legend_label, projection='mill', llcrnrlat=-80, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='i'): ''' Optional Arguments: projection - map projection, default set as 'mill' llcrnrlat - lower left corner latitude value, default is -80 urcrnrlat - upper right corner latitude value, default is 90 llcrnrlon - lower left corner longitude value, default is -180 urcrnrlon - upper right corner longitude value, default is 180 resolution - the resolution of the plot, default is 'i' Required Arguments: lons - list of longitude values to be plotted lats - list of latitude values to be plotted c - the color of the points to be plotted legend_label - how this set of points will be labeled on the legend Returns: m - a basemap object defined by input bounds with input points included ''' # Creates a basic plot of a series of lat,lon points over a defined region m = Basemap(projection=projection, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, resolution=resolution) m.drawcoastlines() m.drawmapboundary() m.drawcountries() m.etopo() m.drawmeridians(np.arange(llcrnrlon, urcrnrlon, 5), labels=[0,0,0,1], fontsize=10) m.drawparallels(np.arange(llcrnrlat, urcrnrlat, 5), labels=[1,0,0,0], fontsize=10) x,y = m(lons, lats) m.scatter(x, y, color=c, label=legend_label, marker='o', edgecolor='none', s=10) return m
def makeMap(latList, lonList, cityList): minLon = -130 minLat = 25 maxLon = -60 maxLat = 50 # Below is used to offset a bit the labels of the cities, for projection='merc'. labelYOffset = -0.9 labelXOffset = 0.8 # Below is used to offset a bit the labels of the cities, for projection='cyl'. #labelYOffset = -0.4 #labelXOffset = 0.8 plt.figure(1, figsize=(15, 15)) myMap = Basemap(minLon, minLat, maxLon, maxLat, projection='merc', resolution='h') myMap.drawcoastlines() # Below if we want to show counties. #myMap.drawcounties(linewidth=1, linestyle='solid', color='red') # Below if we want to show states. #myMap.drawstates(linewidth=2, linestyle='solid', color='green') myMap.drawcountries(linewidth=3, linestyle='solid', color='black') myMap.drawrivers(linewidth=1, linestyle='solid', color='blue') # Another nice option is shaderelief(). #myMap.shadedrelief() myMap.etopo() myMap.scatter(latList, lonList, latlon=True, c='red', s=100) X, Y = myMap(latList, lonList) # The for loop is to add the text labels of the cities. for x, y, label in zip(X, Y, cityList): plt.text(x + labelXOffset, y + labelYOffset, label) return plt.show()
def show(self, proj='moll', lon_0=180, tmap=None, coord=None): from mpl_toolkits.basemap import Basemap import pylab as plt import resources.figures as figures figures.set_fancy() if coord==None: ra = np.rad2deg(self.grid['points'][:,0]) dec = np.rad2deg(self.grid['points'][:,1]) else: ra = np.rad2deg(coord[:,0]) dec = np.rad2deg(coord[:,1]) fig = plt.figure() m = Basemap(projection=proj,lon_0=lon_0)#,celestial=True) # celestial=True inverses alpha (East towards the right) m.drawparallels(np.arange(-60.,90.,30.),labels=[1,0,0,0]) m.drawmeridians(np.arange(0.,360.,30.)) ra__ = np.arange(0., 360., 30.) x, y = m(ra__,ra__*0) for x,y,t in zip(x,y,ra__): plt.text(x, y, figures.format_degree(t), color='black', ha='center', weight='black', size='small') ##93c6ed if tmap==None: m.scatter(ra,dec,latlon=True,marker='x',s=20,cmap=plt.cm.binary) else: m.scatter(ra,dec,c=tmap,latlon=True,marker='x',s=20,cmap=plt.cm.binary) plt.show()
def analysis(filename): with open(filename, 'r') as f: friends = json.load(f) df = pandas.DataFrame(friends) df.to_csv(filename.replace('json','csv'),sep='\t',encoding='utf-8') # print(df.groupby(['City','Sex']).value_counts()) print(df['City'].value_counts()[:30]) # print df # for friend in friends: # print("%s: %s" % (friend.get('NickName'),friend.get('Sex'))) # Create a map on which to draw. We're using a mercator projection, and showing the whole world. m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='c') # Draw coastlines, and the edges of the map. m.drawcoastlines() m.drawmapboundary() # Convert latitude and longitude to x and y coordinates loc = convertgeo(df['City']) print loc x, y = m(loc[0], loc[1]) # list(airports["longitude"].astype(float)), list(airports["latitude"].astype(float))) # Use matplotlib to draw the points onto the map. m.scatter(x,y,1,marker='o',color='red') # Show the plot. plt.show()
def example_2(): # retrieve data dir = "/homespace/gaubert/viirs/Mband-SDR" geo_file = h5py.File("%s/%s" %(dir,"GMODO_npp_d20030125_t0847056_e0848301_b00015_c20090513182937526121_gisf_pop.h5")) lats = geo_file['All_Data']['VIIRS-MOD-GEO_All']['Latitude'][:] lons = geo_file['All_Data']['VIIRS-MOD-GEO_All']['Longitude'][:] # draw map with markers for float locations #m = Basemap(projection='hammer',lon_0=180) lon_ref = lons[0][0]-lons[-1][-1]/2 lat_ref = 10 #m = Basemap(projection='ortho',lat_0=lat_ref,lon_0=lon_ref,resolution='l') m = Basemap(projection='nsper',lat_0=lat_ref,lon_0=lon_ref,satellite_height=2000*1000,resolution='l') #x, y = m(lons[0:10],lats[0:10]) x,y = m(lons,lats) #m.drawcoastlines() m.drawmapboundary(fill_color='#99ffff') m.fillcontinents(color='#cc9966',lake_color='#99ffff') m.scatter(x,y,s = 1 ,color='k') #m.drawgreatcircle(lons[0][0],lats[0][0],lons[0][-1],lats[0][-1],linewidth=2,color='b') #m.drawgreatcircle(lons[-1][0],lats[0][0],lons[-1][-1],lats[0][-1],linewidth=2,color='b') plt.title('Locations of %s ARGO floats active between %s and %s' %\ (len(lats),'2002', '2003')) plt.savefig('/tmp/plotargo.png')
def plot_pierce_points(self,depth=410.0,ax='None'): ''' Plots pierce points for a given depth. If an axes object is supplied as an argument it will use it for the plot. Otherwise, a new axes object is created. ''' if ax == 'None': m = Basemap(llcrnrlon=0.0,llcrnrlat=-35.0,urcrnrlon=120.0,urcrnrlat=35.0) else: m = ax m.drawmapboundary() m.drawcoastlines() found_points = False for i in range(0,len(self.pierce_dict)): if self.pierce_dict[i]['depth'] == depth: x,y = m(self.pierce_dict[i]['lon'],self.pierce_dict[i]['lat']) found_points = True if found_points == True: m.scatter(x,y,50,marker='+',color='r') else: print "no pierce points found for the given depth"
def render_nextbus_dataframe(route, nextbus_df): """Plots the NextBus Vehicle Location's Panda Data frame to a Matplotlib and Basemap Geospatial image.""" min_long = min(nextbus_df.lon) min_lat = min(nextbus_df.lat) max_long = max(nextbus_df.lon) max_lat = max(nextbus_df.lat) bmap = Basemap(llcrnrlon=min_long, llcrnrlat=min_lat, urcrnrlon=max_long, urcrnrlat=max_lat, ellps='WGS84', resolution='h', area_thresh=1000) bmap.drawmapboundary(fill_color='white') bmap.scatter(nextbus_df.lon, nextbus_df.lat, marker='d', edgecolor='g', facecolor='g', alpha=0.5) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.axis([min_long, max_long, min_lat, max_lat]) plt.title('NextBus Vehicle Locations for route {}'.format(route)) plt.grid(True) # plt.legend(loc='lower center') plt.savefig('nextbus_vehicle_locations.png', fmt='png', dpi=600) # plt.show() # Other components (like GMaps plotting) will also use Matplotlib, so # it's better to clear the figure that Matplotlib generated plt.clf()
def plotwithrivers(lat, lon, lat2 = None, lon2 = None): #Plots equal length arrays lat and lon of latitudes and longitudes. WITH RIVERS latLL = min(lat) lonLL = min(lon) latUR = max(lat) lonUR = max(lon) meanlat = np.mean(lat) meanlon = np.mean(lon) map = Basemap(projection='merc' ,llcrnrlon= lonLL - 1,llcrnrlat=latLL -1 , urcrnrlon= lonUR+1,urcrnrlat= latUR+1,resolution='h') #map = Basemap(projection='spstere', boundinglat = latUR +1, lon_0 = meanlon) # draw coastlines, country boundaries, fill continents. map.drawcoastlines(linewidth=0.5) map.drawcountries(linewidth=0.5) # map.fillcontinents(color='coral',lake_color='aqua') # draw the edge of the map projection region (the projection limb) #map.drawmapboundary(fill_color='aqua') # draw lat/lon grid lines every 30 degrees. map.drawmeridians(np.arange(0,360,1)) map.drawparallels(np.arange(-90,90,1)) #map.bluemarble() #NASA image - kek map.drawrivers(linewidth=0.5) map.scatter(lon,lat, latlon = True) try: map.scatter(lon2,lat2,latlon = True , color = 'g') except: print("")
def plotMap(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, lons, lats, color, title): m = Basemap(projection='merc', resolution='i', llcrnrlon = llcrnrlon, llcrnrlat = llcrnrlat, urcrnrlon = urcrnrlon, urcrnrlat = urcrnrlat) m.drawcountries(linewidth=1) m.drawcoastlines(linewidth=1) m.drawlsmask() m.drawstates() m.drawrivers(linewidth=.1) plt.title((str(len(lats)))+ \ title, fontsize=12) x,y = m(lons, lats) if color == 'r': plt.hexbin(x, y, gridsize=40, cmap=plt.cm.Reds) if color == 'b': plt.hexbin(x, y, gridsize=40, cmap=plt.cm.Blues) if color == 'g': plt.hexbin(x, y, gridsize=40, cmap=plt.cm.Greens) m.scatter(lons, lats, 1, marker='o',color=color, latlon=True) plt.show()
def plot(self,reports,itime,ftime,fname,outdir,Nlim=False, Elim=False,Slim=False,Wlim=False, annotate=True,fig=False,ax=False,ss=50,color='blue'): reportidx = N.array([n for n,t in zip(range(len(self.r['EVENT_TYPE'])),self.r['EVENT_TYPE']) if reports in t]) lateidx = N.where(self.datetimes > itime) earlyidx = N.where(self.datetimes < ftime) timeidx = N.intersect1d(earlyidx,lateidx,)#assume_unique=True) plotidx = N.intersect1d(reportidx,timeidx) from mpl_toolkits.basemap import Basemap if fig==False: fig,ax = plt.subplots(1,figsize=(6,6)) m = Basemap(projection='merc', llcrnrlat=Slim, llcrnrlon=Wlim, urcrnrlat=Nlim, urcrnrlon=Elim, lat_ts=(Nlim-Slim)/2.0, resolution='i', ax=ax) m.drawcoastlines() m.drawstates() m.drawcountries() m.scatter(self.r['BEGIN_LON'][plotidx],self.r['BEGIN_LAT'][plotidx],latlon=True, marker='D',facecolors=color,edgecolors='black',s=ss) fig.tight_layout() plt.savefig(os.path.join(outdir,fname))
def __init__(self, subPlot = None, gpxData = None): GeoSectionViewerGpxData.__init__(self, subPlot, gpxData) latitudes, longitudes, elevations, timestamps = self.gpxData.getLatLongElevTs() latitudeMax = max(latitudes) latitudeMin = min(latitudes) longitudeMax = max(longitudes) longitudeMin = min(longitudes) elevationMax = max(elevations) elevationMin = min(elevations) scalledMax = 30 scalledMin = 1 scalledElevations = [((((point.elevation - elevationMin) * (scalledMax - scalledMin)) / (elevationMax - elevationMin)) + scalledMin) for i, point in enumerate(self.gpxData)] bbox = longitudeMin, latitudeMin, longitudeMax, latitudeMax mm = geotiler.Map(extent=bbox, zoom=14) img = geotiler.render_map(mm) img.save("geotiler.png") map = Basemap( llcrnrlon=bbox[0], llcrnrlat=bbox[1], urcrnrlon=bbox[2], urcrnrlat=bbox[3], projection='merc', resolution='i', ax=self.subPlot) map.imshow(img, aspect='auto', origin='upper') map.scatter(longitudes, latitudes, c='red', s=scalledElevations, marker='o', cmap=cm.hot_r, alpha=0.4, latlon=True) map.plot(longitudes, latitudes, 'k', c='red', latlon=True)
def observe(self,iter, labels, X,centers,showPlot=False): print "%s %d." % (self.prefix, iter) pyplot.plot(hold=False) # clear previous plot pyplot.hold(True) m = Basemap(projection='merc',resolution='h',llcrnrlon=120.0, llcrnrlat=21.5, urcrnrlon=123.00, urcrnrlat=25.50) m.drawmapboundary(fill_color='black') # fill to edge m.drawcountries() m.fillcontinents(color='white',lake_color='black',zorder=0) # draw parallels. parallels = np.arange(20.,30,.5) m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10) # draw meridians meridians = np.arange(119.,125.,.5) m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10) # draw points data_colors=[self.colors[lbl] for lbl in labels] m.scatter(X[:, 0], X[:, 1], c=data_colors, alpha=0.5, latlon=True) pyplot.show()
def triangulation_map(station_lon, station_lat, station_val, cmap=None, *args, **kwargs): """ Using matplotlib.pyplot.tricontourf() function to plot contourplot on an irreguar grid by using triangulation. """ # map boundries lat_0 = 51 lat_min = 47 lat_max = 55 lon_0 = 10 lon_min = 5 lon_max = 16 m = Basemap(projection='tmerc', lat_0=lat_0, lon_0=lon_0, llcrnrlat=lat_min, llcrnrlon=lon_min, urcrnrlat=lat_max, urcrnrlon=lon_max, resolution='i') m.drawcoastlines() m.drawcountries() m.drawmapboundary() m.contourf(station_lon, station_lat, station_val, cmap=cmap, latlon=True, tri=True, *args, **kwargs) m.scatter(station_lon, station_lat, color='k', s=5, latlon=True) # Set Triangulation manual?: #station_x, station_y = m(station_lon, station_lat) #triang = tri.Triangulation(station_x, station_y) #plt.tricontour(station_x, station_y, station_val, 15, linewidths=0.5, colors='k') #plt.tricontourf(x, y, z, 15, cmap=plt.cm.rainbow, norm=plt.Normalize(vmax=abs(zi).max(), vmin=-abs(zi).max())) plt.show()
def run(FILE_NAME): with h5py.File(FILE_NAME, mode="r") as f: name = "/RetrievalResults/xco2" data = f[name][:] units = f[name].attrs["Units"][0] longname = f[name].attrs["Description"][0] # Get the geolocation data latitude = f["/RetrievalGeometry/retrieval_latitude"][:] longitude = f["/RetrievalGeometry/retrieval_longitude"][:] m = Basemap(projection="cyl", resolution="l", llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180) m.drawcoastlines(linewidth=0.5) m.drawparallels(np.arange(-90, 91, 45)) m.drawmeridians(np.arange(-180, 180, 45), labels=[True, False, False, True]) m.scatter(longitude, latitude, c=data, s=1, cmap=plt.cm.jet, edgecolors=None, linewidth=0) # cb = m.colorbar(orientation='horizontal', format='%.1e') cb = m.colorbar(location="bottom", format="%.1e", pad="10%") cb.set_label(units) basename = os.path.basename(FILE_NAME) plt.title("{0}\n{1}".format(basename, longname)) fig = plt.gcf() # plt.show() pngfile = "{0}.py.png".format(basename) fig.savefig(pngfile)
def draw_point(lats, lons): m = Basemap(resolution='i') m.drawcoastlines() m.drawcountries() x, y = m(lons, lats) m.scatter(x, y, s=0.3, color='#ff0000', marker='.') plt.show()
def plot_cities(): map = Basemap(llcrnrlon=-119, llcrnrlat=22, urcrnrlon=-64, urcrnrlat=49, projection='lcc', lat_1=33, lat_2=45, lon_0=-95, resolution='i', area_thresh=10000) map.drawcoastlines() map.drawcountries() map.drawstates() # key is language, value is pair (longitudes, latitudes) plots = { "Java" : ([], []), "Python" : ([], []), "R" : ([], []) } # we want each language to have a different marker and color markers = { "Java" : "o", "Python" : "s", "R" : "^" } colors = { "Java" : "r", "Python" : "b", "R" : "g" } for (longitude, latitude), language in cities: plots[language][0].append(longitude) plots[language][1].append(latitude) # create a scatter series for each language for language, (x, y) in plots.iteritems(): x1, y1 = map(x, y) map.scatter(x1, y1, color=colors[language], marker=markers[language], label=language, zorder=10) # plot_state_borders(plt) # assume we have a function that does this plt.legend(loc=3,prop={'size':12}) # let matplotlib choose the location plt.title("Favorite Programming Languages") plt.show()
def Plotcat(ra_0, dec_0, fov_size=15., grid_size=2., allsky=False): pkscat = np.loadtxt('source_list_pks_140MHz',usecols=(0,1)) pkscat[:,0] *= 15. sky = Basemap(projection='ortho', lon_0=-ra_0, lat_0=dec_0, celestial=True) if allsky==True: sky.drawmeridians(np.arange(0.,360.,grid_size)) sky.drawparallels(np.arange(90,-90,-grid_size)) sky.drawmapboundary(fill_color='White') catx, caty = sky(pkscat[:,0],pkscat[:,1]) sky.scatter(catx,caty,3,marker='o',color='Black') else: cnreq = np.array([[ra_0+fov_size/2., dec_0-fov_size/2.], [ra_0-fov_size/2., dec_0+fov_size/2.]]) # = [[ll_ra, ll_dec], [ur_ra, ur_dec]] cnrxy = np.transpose(np.array(sky(cnreq[:,0],cnreq[:,1]))) # = [[ll_x, ll_y], [ur_x, ur_y]] cenxy = np.array(sky(ra_0,dec_0)) cnrmap = cnrxy-np.array([cenxy,cenxy]) m = Basemap(projection='ortho', lon_0=-ra_0, lat_0=dec_0, celestial=True, llcrnrx=cnrxy[0,0]-cenxy[0], llcrnry=cnrxy[0,1]-cenxy[1], urcrnrx=cnrxy[1,0]-cenxy[0], urcrnry=cnrxy[1,1]-cenxy[1]) m.drawmeridians(np.arange(cnreq[0,0], cnreq[1,0], -grid_size), labels=[0,0,0,1],fmt=format_label) m.drawparallels(np.arange(cnreq[0,1], cnreq[1,1], grid_size), labels=[1,0,0,0]) m.drawmapboundary(fill_color='White') catx, caty = m(pkscat[:,0],pkscat[:,1]) m.scatter(catx,caty,3,marker='o',color='Black')
def address_map( data ) : a = addresses_with_locations( data ) plt.figure() m = Basemap( projection = "robin", llcrnrlon = -180, llcrnrlat = -80, urcrnrlon = 180, urcrnrlat = 80, lon_0 = 0, lat_0 = 0, resolution = "c" ) m.drawcoastlines() m.fillcontinents( color = 'coral', lake_color = 'aqua', alpha=0.3 ) m.drawmeridians( arange( -180, 180, 60 ) ) m.drawparallels( arange( -80, 80, 60 ) ) xys = array([m(x[2][1], x[2][0]) for x in a]) xs = xys[:,0] ys = xys[:,1] counts = array([x[1] for x in a]) * 200 m.scatter( xs, ys, s=counts, marker='o', c='b', alpha=0.3 ) plt.title("Research by sites, top 500 papers Ultraintense Lasers") plt.savefig("map.png") plt.close()
def plot_global_map(self): """ Plot global map of event and stations """ # ax = plt.subplot(211) plt.title(self.cmtsource.eventname) m = Basemap(projection='cyl', lon_0=0.0, lat_0=0.0, resolution='c') m.drawcoastlines() m.fillcontinents() m.drawparallels(np.arange(-90., 120., 30.)) m.drawmeridians(np.arange(0., 420., 60.)) m.drawmapboundary() x, y = m(self.sta_lon, self.sta_lat) m.scatter(x, y, 30, color="r", marker="^", edgecolor="k", linewidth='0.3', zorder=3) cmt_lat = self.cmtsource.latitude cmt_lon = self.cmtsource.longitude focmecs = get_cmt_par(self.cmtsource)[:6] ax = plt.gca() bb = beach(focmecs, xy=(cmt_lon, cmt_lat), width=20, linewidth=1, alpha=1.0) bb.set_zorder(10) ax.add_collection(bb)
def plot_global_map(self, outputfile=None): """ Plot global map of event and stations """ # ax = plt.subplot(211) fig = plt.figure() ax = plt.gca() plt.title("Station and Event distribution") m = Basemap(projection='moll', lon_0=0.0, lat_0=0.0, resolution='c') m.drawcoastlines() m.fillcontinents() m.drawparallels(np.arange(-90., 120., 30.)) m.drawmeridians(np.arange(0., 420., 60.)) m.drawmapboundary() cm = plt.cm.get_cmap('RdYlBu') x, y = m(self.station_loc[:, 1], self.station_loc[:, 0]) m.scatter(x, y, 30, color=self.weight, marker="^", edgecolor="k", linewidth='0.3', zorder=3, cmap=cm) plt.colorbar(shrink=0.8) cmt_lat = self.event.latitude cmt_lon = self.event.longitude src_x, src_y = m(cmt_lon, cmt_lat) m.scatter(src_x, src_y, 60, color="g", marker="o", edgecolor="k", linewidth='0.3', zorder=3) if outputfile is None: plt.show() else: plt.savefig(outputfile) plt.close(fig)
def draw_fires_on_map(): """ Draw a map of the United States, and mark the large fires, based on size """ # Get a location dictionary of the active fires try: location = get_fires()['FIRES'] print 'Retrieved fires from Active Fire Mapping Program' except: location = get_incidents(limit_num=10) print 'Retrieved fires from InciWeb' ## ---- Lat/Lons ---------------------------------------------------------- ## ------------------------------------------------------------------------ h = h5py.File( '/uufs/chpc.utah.edu/common/home/horel-group7/Pando/GOES16/goes16_conus_latlon_east.h5', 'r') lons = h['longitude'][:] lats = h['latitude'][:] try: ABI = file_nearest(datetime.utcnow()) ## ---- TRUE COLOR -------------------------------------------------------- ## ------------------------------------------------------------------------ TC = get_GOES16_truecolor(ABI, only_RGB=False, night_IR=True) print 'File date:', TC['DATE'] ## ---- FIRE TEMPERATURE -------------------------------------------------- ## ------------------------------------------------------------------------ FT = get_GOES16_firetemperature(ABI, only_RGB=False) ## ---- Geostationary Lightning Mapper ------------------------------------ ## ------------------------------------------------------------------------ GLM = accumulate_GLM(get_GLM_files_for_ABI(ABI)) ## ---- BLEND TRUE COLOR/FIRE TEMPERATURE --------------------------------- max_RGB = np.nanmax([FT['rgb_tuple'], TC['rgb_tuple']], axis=0) except: ABI = None bot_left_lat = np.min([location[i]['latitude'] for i in location.keys()]) bot_left_lon = np.min([location[i]['longitude'] for i in location.keys()]) top_right_lat = np.max([location[i]['latitude'] for i in location.keys()]) top_right_lon = np.max([location[i]['longitude'] for i in location.keys()]) plt.figure(100) #m = draw_CONUS_cyl_map() bot_left_lat -= 1.5 bot_left_lon -= 1.5 top_right_lat += 1.5 top_right_lon += 2.5 print bot_left_lat, bot_left_lon, top_right_lat, top_right_lon m = Basemap(resolution='i', projection='cyl', area_thresh=1500,\ llcrnrlon=bot_left_lon, llcrnrlat=bot_left_lat, \ urcrnrlon=top_right_lon, urcrnrlat=top_right_lat) if ABI is None: m.arcgisimage(xpixels=1000, dpi=100) plt.xlabel('Updated: %s\nGOES Image: %s' % (datetime.now().strftime('%Y-%B-%d %H:%M MT'), 'No GOES Image on Pando'), fontsize=7) else: newmap = m.pcolormesh(lons, lats, TC['TrueColor'][:, :, 1], color=max_RGB, zorder=1, latlon=True) newmap.set_array(None) m.scatter(GLM['longitude'], GLM['latitude'], marker='+', color='yellow', zorder=10, latlon=True) plt.xlabel('Updated: %s\nGOES Image: %s' % (datetime.now().strftime('%Y-%B-%d %H:%M MT'), TC['DATE'].strftime('%Y-%B-%d %H:%M UTC')), fontsize=7) m.drawmapboundary(fill_color='k', zorder=5) m.drawstates(linewidth=.2, zorder=5) m.drawcoastlines(linewidth=.25, zorder=5) m.drawcountries(linewidth=.2, zorder=5) print "\n\n Plot scatter points" for F in location: x, y = m(location[F]['longitude'], location[F]['latitude']) m.scatter(x, y, s=location[F]['area'] / 300, c='orangered', edgecolors='none', zorder=10) plt.text(x + .1, y + .1, F, fontsize=7, zorder=10) plt.title('Active Fires Larger than 1000 Acres\n%s' % (date.today().strftime('%B %d, %Y')), fontsize=15) plt.savefig( '/uufs/chpc.utah.edu/common/home/u0553130/public_html/oper/HRRR_fires/firemap.png', bbox_inches="tight") return location
def plot_data_corr_map_with_sit(): dirs = "../result_h_1day_delay/corr_ic0_search_detail/" if not os.path.exists(dirs): os.makedirs(dirs) month_list = ["05", "06", "07", "08", "09", "10"] for month in month_list: print(month) data = pd.read_csv("../data/corr_gw/corr_gw_" + month + ".csv").dropna() """ 3種類の図 1 相関が低い時に閾値を満たす 相関が低いのに閾値を満たしていない(偶然) 2 相関が高い時に閾値を満たしていない 相関が高いのに閾値を満たす(偶然) 3 無相関なのに閾値を満たす """ """ #見栄えを整えるために書き直したもの data_corr = np.array(data["corr"]) save_name_corr = "../result_h_1day_delay/corr_map/ic0_A_" + month + "_thesis.png" plot_map_for_thesis(data_corr, save_name_corr, plt.cm.jet, 1, -1) data_std = np.array(data["ic0_std"]) save_name_std = "../result_h_1day_delay/std_map/ic0_std_" + month + "_thesis.png" plot_map_for_thesis(data_std, save_name_std, plt.cm.jet, 25, 0) """ th_sit = 250 th_A = 0.002 th_corr_list = [0.5, 0.6, 0.7, 0.8] for th_corr in th_corr_list: grid_1_t = np.array(data[(data["corr"]<=-th_corr)&(data["sit_std"]>=th_sit)&(data["A_std"]>=th_A)].index) grid_1_f = np.array(data[(data["corr"]<=-th_corr)&((data["sit_std"]<th_sit)|(data["A_std"]<th_A))].index) grid_2_t = np.array(data[(data["corr"]>=th_corr)&((data["sit_std"]<th_sit)|(data["A_std"]<th_A))].index) grid_2_f = np.array(data[(data["corr"]>=th_corr)&(data["sit_std"]>=th_sit)&(data["A_std"]>=th_A)].index) grid_3 = np.array(data[(data["corr"]>-th_corr)&(data["corr"]<th_corr)&(data["sit_std"]>=th_sit)&(data["A_std"]>=th_A)].index) print("grid_1_t: {}\ngrid_1_f: {}\nggrid_2_t: {}\ngrid_2_f: {}\ngrid_3: {}".format( grid_1_t, grid_1_f, grid_2_t, grid_2_f, grid_3)) m = Basemap(lon_0=180, boundinglat=50, resolution='l', projection='npstere') lon = np.array(latlon_ex.Lon) lat = np.array(latlon_ex.Lat) x, y = m(lon, lat) m.drawcoastlines(color = '0.15') m.fillcontinents(color='#555555') m.scatter(x[grid_1_t], y[grid_1_t], marker='o', color="b", s=2, alpha=0.9) m.scatter(x[grid_1_f], y[grid_1_f], marker='+', color="r", s=2, alpha=0.9) plt.savefig(dirs + "sit_std_A_std_1_th_" + str(int(th_corr*10)) + "_" + month + ".png", dpi=200) plt.close() m.drawcoastlines(color = '0.15') m.fillcontinents(color='#555555') m.scatter(x[grid_2_t], y[grid_2_t], marker='o', color="b", s=2, alpha=0.9) m.scatter(x[grid_2_f], y[grid_2_f], marker='+', color="r", s=2, alpha=0.9) plt.savefig(dirs + "sit_std_A_std_2_th_" + str(int(th_corr*10)) + "_" + month + ".png", dpi=200) plt.close() m.drawcoastlines(color = '0.15') m.fillcontinents(color='#555555') m.scatter(x[grid_3], y[grid_3], marker='o', color = "r", s=2, alpha=0.9) plt.savefig(dirs + "sit_std_A_std_3_th_" + str(int(th_corr*10)) + "_" + month + ".png", dpi=200) plt.close() """
x_grid, y_grid = city_map(lon_grid, lat_grid) clevs = [0.1] + np.linspace(0.0, 85, 18) cont = city_map.contourf(x_grid, y_grid, global_emissions_values, clevs, cmap='Reds', zorder=100) # Plot cities x, y = city_map(np.array(city_data['Longitude'].tolist()), np.array(city_data['Latitude'].tolist())) city_map.scatter(x, y, 30, marker='o', edgecolors='m', facecolors='none', zorder=200) # Finish plot plt.title( 'The top 49 $CO_2$ emitting cities in 2005 [Hoornweg, 2010], \n ' + 'located within the globally gridded $CO_2$ emissions (Mt; ' + '>1e-4) during ' + year) cbar = city_map.colorbar(cont, location='bottom', pad='5%') cbar.set_label('Mt $CO_2$') plt.show()
def _plot_basemap_into_axes(ax, lons, lats, size, color, bmap=None, labels=None, projection='global', resolution='l', continent_fill_color='0.8', water_fill_color='1.0', colormap=None, marker="o", title=None, adjust_aspect_to_colorbar=False, **kwargs): # @UnusedVariable """ Creates a (or adds to existing) basemap plot with a data point scatter plot in given axes. See :func:`plot_basemap` for details on most args/kwargs. :type ax: :class:`matplotlib.axes.Axes` :param ax: Existing matplotlib axes instance, optionally with previous basemap plot (see `bmap` kwarg). :type bmap: :class:`mpl_toolkits.basemap.Basemap` :param bmap: Basemap instance in provided matplotlib Axes `ax` to reuse. If specified, any kwargs regarding the basemap plot setup will be ignored (i.e. `projection`, `resolution`, `continent_fill_color`, `water_fill_color`). :rtype: :class:`matplotlib.collections.PathCollection` :returns: Matplotlib path collection (e.g. to reuse for colorbars). """ fig = ax.figure if bmap is None: if projection == 'global': bmap = Basemap(projection='moll', lon_0=round(np.mean(lons), 4), resolution=_BASEMAP_RESOLUTIONS[resolution], ax=ax) elif projection == 'ortho': bmap = Basemap(projection='ortho', resolution=_BASEMAP_RESOLUTIONS[resolution], area_thresh=1000.0, lat_0=round(np.mean(lats), 4), lon_0=round(mean_longitude(lons), 4), ax=ax) elif projection == 'local': if min(lons) < -150 and max(lons) > 150: max_lons = max(np.array(lons) % 360) min_lons = min(np.array(lons) % 360) else: max_lons = max(lons) min_lons = min(lons) lat_0 = max(lats) / 2. + min(lats) / 2. lon_0 = max_lons / 2. + min_lons / 2. if lon_0 > 180: lon_0 -= 360 deg2m_lat = 2 * np.pi * 6371 * 1000 / 360 deg2m_lon = deg2m_lat * np.cos(lat_0 / 180 * np.pi) if len(lats) > 1: height = (max(lats) - min(lats)) * deg2m_lat width = (max_lons - min_lons) * deg2m_lon margin = 0.2 * (width + height) height += margin width += margin else: height = 2.0 * deg2m_lat width = 5.0 * deg2m_lon # do intelligent aspect calculation for local projection # adjust to figure dimensions w, h = fig.get_size_inches() ax_bbox = ax.get_position() aspect = (w * ax_bbox.width) / (h * ax_bbox.height) if adjust_aspect_to_colorbar: aspect *= 1.2 if width / height < aspect: width = height * aspect else: height = width / aspect bmap = Basemap(projection='aea', resolution=_BASEMAP_RESOLUTIONS[resolution], area_thresh=1000.0, lat_0=round(lat_0, 4), lon_0=round(lon_0, 4), width=width, height=height, ax=ax) # not most elegant way to calculate some round lats/lons def linspace2(val1, val2, n): """ returns around n 'nice' values between val1 and val2 """ dval = val2 - val1 round_pos = int(round(-np.log10(1. * dval / n))) # Fake negative rounding as not supported by future as of now. if round_pos < 0: factor = 10**(abs(round_pos)) delta = round(2. * dval / n / factor) * factor / 2 else: delta = round(2. * dval / n, round_pos) / 2 new_val1 = np.ceil(val1 / delta) * delta new_val2 = np.floor(val2 / delta) * delta n = int((new_val2 - new_val1) / delta + 1) return np.linspace(new_val1, new_val2, n) n_1 = int(np.ceil(height / max(width, height) * 8)) n_2 = int(np.ceil(width / max(width, height) * 8)) parallels = linspace2(lat_0 - height / 2 / deg2m_lat, lat_0 + height / 2 / deg2m_lat, n_1) # Old basemap versions have problems with non-integer parallels. try: bmap.drawparallels(parallels, labels=[0, 1, 1, 0]) except KeyError: parallels = sorted(list(set(map(int, parallels)))) bmap.drawparallels(parallels, labels=[0, 1, 1, 0]) if min(lons) < -150 and max(lons) > 150: lon_0 %= 360 meridians = linspace2(lon_0 - width / 2 / deg2m_lon, lon_0 + width / 2 / deg2m_lon, n_2) meridians[meridians > 180] -= 360 bmap.drawmeridians(meridians, labels=[1, 0, 0, 1]) else: msg = "Projection '%s' not supported." % projection raise ValueError(msg) # draw coast lines, country boundaries, fill continents. if MATPLOTLIB_VERSION >= [2, 0, 0]: ax.set_facecolor(water_fill_color) else: ax.set_axis_bgcolor(water_fill_color) bmap.drawcoastlines(color="0.4") bmap.drawcountries(color="0.75") bmap.fillcontinents(color=continent_fill_color, lake_color=water_fill_color) # draw the edge of the bmap projection region (the projection limb) bmap.drawmapboundary(fill_color=water_fill_color) # draw lat/lon grid lines every 30 degrees. bmap.drawmeridians(np.arange(-180, 180, 30)) bmap.drawparallels(np.arange(-90, 90, 30)) fig.bmap = bmap # compute the native bmap projection coordinates for events. x, y = bmap(lons, lats) # plot labels if labels: if 100 > len(lons) > 1: for name, xpt, ypt, _colorpt in zip(labels, x, y, color): # Check if the point can actually be seen with the current bmap # projection. The bmap object will set the coordinates to very # large values if it cannot project a point. if xpt > 1e25: continue ax.text(xpt, ypt, name, weight="heavy", color="k", zorder=100, path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white") ]) elif len(lons) == 1: ax.text(x[0], y[0], labels[0], weight="heavy", color="k", path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white") ]) # scatter plot is removing valid x/y points with invalid color value, # so we plot those points separately. try: nan_points = np.isnan(np.array(color, dtype=np.float)) except ValueError: # `color' was not a list of values, but a list of colors. pass else: if nan_points.any(): x_ = np.array(x)[nan_points] y_ = np.array(y)[nan_points] size_ = np.array(size)[nan_points] bmap.scatter(x_, y_, marker=marker, s=size_, c="0.3", zorder=10, cmap=None) scatter = bmap.scatter(x, y, marker=marker, s=size, c=color, zorder=10, cmap=colormap) if title: ax.set_title(title) return scatter
def plot_target(data_temp, var_temp, start_indices_temp, end_indices_temp, out_dir_temp): #Set some strings if var_temp == 'rad_continuum_o2': var_string = 'o2_radiance' var_cbar_string = 'Radiance [Ph s' + r'$^{-1}$' + ' m' + r'$^{-2}$' + ' sr' + r'$^{-1}$' + r'$\mu$' + 'm' + r'$^{-1}$' + ']' var_title_string = "O" + r'$_2$' + ' A-Band Radiance' var_cbar = plt.cm.Purples_r elif var_temp == 'xco2': var_string = 'xco2' var_cbar_string = r'$X_{CO_2}$' + ' [ppm]' var_title_string = r'$X_{CO_2}$' var_cbar = plt.cm.viridis elif var_temp == 'dp': var_string = 'dp' var_cbar_string = 'dp [hPa]' var_title_string = 'dp' var_cbar = plt.cm.RdBu_r elif var_temp == 'aod_total': var_string = 'aod' var_cbar_string = 'AOD' var_title_string = 'AOD' var_cbar = plt.cm.magma else: print("Please select an appropriate variable...") ############################################ #Plot all the individual TG/AMs! for i in range(len(start_indices_temp)): print( "---------------------------------------------------------------") print("Plotting TG/AM ", str(i + 1), " of ", len(start_indices_temp)) data_temp2 = data_temp[start_indices_temp[i]:end_indices_temp[i]] print(data_temp2['target_id'][0], int(data_temp2['orbit'][0]), data_temp2['sounding_id'][0]) #Remove weird outliers that are far from the actual TG/AM cluster_input = np.array( [data_temp2['longitude'], data_temp2['latitude']]).T try: clusters = hcluster.fclusterdata(cluster_input, 1., criterion='distance') print("Cluster #s = ", np.bincount(clusters)) #Grab the largest cluster, or any/all clusters greater than 30 soundings cluster_mask = (clusters == np.argmax( np.bincount(clusters))) | np.isin( clusters, np.where(np.bincount(clusters) > 30)[0]) except: #If there's exactly one sounding, fclusterdata doesn't work cluster_mask = np.ones(len(data_temp2), dtype=bool) #Determine plotting box N,S,E,W = np.round(max(data_temp2['target_lat'][cluster_mask][0],data_temp2['latitude'][cluster_mask].max())+.25,1),\ np.round(min(data_temp2['target_lat'][cluster_mask][0],data_temp2['latitude'][cluster_mask].min())-.25,1),\ np.round(max(data_temp2['target_lon'][cluster_mask][0],data_temp2['longitude'][cluster_mask].max())+(.25/np.cos(np.deg2rad(max(data_temp2['target_lat'][cluster_mask][0],data_temp2['latitude'][cluster_mask].max())))),1),\ np.round(min(data_temp2['target_lon'][cluster_mask][0],data_temp2['longitude'][cluster_mask].min())-(.25/np.cos(np.deg2rad(min(data_temp2['target_lat'][cluster_mask][0],data_temp2['latitude'][cluster_mask].min())))),1) #And keep anything within the plotting box data_temp2 = data_temp2[(data_temp2['latitude'] < N) & (data_temp2['latitude'] > S) & (data_temp2['longitude'] < E) & (data_temp2['longitude'] > W)] #Get some datetime info from the sounding_id month_str = calendar.month_abbr[int( data_temp2['sounding_id'][0].astype(str)[4:6].lstrip("0"))] day_str, year_str = data_temp2['sounding_id'][0].astype( str)[6:8].lstrip("0"), data_temp2['sounding_id'][0].astype( str)[:4].lstrip("0") hour_str, minute_str = data_temp2['sounding_id'][0].astype( str)[8:10], data_temp2['sounding_id'][0].astype(str)[10:12] #Check if the .png exists already. If not, make it! if os.path.isfile(out_dir_temp + '/' + data_temp2['production_string'][0].astype(str) + '/' + var_string + '/OCO3_' + data_temp2['production_string'][0].astype(str) + "_" + var_string + '_' + str(data_temp2['sounding_id'][0])[:8] + '_' + str(int(data_temp2['orbit'][0])) + "_" + data_temp2['target_id'][0].astype(str) + '.png'): print(out_dir_temp + '/' + data_temp2['production_string'][0].astype(str) + '/' + var_string + '/OCO3_' + data_temp2['production_string'][0].astype(str) + "_" + var_string + '_' + str(data_temp2['sounding_id'][0])[:8] + '_' + str(int(data_temp2['orbit'][0])) + "_" + data_temp2['target_id'][0].astype(str) + '.png already exists!') else: fig, ax1 = plt.subplots(figsize=[20, 20]) m1 = Basemap(llcrnrlon=W, llcrnrlat=S, urcrnrlon=E, urcrnrlat=N, epsg=3857, resolution='h') try: m1.arcgisimage(service='World_Imagery', xpixels=2000, verbose=True) except: #Sometimes this fails randomly, so try again time.sleep(20) m1.arcgisimage(service='World_Imagery', xpixels=2000, verbose=True) m1.drawmeridians(np.linspace(W, E, 6)[1:-1], labels=[0, 0, 0, 1], size=24, color='0.75') m1.drawparallels(np.linspace(N, S, 6)[1:-1], labels=[1, 0, 0, 0], size=24, color='0.75') m1.drawcoastlines() #Map Scale. Have to hack because the Basemap drawmapscale function is broken, but this should work. Cartopy doesn't even have a map scale function. lat0 = S + (N - S) * 0.04 + 0.02 #0.04 lon0 = W + (E - W) * 0.04 distance = 40. / np.cos(lat0 * np.pi / 180.) corner_buffered_m1 = m1(lon0, lat0) corner_buffered_lon, corner_buffered_lat = m1( corner_buffered_m1[0] + (distance / 2 * 1000), corner_buffered_m1[1], inverse=True) scale = m1.drawmapscale(corner_buffered_lon, corner_buffered_lat, corner_buffered_lon, corner_buffered_lat, distance, units='km', fontcolor='w', fontsize=16, yoffset=2000) scale[3].set_text(40) #Plot footprints x1, y1 = m1(data_temp2['vertex_longitude_1'], data_temp2['vertex_latitude_1']) x2, y2 = m1(data_temp2['vertex_longitude_2'], data_temp2['vertex_latitude_2']) x3, y3 = m1(data_temp2['vertex_longitude_3'], data_temp2['vertex_latitude_3']) x4, y4 = m1(data_temp2['vertex_longitude_4'], data_temp2['vertex_latitude_4']) patches = [] for i in range(len(x1)): if (x1[i] == 0.0) | (x2[i] == 0.0) | (x3[i] == 0.0) | (x4[i] == 0.0): print("Bad vertex...") else: patches += [ Polygon([(x1[i], y1[i]), (x2[i], y2[i]), (x3[i], y3[i]), (x4[i], y4[i])]) ] p = PatchCollection(patches, alpha=1.) p.set_array(data_temp2[var_temp]) if var_temp == 'dp': p.set_clim( -1 * max(np.abs(np.percentile(data_temp2[var_temp], 10)), np.abs(np.percentile(data_temp2[var_temp], 90))), max(np.abs(np.percentile(data_temp2[var_temp], 10)), np.abs(np.percentile(data_temp2[var_temp], 90)))) elif var_temp == 'aod_total': p.set_clim(0, max(0.3, np.percentile(data_temp2[var_temp], 90))) else: p.set_clim(np.percentile(data_temp2[var_temp], 10), np.percentile(data_temp2[var_temp], 90)) p.set_lw(1.0) p.set_cmap(var_cbar) ax1.add_collection(p) #Colorbar divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size=0.4, pad=0.25) if var_temp == 'aod_total': cbar = fig.colorbar(p, extend='max', cax=cax) else: cbar = fig.colorbar(p, extend='both', cax=cax) cbar.set_label(var_cbar_string, size=28, rotation=270, labelpad=35) cbar.ax.tick_params(labelsize=22) cbar.ax.yaxis.get_offset_text().set_fontsize(22) #Title title = ax1.set_title( 'OCO-3 ' + var_title_string + '\n' + data_temp2['sounding_operation_mode_string'][0].astype(str) + ' Mode (' + data_temp2['sounding_pcs_data_source_string'][0].astype(str) + '), ' + data_temp2['target_id'][0].astype(str) + ', "' + data_temp2['target_name'][0].astype(str) + '"\n' + data_temp2['production_string'][0].astype(str) + '\n' + hour_str + ':' + minute_str + ' UTC ' + day_str + ' ' + month_str + ' ' + year_str + ', Orbit ' + str(int(data_temp2['orbit'][0])), size=30, y=1.01) #Time stamp plt.text(0.99, 0.01, "Created " + str(datetime.datetime.now().day) + ' ' + calendar.month_abbr[datetime.datetime.now().month] + ' ' + str(datetime.datetime.now().year) + "\nCourtesy NASA/JPL-Caltech (R. R. Nelson)", ha='right', va='bottom', transform=ax1.transAxes, color='1.0', size=18) #Preliminary data stamp plt.text(0.01, 0.99, "PRELIMINARY (vEarly)", ha='left', va='top', transform=ax1.transAxes, color='r', size=18) #Globe inset ax2 = inset_axes(ax1, width=2., height=2.) m2 = Basemap(projection='ortho', lat_0=((N + S) / 2.), lon_0=((E + W) / 2.), resolution='l') m2.bluemarble() x1_globe, y1_globe = m2(((W + E) / 2.), ((N + S) / 2.)) m2.scatter(x1_globe, y1_globe, c='r', s=100, marker='*') #Mark the target x1_target, y1_target = m1(data_temp2['target_lon'][0], data_temp2['target_lat'][0]) ax1.scatter(x1_target, y1_target, c='r', marker="*", s=600) #Create save directory if it doesn't exist if not os.path.exists( out_dir_temp + '/' + data_temp2['production_string'][0].astype(str) + '/' + var_string): os.makedirs(out_dir_temp + '/' + data_temp2['production_string'][0].astype(str) + '/' + var_string) #Save figure print("Saving as " + out_dir_temp + '/' + data_temp2['production_string'][0].astype(str) + '/' + var_string + '/OCO3_' + data_temp2['production_string'][0].astype(str) + "_" + var_string + '_' + str(data_temp2['sounding_id'][0])[:8] + '_' + str(int(data_temp2['orbit'][0])) + "_" + data_temp2['target_id'][0].astype(str) + '.png')
elon = float(tmp[1]) plot_event = False slats.append(float(tmp[2])) slons.append(float(tmp[3])) plat1.append(float(tmp[4])) plon1.append(float(tmp[5])) plat2.append(float(tmp[6])) plon2.append(float(tmp[7])) for s in range(len(slats)): print(s + 1, len(slats)) m.drawgreatcircle(elon, elat, slons[s], slats[s], linewidth=0.5, color='gray', alpha=0.5, zorder=1) m.drawgreatcircle(plon1[s], plat1[s], plon2[s], plat2[s], linewidth=0.5, color='g', zorder=2) x1, y1 = m(slons[s], slats[s]) m.scatter(x1, y1, s=40, marker='^', facecolors='white', alpha=1, zorder=2) x, y = m(elon + 360., elat) if (i == 2): m.scatter(x, y, s=265, marker='*', facecolors='y', alpha=1, zorder=2, label='Event') m.scatter(x1, y1, s=40, marker='^', facecolors='white', alpha=1, zorder=2, label='Station') else: m.scatter(x, y, s=265, marker='*', facecolors='y', alpha=1, zorder=2) x0, y0 = -167.5, 17.5 R = 7.5 m.tissot(x0, y0, R, 100, facecolor='b', alpha=0.4, label='ULVZ')
#============================================ # set up map projection with # use low resolution coastlines. map = Basemap(projection='ortho', lat_0=35, lon_0=120, resolution='l') # draw coastlines, country boundaries, fill continents. map.drawcoastlines(linewidth=0.25) map.drawcountries(linewidth=0.25) # draw the edge of the map projection region (the projection limb) map.drawmapboundary(fill_color='#689CD2') # draw lat/lon grid lines every 30 degrees. map.drawmeridians(np.arange(0, 360, 30)) map.drawparallels(np.arange(-90, 90, 30)) # Fill continent wit a different color map.fillcontinents(color='#BF9E30', lake_color='#689CD2', zorder=0) # compute native map projection coordinates of lat/lon grid. x, y = map(lons, lats) max_pop = max(pops) # Plot each city in a loop. # Set some parameters size_factor = 80.0 y_offset = 15.0 rotation = 30 for i, j, k, name in zip(x, y, pops, names): size = size_factor * k / max_pop cs = map.scatter(i, j, s=size, marker='o', color='#FF5600') plt.text(i, j + y_offset, name, rotation=rotation, fontsize=10) plt.title('Major Cities in Asia & Population') plt.show()
from mpl_toolkits.basemap import Basemap m = Basemap(projection='merc', llcrnrlat=40.496044, urcrnrlat=40.915256, llcrnrlon=-74.255735, urcrnrlon=-73.700272, resolution='i') m.drawmapboundary(fill_color='#85A6D9') m.drawcoastlines(color='#6D5F47', linewidth=.4) m.drawrivers(color='#6D5F47', linewidth=.4) # Convert the longitudes and latitudes to list longitudes = combined['lon'].tolist() latitudes = combined['lat'].tolist() m.scatter(longitudes, latitudes, s=20, zorder=2, latlon=True) plt.show() ## 10. Plotting Out Statistics ## from mpl_toolkits.basemap import Basemap m = Basemap(projection='merc', llcrnrlat=40.496044, urcrnrlat=40.915256, llcrnrlon=-74.255735, urcrnrlon=-73.700272, resolution='i') m.drawmapboundary(fill_color='#85A6D9') m.drawcoastlines(color='#6D5F47', linewidth=.4) m.drawrivers(color='#6D5F47', linewidth=.4)
misr_dset = f['/Target/Data_Fields/MISR_AN_Red_Radiance'] misr_data = misr_dset[:].astype(np.float64) ds_lat = f['/Geolocation/Latitude'] lat = ds_lat[:].astype(np.float64) ds_lon = f['/Geolocation/Longitude'] lon = ds_lon[:].astype(np.float64) # Plot data. data = misr_data data[data == -999] = np.nan datam = np.ma.masked_array(data, np.isnan(data)) m = Basemap(projection='cyl', resolution='l', llcrnrlat=np.min(lat), urcrnrlat=np.max(lat), llcrnrlon=np.min(lon), urcrnrlon=np.max(lon)) slat = (np.ceil(np.max(lat)) - np.floor(np.min(lat))) / 6.0 slon = (np.ceil(np.max(lon)) - np.floor(np.min(lon))) / 6.0 m.drawcoastlines(linewidth=0.5) m.drawparallels(np.arange(np.floor(np.min(lat)), np.ceil(np.max(lat)), slat), labels=[1, 0, 0, 0]) m.drawmeridians(np.arange(np.floor(np.min(lon)), np.ceil(np.max(lon)), slon), labels=[0, 0, 0, 1]) # m.pcolormesh(lon, lat, datam, latlon=True, cmap='jet') m.scatter(lon, lat, c=datam, s=1, edgecolors=None, linewidth=0) fig = plt.gcf() fig.suptitle('{0}'.format(file_name)) pngfile = file_name + '.py.png' fig.savefig(pngfile) print("--- %s seconds ---" % (time.time() - start_time))
def main(): # constantes RUTA_CARPETA = "/home/jorge/Documents/Research/proyectoCaborca" # fecha actual fechaActual = strftime("%Y-%m-%d") # fecha -1 anio, mes, dia = generarDiaAnterior(fechaActual) # generar ruta de archivos # rutaCarpetaDeArchivos = "{}/estaciones/{}-{:02d}-{:02d}".format(RUTA_CARPETA, anio, mes, dia) # ruta carpeta rutaCarpetaEstacionesMapas = "******".format(RUTA_CARPETA, anio, mes, dia) # crear carpeta de mapas if not os.path.exists(rutaCarpetaEstacionesMapas): os.mkdir(rutaCarpetaEstacionesMapas) else: print("***** Carpeta ya existe") # datos de estaciones rutaArchivoEstaciones = "{}/estaciones/coor_est.csv".format(RUTA_CARPETA) dataEstaciones = pd.read_csv(rutaArchivoEstaciones) # ciclo # generar frame frames = [] for i in range(1,6,1): print("valor de i:", i) # datos a procesar rutaDatosEstaciones = "{}/estaciones/{}-{:02d}-{:02d}/{}.csv".format(RUTA_CARPETA, anio, mes, dia,i) print(rutaDatosEstaciones) dataTemp = pd.read_csv(rutaDatosEstaciones) print(dataTemp.head()) # valor de longitud # latTemp = dataEstaciones.loc[dataEstaciones["ID"]==i]["Lat"] latTemp = dataEstaciones.iloc[i-1]["Lat"] print("***** lat", latTemp) dataTemp["Lat"] = latTemp # valor de latitud # lonTemp = dataEstaciones.loc[dataEstaciones["ID"]==i]["Long"] lonTemp = dataEstaciones.iloc[i-1]["Long"] dataTemp["Lon"] = lonTemp print("***** Lon", lonTemp) frames.append(dataTemp) print(dataTemp.head()) # merge frames data = pd.concat(frames) # array columnas a evaluar arrayColumns = ["PM1_1M", "PM1_5M","PM1_15M","PM2P5_1M","PM2P5_5M","PM2P5_15M","PM2P5_1H","PM1_1H","PM10_1M","PM10_5M","PM10_15M","PM10_1H"] # tiempos a mapear tiempos = np.array(data["Time"]) tiempos = np.unique(tiempos) # ciclo de procesamiento for t in tiempos: # clasificar valores dataProcesamiento = data.loc[data["Time"] == t] for columna in arrayColumns: # determinar valores de x y y x_values = np.array(dataProcesamiento["Lon"]) y_values = np.array(dataProcesamiento["Lat"]) # ordenar valores x_values.sort() y_values.sort() # print print(x_values) print(y_values) # limites min y max LONG_MIN = x_values[0] LONG_MAX = x_values[-1] LAT_MIN = y_values[0] LAT_MAX = y_values[-1] # limites longitud > -115.65 y < -107.94 dataProcesamiento = dataProcesamiento.loc[dataProcesamiento['Lon'] > LONG_MIN] dataProcesamiento = dataProcesamiento.loc[dataProcesamiento['Lon'] < LONG_MAX] # limites latitud > 25.41 y < 33.06 dataProcesamiento = dataProcesamiento.loc[dataProcesamiento['Lat'] > LAT_MIN] dataProcesamiento = dataProcesamiento.loc[dataProcesamiento['Lat'] < LAT_MAX] # obtener valores de x, y lons = np.array(dataProcesamiento['Lon']) lats = np.array(dataProcesamiento['Lat']) # iniciar la gráfica #plt.clf() # agregar locación de estaciones xC = np.array(dataEstaciones['Long']) yC = np.array(dataEstaciones['Lat']) m = Basemap(projection='mill',llcrnrlat=LAT_MIN,urcrnrlat=LAT_MAX,llcrnrlon=LONG_MIN,urcrnrlon=LONG_MAX,resolution='h') # generar lats, lons x, y = m(lons, lats) # numero de columnas y filas numCols = len(x) numRows = len(y) # generar xi, yi xi = np.linspace(x.min(), x.max(), numCols) yi = np.linspace(y.min(), y.max(), numRows) # generar el meshgrid xi, yi = np.meshgrid(xi, yi) # generar zi z = np.array(dataProcesamiento[columna]) zi = gd((x,y), z, (xi,yi), method='cubic') # generar clevs stepVariable = 1 step = (z.max() - z.min()) / 10 # verificar el valor del intervalo if step <= 1: stepVariable = 1 clevs = np.linspace(z.min(), z.max() + stepVariable , 10) #clevs = [1,2,3,4,5,6,7,8,9,10] # contour plot cs = m.contourf(xi,yi,zi, clevs, zorder=5, alpha=0.5, cmap='PuBu') # agregar archivo shape de estados m.readshapefile('../shapes/Estados', 'Estados') # agregar puntos de estaciones m.scatter(xC, yC, latlon=True,s=1, marker='o', color='r', zorder=25) # colorbar cbar = m.colorbar(cs, location='right', pad="5%") cbar.set_label('mm') tituloTemporalParaElMapa = "{} {}-{:02d}-{:02d}".format(columna,anio,mes,dia) (tituloTemporalParaElMapa) # Mac /Users/jorgemauricio/Documents/Research/proyectoGranizo/Maps/{}_{}.png # Linux /home/jorge/Documents/Research/proyectoGranizo/Maps/{}_{}.png nombreTemporalParaElMapa = "{}/estaciones/maps/{}-{:02d}-{:02d}/{}.png".format(RUTA_CARPETA, anio, mes, dia, columna) plt.annotate('@2018 INIFAP', xy=(-109,29), xycoords='figure fraction', xytext=(0.45,0.45), color='g', zorder=50) plt.savefig(nombreTemporalParaElMapa, dpi=300) print('****** Genereate: {}'.format(nombreTemporalParaElMapa))
m2 = Basemap(projection='hammer', llcrnrlon=-180, urcrnrlon=180, llcrnrlat=-90, urcrnrlat=90, resolution='c', lon_0=0) # Draw lat/lon grid lines every 30 degrees. # m2.drawmeridians(np.arange(-180, 180, 30)) m2.drawparallels(np.arange(-90, 90, 30), labels=[1, 1, 0, 1]) # Compute native map projection coordinates of lat/lon grid. x, y = m2(lon, lat) x1, y1 = m2(lon1, lat1) # Contour data over the map. cs = m2.contourf(x, y, d_hat2_Eu) cs = m2.scatter(x1, y1, color='red', s=30) fig.savefig('./Figures/EuSCMS_ring_Step0_Eu_noise_hammer.pdf') fig = plt.figure(figsize=(14, 8)) Eu_step = SCMS_Eu_log2.shape[2] - 1 lon1 = SCMS_Eu_log2[:, 0, Eu_step] lat1 = SCMS_Eu_log2[:, 1, Eu_step] m2 = Basemap(projection='hammer', lat_0=30, lon_0=0) # Draw lat/lon grid lines every 30 degrees. # m2.drawmeridians(np.arange(-180, 180, 30)) m2.drawparallels(np.arange(-90, 90, 30), labels=[1, 1, 0, 1]) # Compute native map projection coordinates of lat/lon grid. x, y = m2(lon, lat) x1, y1 = m2(lon1, lat1) # Contour data over the map. cs = m2.contourf(x, y, d_hat2_Eu)
def map_nwp_tracks_per_storm(idai_an_file, ken_an_file, outfile, region, cat, name, startdate, enddate): """Plots a map of storm tracks in the Southern Hemisphere Plots a map of storm tracks for one storm in the Southern Hemisphere from a list of several TRACK files (e.g. one per year) that have been reformatted to suit Python Plots all forecasts of one storm, and the reanalysis and ibtracs tracks. Plots the tracks so that they change colour from lighter to darker with time Note: the colormap used is hardcoded in the function (where 'colors' is assigned) Function takes a list of filenames as input argument""" # set up map of region #if region == "SH": #lat1 = 30 #lat2 = -60 #lon1 = -25 #lon2 = 335 #elif region == "SIO": #lat1=30 #lat2=-55 #lon1=-10 #lon2=130 lat1 = 0 lat2 = -30 lon1 = 20 lon2 = 60 fig = plt.figure(figsize=(6, 3)) ax = fig.add_axes([0.05, 0.1, 0.9, 0.96]) m = Basemap(llcrnrlon=lon1, llcrnrlat=lat2, urcrnrlon=lon2, urcrnrlat=lat1, projection='mill', resolution='l') RSMClats = [-40, 0, 0, -40] RSMClons = [30, 30, 90, 90] #draw_rectangle(RSMClats,RSMClons,m) #m.bluemarble(alpha=0.8) m.drawcoastlines(linewidth=0.6, color='k') m.drawcountries(linewidth=0.6, color='k') #m.fillcontinents(color='lightgray', alpha=0.4) hurricane = get_hurricane_symbol() idai_an_data = np.genfromtxt(idai_an_file, dtype=float, skip_header=1) # count how many track points this storm has no_points = len(idai_an_data[:, 0]) # set up an array to hold the lat and lon of each point of this storm track_coords = np.zeros((no_points, 2)) # get the lat and lons from the track file for this storm only track_coords[:, 0] = idai_an_data[:, 7] # longitudes track_coords[:, 1] = idai_an_data[:, 8] # latitudes # To have the line changing colour from start to finish, split the coordinates into segments points = np.array([track_coords[:, 0], track_coords[:, 1]]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) #colors = cm.OrRd(np.linspace(0.2, 1, no_points)) colors = cm.PuBu(np.linspace(0.25, 1, no_points)) #iterate over each segment of this track for p, cl in zip(range(no_points - 1), colors): if p < 61: z = 10 elif p > 61: z = 9 ## need to separate the x and y values for each segment, and plot each segment on the map xarr = [] yarr = [] xarr.append(segments[p][0][0]) xarr.append(segments[p][1][0]) yarr.append(segments[p][0][1]) yarr.append(segments[p][1][1]) x, y = m(xarr, yarr) #m.plot(x, y, linewidth=1.5, color=cl,zorder=z) pp = range(0, no_points, 4) colors2 = cm.PuBu(np.linspace(0, 1, 24)) print pp for p, cl in zip(pp, colors2): if 37 < p < 61: xx, yy = m(idai_an_data[p, 7], idai_an_data[p, 8]) #m.scatter(xx,yy,marker=hurricane,edgecolors='steelblue',facecolors='None',s=200,linewidth=1.5,zorder=11) #xs,ys=m(idai_an_data[0,7],idai_an_data[0,8]) #m.scatter(xs,ys,marker=hurricane,edgecolors='orange',facecolors='None',s=50,linewidth=1) ken_an_data = np.genfromtxt(ken_an_file, dtype=float, skip_header=1) no_points = len(ken_an_data[:, 0]) # set up an array to hold the lat and lon of each point of this storm track_coords = np.zeros((no_points, 2)) # get the lat and lons from the track file for this storm only track_coords[:, 0] = ken_an_data[:, 7] # longitudes track_coords[:, 1] = ken_an_data[:, 8] # latitudes # To have the line changing colour from start to finish, split the coordinates into segments points = np.array([track_coords[:, 0], track_coords[:, 1]]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) colors = cm.PuBu(np.linspace(0.2, 1, no_points)) # iterate over each segment of this track for p, cl in zip(range(no_points - 1), colors): ## need to separate the x and y values for each segment, and plot each segment on the map xarr = [] yarr = [] xarr.append(segments[p][0][0]) xarr.append(segments[p][1][0]) yarr.append(segments[p][0][1]) yarr.append(segments[p][1][1]) x, y = m(xarr, yarr) m.plot(x, y, linewidth=1.5, color=cl) if 12 < p < 20: xx, yy = m(ken_an_data[p, 7], ken_an_data[p, 8]) m.scatter(xx, yy, marker=hurricane, edgecolors='steelblue', facecolors='None', s=200, linewidth=1.5, zorder=11) #xs, ys = m(ken_an_data[0, 7], ken_an_data[0, 8]) #m.scatter(xs, ys, marker=hurricane, edgecolors='skyblue', facecolors='None', s=50, linewidth=1) #save and close the plot fig.subplots_adjust(wspace=0) plt.savefig(outfile, bbox_inches='tight', pad_inches=0.05, dpi=500) plt.close()
axins.set_xlim(-53.75, -51.75) axins.set_ylim(46, 48) #axins.set_edgecolor('r') plt.xticks(visible=False) plt.yticks(visible=False) map2 = Basemap(llcrnrlon=-53.75, llcrnrlat=46, urcrnrlon=-51.75,urcrnrlat=48, ax=axins, resolution='f') x,y = map2(*np.meshgrid(lon,lat)) #c = map2.contour(x, y, -Z, v2, colors='k'); c = map2.contourf(x, y, -Z, v2, cmap=plt.cm.PuBu_r); map2.fillcontinents(color='grey'); map2.drawparallels(np.arange(-46,48,1)) map2.drawmeridians(np.arange(-54, -52, 1)) ## Stn27 on map lat_27 = 47.5373 lon_27 = -52.5838 x, y = map2(lon_27, lat_27) map2.scatter(x,y,5,marker='p',color='red') plt.text(x, y, ' Stn 27', horizontalalignment='left', verticalalignment='center', fontsize=10, color='red', fontweight='bold') # Plot inset lines mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="r") #### ---- Save Figure ---- #### fig.set_size_inches(w=5, h=5) fig.set_dpi(300) fig.savefig(fig_name) #plt.show()
map.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10) # Draw meridians meridians = np.arange(-6., 10., 2.) map.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10) map.drawcoastlines() map.drawcountries() map.drawmapboundary() map.drawrivers() # Draw scatter plot with all cities x, y = map(lons, lats) map.scatter(x, y, s=size, alpha=0.6, c=size, norm=colors.LogNorm(vmin=1, vmax=max(size)), cmap='hsv') map.colorbar(location="bottom", pad="4%") # Draw scatter plot of cities with highiest number of workplaces x1, y1 = map(top_industry_lons, top_industry_lats) map.scatter(x1, y1, c="black") for i in range(len(top_industry_names)): plt.annotate(top_industry_names[i], xy=(map(top_industry_lons[i] + 0.25, top_industry_lats[i])), fontsize=25) plt.title("French Industry from a bird's eye view",
def marksOnMap(lons, lats, vals=None, vmin=None, vmax=None, imageWidth=None, imageHeight=None, outFile=None, projection='cyl', cmap=M.cm.jet, sizes=80, colors='b', marker='o', makeFigure=False, times=None, timeDelta=None, borders=[0., -90., 360., 90.], autoBorders=True, borderSlop=10., meridians=[0, 360, 60], parallels=[-60, 90, 30], **options ): lons = normalizeLons(lons) if imageWidth is not None: makeFigure = True if projection is None: projection = 'cyl' # ensureItems(options, {'xlabel': 'Longitude (deg)', 'ylabel': 'Latitude (deg)', ensureItems(options, { \ 'title': 'Markers on a Map', 'dpi': 100, 'imageWidth': imageWidth or 1024, 'imageHeight': imageHeight or 768}) if autoBorders: borders = [min(lons), min(lats), max(lons), max(lats)] borders = roundBorders(borders, borderSlop) m = Basemap(borders[0], borders[1], borders[2], borders[3], \ projection=projection, lon_0=N.average([lons[0], lons[-1]])) if makeFigure: dpi = float(options['dpi']) width = float(imageWidth) / dpi if imageHeight is None: height = width * m.aspect else: height = float(imageHeight) / dpi f = M.figure(figsize=(width,height)).add_axes([0.1,0.1,0.8,0.8],frameon=True) if vals is not None: if vmin is None or vmin == 'auto': vmin = min(vals) warn('auto scale min is %f' % vmin) else: vmin = float(vmin) if vmax is None or vmax == 'auto': vmax = max(vals) else: vmax = float(vmax) warn('auto scale max is %f' % vmax) vrange = (vmax - vmin) / 255. colors = N.array([(val - vmin)/vrange for val in vals]) if timeDelta is not None: if times is not None: times = map(mkTime, times) timeDelta = float(timeDelta) * 60. start = roundTime(times[0], 'down', timeDelta) end = roundTime(times[-1], 'up', timeDelta) plotTimes = arange(start, end+timeDelta, timeDelta) else: timeDelta = None g = m.scatter(lons, lats, s=sizes, c=colors, marker=marker, cmap=cmap, vmin=vmin, vmax=vmax, **validCmdOptions(options, 'map.scatter')) m.drawcoastlines() m.drawmeridians(range(meridians[0], meridians[1], meridians[2]), labels=[0,0,0,1]) m.drawparallels(range(parallels[0], parallels[1], parallels[2]), labels=[1,1,1,1]) M.colorbar(g) evalKeywordCmds(options) if outFile: M.savefig(outFile, **validCmdOptions(options, 'savefig'))
i=0 for row in grid_center_xys: row_center_xs = [coord[0] for coord in row] row_center_ys = [coord[1] for coord in row] center_xs = center_xs + row_center_xs center_ys = center_ys + row_center_ys if (290 <= i < 340 ): for coord in row: center_x = coord[0] center_y = coord[1] grid_center_lon, grid_center_lat = m(center_x, center_y, inverse = True) grid_center_coords = (grid_center_lat,grid_center_lon) sample_locn = (sample_lat, sample_lon) distance_to_sample_locn = vincenty(sample_locn,grid_center_coords) m.scatter(center_x,center_y, color = 'g', marker = '.',zorder=300) distance = axes.text(center_x,center_y, str(round(distance_to_sample_locn,1)), color='k') i+=1 #draw the arctic circle if include_arctic_circle == True: arctic_circle = [] for lon in range(0,361,1): ac_endpoint = [66.55, lon] arctic_circle.append(ac_endpoint) ac_endpoints = np.array(arctic_circle) ac_lats = ac_endpoints[:,0] ac_lons = ac_endpoints[:,1] x,y = m(ac_lons,ac_lats) ac = m.plot(x,y, color = 'k', linewidth = 2.5,)
def geoplot(data=None, lon=None, lat=None, **kw): '''Show 2D data in a lon-lat plane. Parameters ----------- data: array of shape (n_lat, n_lon), or [u_array, v_array]-like for (u,v) data or None(default) when only plotting the basemap. lon: n_lon length vector or None(default). lat: n_lat length vector or None(default). kw: dict parameters related to basemap or plot functions. Basemap related parameters: ---------------------------- basemap_kw: dict parameter in the initialization of a Basemap. proj or projection: map projection name (default='moll') popular projections: 'ortho', 'np'(='nplaea'), 'sp'(='splaea') and other projections given from basemap. lon_0: map center longitude (None as default). lat_0: map center latitude (None as default). lonlatcorner: (llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat). boundinglat: latitude at the map out boundary (None as default). basemap_round or round: True(default) or False. fill_continents: bool value (False as default). continents_kw: dict parameter used in the Basemap.fillcontinents method. continents_color: color of continents ('0.33' as default). lake_color: color of lakes ('none' as default). ocean_color: color of ocean (None as default). coastlines_kw: dict parameter used in the Basemap.drawcoastlines method. coastlines_color: color of coast lines ('0.33' as default). gridOn: bool value (True as default). gridLabelOn: bool value (False as default). parallels_kw: dict parameters used in the Basemap.drawparallels method. parallels: parallels to be drawn (None as default). parallels_color: color of parallels ('0.5' as default). parallels_labels:[0,0,0,0] or [1,0,0,0]. meridians_kw: dict parameters used in the Basemap.drawmeridians method. meridians: meridians to be drawn (None as default). meridians_color: color of meridians (parallels_color as default). meridians_labels: [0,0,0,0] or [0,0,0,1]. lonlatbox: None or (lon_start, lon_end, lat_start, lat_end). lonlatbox_kw: dict parameters in the plot of lon-lat box. lonlatbox_color: General plot parameters: ------------------------- ax: axis object, default is plt.gca() plot_type: a string of plot type from ('pcolor', 'pcolormesh', 'imshow', 'contourf', 'contour', 'quiver', 'scatter') or None(default). cmap: pyplot colormap. clim: a tuple of colormap limit. levels: sequence, int or None (default=None) plot_kw: dict parameters used in the plot functions. Pcolor/Pcolormesh related parameters: ------------------------------- rasterized: bool (default is True). Imshow related parameters --------------------------- origin: 'lower' or 'upper'. extent: horizontal range. interpolation: 'nearest' (default) or 'bilinear' or 'cubic'. Contourf related parameters: ------------------------------- extend: 'both'(default). Contour related parameters: ---------------------------- label_contour: False(default) or True. Whether to label contours or not. colors: contour color (default is 'gray'). Quiver plot related parameters: -------------------------------- stride: stride along lon and lat. stride_lon: stride along lon. stride_lat: stride along lat. quiver_scale: quiver scale. quiver_color: quiver color. sparse_polar_grids: bool, default is True. quiver_kw: dict parameters used in the plt.quiver function. hide_qkey: bool value, whether to show the quiverkey plot. qkey_X: X parameter in the plt.quiverkey function (default is 0.85). qkey_Y: Y parameter in the plt.quiverkey function (default is 1.02). qkey_U: U parameter in the plt.quiverkey function (default is 2). qkey_label: label parameter in the plt.quiverkey function. qkey_labelpos: labelpos parameter in the plt.quiverkey function. qkey_kw: dict parameters used in the plt.quiverkey function. Scatter related parameters: ------------------------------ scatter_data: None(default) or (lonvec, latvec). Hatch plot related parameters: ---------------------------------- hatches: ['///'] is default. Colorbar related parameters: ------------------------------- hide_cbar: bool value, whether to show the colorbar. cbar_type: 'vertical'(shorten as 'v') or 'horizontal' (shorten as 'h'). cbar_extend: extend parameter in the plt.colorbar function. 'neither' as default here. cbar_size: default '2.5%' for vertical colorbar, '5%' for horizontal colorbar. cbar_pad: default 0.1 for vertical colorbar, 0.4 for horizontal colorbar. cbar_kw: dict parameters used in the plt.colorbar function. units: str long_name: str Returns -------- basemap object if only basemap is plotted. plot object if data is shown. ''' # target axis ax = kw.pop('ax', None) if ax is not None: plt.sca(ax) if isinstance(data, xr.DataArray): data_array = data.copy() data = data_array.values if np.any(np.isnan(data)): data = ma.masked_invalid(data) if lon is None: try: lonname = [ s for s in data_array.dims if s in ('lon', 'longitude', 'X') ][0] except IndexError: lonname = [s for s in data_array.dims if 'lon' in s][0] lon = data_array[lonname] if lat is None: try: latname = [ s for s in data_array.dims if s in ('lat', 'latitude', 'Y') ][0] except IndexError: latname = [s for s in data_array.dims if 'lat' in s][0] lat = data_array[latname] # guess data name try: data_name = data_array.attrs['long_name'] except KeyError: try: data_name = data_array.name except AttributeError: data_name = '' # guess data units try: data_units = data_array.attrs['units'] except KeyError: data_units = '' # copy the original data elif data is not None: try: data = data.copy() except: try: # data has two components(u,v) data = (data[0].copy(), data[1].copy()) except: pass if lon is not None: lon = lon.copy() if lat is not None: lat = lat.copy() # #### basemap parameters # basemap kw parameter basemap_kw = kw.pop('basemap_kw', {}) # projection # proj = kw.pop('proj', 'cyl') # proj = kw.pop('proj', 'moll') proj = kw.pop('proj', 'hammer') proj = kw.pop('projection', proj) # projection overrides the proj parameter # short names for nplaea and splaea projections if proj in ('npolar', 'polar', 'np'): proj = 'nplaea' elif proj in ('spolar', 'sp'): proj = 'splaea' # lon_0 lon_0 = kw.pop('lon_0', None) if lon_0 is None: if lon is not None: if np.isclose(np.abs(lon[-1] - lon[0]), 360): lon_0 = (lon[0] + lon[-2]) / 2.0 else: lon_0 = (lon[0] + lon[-1]) / 2.0 else: # dummy = np.linspace(0, 360, data.shape[1]+1)[0:-1] # lon_0 = ( dummy[0] + dummy[-1] )/2.0 lon_0 = 180 # elif proj in ('moll', 'cyl', 'hammer', 'robin'): # lon_0 = 180 # elif proj in ('ortho','npstere', 'nplaea', 'npaeqd', 'spstere', 'splaea', 'spaeqd'): # lon_0 = 0 else: # lon_0 is specified if lon is not None and proj in ('moll', 'cyl', 'hammer'): # correct the lon_0 so that it is at the edge of a grid box lon_0_data = (lon[0] + lon[-1]) / 2.0 d_lon = lon[1] - lon[0] d_lon_0 = lon_0 - lon_0_data lon_0 = float(int(d_lon_0 / d_lon)) * d_lon + lon_0_data # lat_0 lat_0 = kw.pop('lat_0', None) if lat_0 is None: if lat is not None: lat_0 = (lat[0] + lat[-1]) / 2.0 elif proj in ('ortho', ): lat_0 = 45 # lonlatcorner = (llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat) lonlatcorner = kw.pop('lonlatcorner', None) if lonlatcorner is not None: llcrnrlon = lonlatcorner[0] urcrnrlon = lonlatcorner[1] llcrnrlat = lonlatcorner[2] urcrnrlat = lonlatcorner[3] else: llcrnrlon = None urcrnrlon = None llcrnrlat = None urcrnrlat = None llcrnrlon = basemap_kw.pop('llcrnrlon', llcrnrlon) urcrnrlon = basemap_kw.pop('urcrnrlon', urcrnrlon) llcrnrlat = basemap_kw.pop('llcrnrlat', llcrnrlat) urcrnrlat = basemap_kw.pop('urcrnrlat', urcrnrlat) if llcrnrlon is None and urcrnrlon is None and llcrnrlat is None and urcrnrlat is None: lonlatcorner = None else: lonlatcorner = (llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat) # boundinglat boundinglat = kw.pop('boundinglat', None) if boundinglat is None: if proj in ('npstere', 'nplaea', 'npaeqd'): boundinglat = 30 elif proj in ('spstere', 'splaea', 'spaeqd'): boundinglat = -30 # basemap round: True or False if proj in ('npstere', 'nplaea', 'npaeqd', 'spstere', 'splaea', 'spaeqd'): basemap_round = kw.pop('basemap_round', True) else: basemap_round = kw.pop('basemap_round', False) basemap_round = kw.pop('round', basemap_round) # base map proj = basemap_kw.pop('projection', proj) lon_0 = basemap_kw.pop('lon_0', lon_0) lat_0 = basemap_kw.pop('lat_0', lat_0) boundinglat = basemap_kw.pop('boundinglat', boundinglat) basemap_round = basemap_kw.pop('round', basemap_round) m = Basemap(projection=proj, lon_0=lon_0, lat_0=lat_0, boundinglat=boundinglat, round=basemap_round, llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, **basemap_kw) # fill continents or plot coast lines fill_continents = kw.pop('fill_continents', False) if fill_continents: # use Basemap.fillcontinents method continents_kw = kw.pop('continents_kw', {}) continents_color = kw.pop('continents_color', '0.33') continents_color = continents_kw.pop('color', continents_color) lake_color = kw.pop('lake_color', 'none') lake_color = continents_kw.pop('lake_color', lake_color) m.fillcontinents(color=continents_color, lake_color=lake_color, **continents_kw) # else: draw_coastlines = kw.pop('draw_coastlines', not fill_continents) if draw_coastlines: # use Basemap.drawcoastlines method coastlines_kw = kw.pop('coastlines_kw', {}) coastlines_color = kw.pop('coastlines_color', '0.33') coastlines_color = coastlines_kw.pop('color', coastlines_color) coastlines_lw = kw.pop('coastlines_lw', 0.5) coastlines_lw = coastlines_kw.pop('lw', coastlines_lw) m.drawcoastlines(color=coastlines_color, linewidth=coastlines_lw, **coastlines_kw) ocean_color = kw.pop('ocean_color', None) if ocean_color is not None: m.drawmapboundary(fill_color=ocean_color) # parallels gridOn = kw.pop('gridOn', True) gridLabelOn = kw.pop('gridLabelOn', False) parallels_kw = kw.pop('parallels_kw', {}) # parallels = kw.pop('parallels', np.arange(-90,91,30)) parallels = kw.pop('parallels', None) parallels = parallels_kw.pop('parallels', parallels) parallels_color = kw.pop('parallels_color', '0.5') parallels_color = parallels_kw.pop('color', parallels_color) parallels_lw = kw.pop('parallels_lw', 0.5) parallels_lw = parallels_kw.pop('lw', parallels_lw) parallels_labels = kw.pop('parallels_labels', None) parallels_labels = parallels_kw.pop('labels', parallels_labels) if parallels_labels is None: if gridLabelOn: parallels_labels = [1, 0, 0, 0] else: parallels_labels = [0, 0, 0, 0] if parallels is not None: m.drawparallels(parallels, color=parallels_color, labels=parallels_labels, linewidth=parallels_lw, **parallels_kw) elif gridOn: m.drawparallels(np.arange(-90, 91, 30), color=parallels_color, linewidth=parallels_lw, labels=parallels_labels, **parallels_kw) # meridians meridians_kw = kw.pop('meridians_kw', {}) # meridians = kw.pop('meridians', np.arange(-180, 360, 30)) meridians = kw.pop('meridians', None) meridians = meridians_kw.pop('meridians', meridians) meridians_color = kw.pop('meridians_color', parallels_color) meridians_color = meridians_kw.pop('color', meridians_color) meridians_lw = kw.pop('meridians_lw', parallels_lw) meridians_lw = meridians_kw.pop('lw', meridians_lw) meridians_labels = kw.pop('meridians_labels', None) meridians_labels = meridians_kw.pop('labels', meridians_labels) if meridians_labels is None: if gridLabelOn: if proj in ('npstere', 'nplaea', 'npaeqd', 'spstere', 'splaea', 'spaeqd'): meridians_labels = [1, 1, 0, 0] elif proj in ('cyl', ): meridians_labels = [0, 0, 0, 1] else: meridians_labels = [0, 0, 0, 0] print('Meridian are not labeled.') else: meridians_labels = [0, 0, 0, 0] if meridians is not None: m.drawmeridians(meridians, color=meridians_color, labels=meridians_labels, linewidth=meridians_lw, **meridians_kw) elif gridOn: m.drawmeridians(np.arange(0, 360, 30), color=meridians_color, labels=meridians_labels, linewidth=meridians_lw, **meridians_kw) # lonlatbox lonlatbox = kw.pop('lonlatbox', None) if lonlatbox is not None: lonlon = np.array([ np.linspace(lonlatbox[0], lonlatbox[1], 100), lonlatbox[1] * np.ones(100), np.linspace(lonlatbox[1], lonlatbox[0], 100), lonlatbox[0] * np.ones(100) ]).ravel() latlat = np.array([ lonlatbox[2] * np.ones(100), np.linspace(lonlatbox[2], lonlatbox[3], 100), lonlatbox[3] * np.ones(100), np.linspace(lonlatbox[3], lonlatbox[2], 100) ]).ravel() lonlatbox_kw = kw.pop('lonlatbox_kw', {}) lonlatbox_color = kw.pop('lonlatbox_color', 'k') lonlatbox_color = lonlatbox_kw.pop('color', lonlatbox_color) m.plot(lonlon, latlat, latlon=True, color=lonlatbox_color, **lonlatbox_kw) # scatter scatter_data = kw.pop('scatter_data', None) if scatter_data is not None: # L = data.astype('bool') # marker_color = kw.pop('marker_color', 'k') # plot_obj = m.scatter(X[L], Y[L], color=marker_color, **kw) lonvec, latvec = scatter_data plot_obj = m.scatter(lonvec, latvec, **kw) # #### stop here and return the map object if data is None if data is None: return m # data prepare input_data_have_two_components = isinstance(data, tuple) \ or isinstance(data, list) if input_data_have_two_components: # input data is (u,v) or [u, v] where u, v are ndarray and two components of a vector assert len( data) == 2, 'quiver data must contain only two componets u and v' u = data[0].squeeze() v = data[1].squeeze() assert u.ndim == 2, 'u component data must be two dimensional' assert v.ndim == 2, 'v component data must be two dimensional' data = np.sqrt(u**2 + v**2) # calculate wind speed else: # input data is a ndarray data = data.squeeze() assert data.ndim == 2, 'Input data must be two dimensional!' # lon if lon is None: # lon = np.linspace(0, 360, data.shape[1]+1)[0:-1] # lon_edge = np.hstack(( # lon[0]*2 - lon[1], # lon, # lon[-1]*2 - lon[-2])) # lon_edge = ( lon_edge[:-1] + lon_edge[1:] )/2.0 lon_edge = np.linspace(lon_0 - 180, lon_0 + 180, data.shape[1] + 1) lon = (lon_edge[:-1] + lon_edge[1:]) / 2.0 else: # lon is specified if np.isclose(np.abs(lon[-1] - lon[0]), 360): # first and last longitude point to the same location: remove the last longitude lon = lon[:-1] data = data[:, :-1] if input_data_have_two_components: u = u[:, :-1] v = v[:, :-1] if (not np.isclose(lon_0, (lon[0] + lon[-1]) / 2.0) and proj in ('moll', 'cyl', 'hammer', 'robin')): # lon_0 not at the center of lon, need to shift grid lon_west_end = lon_0 - 180 + ( lon[1] - lon[0]) / 2.0 # longitude of west end # make sure the longitude of west end within the lon if lon_west_end < lon[0]: lon_west_end += 360 elif lon_west_end > lon[-1]: lon_west_end -= 360 data, lon_shift = shiftgrid(lon_west_end, data, lon, start=True) if input_data_have_two_components: u, lon_shift = shiftgrid(lon_west_end, u, lon, start=True) v, lon_shift = shiftgrid(lon_west_end, v, lon, start=True) lon = lon_shift if lon[0] < -180: lon += 360 elif lon[-1] >= 540: lon -= 360 lon_hstack = np.hstack( (2 * lon[0] - lon[1], lon, 2 * lon[-1] - lon[-2])) lon_edge = (lon_hstack[:-1] + lon_hstack[1:]) / 2.0 # lat if lat is None: lat_edge = np.linspace(-90, 90, data.shape[0] + 1) lat = (lat_edge[:-1] + lat_edge[1:]) / 2.0 else: lat_hstack = np.hstack( (2 * lat[0] - lat[1], lat, 2 * lat[-1] - lat[-2])) lat_edge = (lat_hstack[:-1] + lat_hstack[1:]) / 2.0 lat_edge[lat_edge > 90] = 90 lat_edge[lat_edge < -90] = -90 Lon, Lat = np.meshgrid(lon, lat) X, Y = m(Lon, Lat) Lon_edge, Lat_edge = np.meshgrid(lon_edge, lat_edge) X_edge, Y_edge = m(Lon_edge, Lat_edge) # ###### plot parameters # plot_type plot_type = kw.pop('plot_type', None) if plot_type is None: if input_data_have_two_components: plot_type = 'quiver' # elif ( proj in ('cyl',) # and lonlatcorner is None # ): # plot_type = 'imshow' # print('plot_type **** imshow **** is used.') elif proj in ('nplaea', 'splaea', 'ortho'): # pcolormesh has a problem for these projections plot_type = 'pcolor' print('plot_type **** pcolor **** is used.') else: plot_type = 'pcolormesh' print('plot_type **** pcolormesh **** is used.') # cmap cmap = kw.pop('cmap', None) if cmap is None: zz_max = data.max() zz_min = data.min() if zz_min >= 0: try: cmap = plt.get_cmap('viridis') except: cmap = plt.get_cmap('OrRd') elif zz_max <= 0: try: cmap = plt.get_cmap('viridis') except: cmap = plt.get_cmap('Blues_r') else: cmap = plt.get_cmap('RdBu_r') elif isinstance(cmap, str): cmap = plt.get_cmap(cmap) # clim parameters clim = kw.pop('clim', None) robust = kw.pop('robust', False) if clim is None: if isinstance(data, np.ma.core.MaskedArray): data1d = data.compressed() else: data1d = data.ravel() notNaNs = np.logical_not(np.isnan(data1d)) data1d = data1d[notNaNs] if robust: a = np.percentile(data1d, 2) b = np.percentile(data1d, 98) else: a = data1d.min() b = data1d.max() if a * b < 0: b = max(abs(a), abs(b)) a = -b clim = a, b # levels levels = kw.pop('levels', None) if levels is None: if plot_type in ('contour', 'contourf', 'contourf+'): a, b = clim levels = np.linspace(a, b, 11) elif isinstance(levels, int): if plot_type in ('contour', 'contourf', 'contourf+'): a, b = clim levels = np.linspace(a, b, levels) elif plot_type in ('pcolor', 'pcolormesh', 'imshow'): cmap = plt.get_cmap(cmap.name, levels - 1) else: # levels is a sequence if plot_type in ('pcolor', 'pcolormesh', 'imshow'): cmap = plt.get_cmap(cmap.name, len(levels) - 1) clim = min(levels), max(levels) # colorbar parameters if plot_type in ('pcolor', 'pcolormesh', 'contourf', 'contourf+', 'imshow'): cbar_type = kw.pop('cbar_type', 'vertical') cbar_kw = kw.pop('cbar_kw', {}) cbar_extend = kw.pop('cbar_extend', 'neither') cbar_extend = cbar_kw.pop('extend', cbar_extend) hide_cbar = kw.pop('hide_cbar', False) if cbar_type in ('v', 'vertical'): cbar_size = kw.pop('cbar_size', '2.5%') cbar_size = cbar_kw.pop('size', cbar_size) cbar_pad = kw.pop('cbar_pad', 0.1) cbar_pad = cbar_kw.pop('pad', cbar_pad) cbar_position = 'right' cbar_orientation = 'vertical' elif cbar_type in ('h', 'horizontal'): # cbar = hcolorbar(units=units) cbar_size = kw.pop('cbar_size', '5%') cbar_size = cbar_kw.pop('size', cbar_size) cbar_pad = kw.pop('cbar_pad', 0.4) cbar_pad = cbar_kw.pop('pad', cbar_pad) cbar_position = 'bottom' cbar_orientation = 'horizontal' # units in colorbar units = kw.pop('units', None) if units is None: try: units = data_units # input data is a DataArray except: units = '' # long_name in colorbar long_name = kw.pop('long_name', None) if long_name is None: try: long_name = data_name # if input data is a DataArray if long_name is None: long_name = '' except: long_name = '' # ###### plot # pcolor if plot_type in ('pcolor', ): rasterized = kw.pop('rasterized', True) plot_obj = m.pcolor(X_edge, Y_edge, data, cmap=cmap, rasterized=rasterized, **kw) # pcolormesh elif plot_type in ('pcolormesh', ): rasterized = kw.pop('rasterized', True) plot_obj = m.pcolormesh(X_edge, Y_edge, data, cmap=cmap, rasterized=rasterized, **kw) # imshow elif plot_type in ('imshow', ): if Y_edge[-1, 0] > Y_edge[0, 0]: origin = kw.pop('origin', 'lower') else: origin = kw.pop('origin', 'upper') extent = kw.pop( 'extent', [X_edge[0, 0], X_edge[0, -1], Y_edge[0, 0], Y_edge[-1, 0]]) interpolation = kw.pop('interpolation', 'nearest') plot_obj = m.imshow(data, origin=origin, cmap=cmap, extent=extent, interpolation=interpolation, **kw) # contourf elif plot_type in ('contourf', ): if proj in ('ortho','npstere', 'nplaea', 'npaeqd', 'spstere', 'splaea', 'spaeqd')\ and np.isclose(np.abs(lon_edge[-1]-lon_edge[0]), 360): data, lon = addcyclic(data, lon) Lon, Lat = np.meshgrid(lon, lat) X, Y = m(Lon, Lat) extend = kw.pop('extend', 'both') plot_obj = m.contourf(X, Y, data, extend=extend, cmap=cmap, levels=levels, **kw) # contour elif plot_type in ('contour', ): if proj in ('ortho','npstere', 'nplaea', 'npaeqd', 'spstere', 'splaea', 'spaeqd')\ and np.isclose(np.abs(lon_edge[-1]-lon_edge[0]), 360): data, lon = addcyclic(data, lon) Lon, Lat = np.meshgrid(lon, lat) X, Y = m(Lon, Lat) colors = kw.pop('colors', 'k') if colors is not None: cmap = None alpha = kw.pop('alpha', 0.5) plot_obj = m.contour(X, Y, data, cmap=cmap, colors=colors, levels=levels, alpha=alpha, **kw) label_contour = kw.pop('label_contour', False) if label_contour: plt.clabel(plot_obj, plot_obj.levels[::2], fmt='%.2G') # contourf + contour elif plot_type in ('contourf+', ): if proj in ('ortho','npstere', 'nplaea', 'npaeqd', 'spstere', 'splaea', 'spaeqd')\ and np.isclose(np.abs(lon_edge[-1]-lon_edge[0]), 360): data, lon = addcyclic(data, lon) Lon, Lat = np.meshgrid(lon, lat) X, Y = m(Lon, Lat) extend = kw.pop('extend', 'both') linewidths = kw.pop('linewidths', 1) plot_obj = m.contourf(X, Y, data, extend=extend, cmap=cmap, levels=levels, **kw) colors = kw.pop('colors', 'k') if colors is not None: cmap = None alpha = kw.pop('alpha', 0.5) m.contour(X, Y, data, cmap=cmap, colors=colors, alpha=alpha, levels=levels, linewidths=linewidths, **kw) # quiverplot elif plot_type in ('quiver', ): nGrids = kw.pop('nGrids', 50) nx = kw.pop('nx', nGrids) ny = kw.pop('ny', nGrids) stride = kw.pop('stride', 1) stride_lon = kw.pop('stride_lon', stride) stride_lat = kw.pop('stride_lat', stride) print(stride, stride_lon, stride_lat) if (stride != 1) or (stride_lon != 1) or ( stride_lat != 1 ): # compatible with old api, with stride, stride_lon, stride_lat controling quiver grids. To be obsolete. Use nGrids, nx, ny instead print('stride used') lon_ = lon[::stride_lon] # subset of lon lat_ = lat[::stride_lat] u_ = u[::stride_lat, ::stride_lon] v_ = v[::stride_lat, ::stride_lon] # sparse polar area sparse_polar_grids = kw.pop('sparse_polar_grids', True) if sparse_polar_grids: msk = np.empty(u_.shape) * np.nan for i in range(lat_.size): step = int(1. / np.cos(lat_[i] * np.pi / 180)) msk[i, 0::step] = 0 u_ += msk v_ += msk Lon_, Lat_ = np.meshgrid(lon_, lat_) u_rot, v_rot, X_, Y_ = m.rotate_vector(u_, v_, Lon_, Lat_, returnxy=True) else: # use nGrids, nx, ny to control the quiver grids if lon.max() > 180: u_, lon_ = shiftgrid(180., u, lon, start=False) v_, lon_ = shiftgrid(180., v, lon, start=False) else: u_ = u v_ = v lon_ = lon u_rot, v_rot, X_, Y_ = m.transform_vector(u_, v_, lon_, lat, nx, ny, returnxy=True) quiver_color = kw.pop('quiver_color', 'g') quiver_scale = kw.pop('quiver_scale', None) hide_qkey = kw.pop('hide_qkey', False) qkey_kw = kw.pop('qkey_kw', {}) qkey_X = kw.pop('qkey_X', 0.85) qkey_X = qkey_kw.pop('X', qkey_X) qkey_Y = kw.pop('qkey_Y', 1.02) qkey_Y = qkey_kw.pop('Y', qkey_Y) qkey_U = kw.pop('qkey_U', 2) qkey_U = qkey_kw.pop('U', qkey_U) qkey_label = kw.pop('qkey_label', '{:g} '.format(qkey_U) + units) qkey_label = qkey_kw.pop('label', qkey_label) qkey_labelpos = kw.pop('qkey_labelpos', 'W') qkey_labelpos = qkey_kw.pop('labelpos', qkey_labelpos) plot_obj = m.quiver(X_, Y_, u_rot, v_rot, color=quiver_color, scale=quiver_scale, **kw) if not hide_qkey: # quiverkey plot plt.quiverkey(plot_obj, qkey_X, qkey_Y, qkey_U, label=qkey_label, labelpos=qkey_labelpos, **qkey_kw) # hatch plot elif plot_type in ('hatch', 'hatches'): hatches = kw.pop('hatches', ['///']) plot_obj = m.contourf(X, Y, data, colors='none', hatches=hatches, extend='both', **kw) else: print( 'Please choose a right plot_type from ("pcolor", "contourf", "contour")!' ) # set clim if plot_type in ('pcolor', 'pcolormesh', 'imshow'): plt.clim(clim) # plot colorbar if plot_type in ('pcolor', 'pcolormesh', 'contourf', 'contourf+', 'imshow'): ax_current = plt.gca() divider = make_axes_locatable(ax_current) cax = divider.append_axes(cbar_position, size=cbar_size, pad=cbar_pad) cbar = plt.colorbar(plot_obj, cax=cax, extend=cbar_extend, orientation=cbar_orientation, **cbar_kw) if cbar_type in ('v', 'vertical'): # put the units on the top of the vertical colorbar cbar.ax.xaxis.set_label_position('top') cbar.ax.set_xlabel(units) cbar.ax.set_ylabel(long_name) elif cbar_type in ('h', 'horizontal'): # cbar.ax.yaxis.set_label_position('right') # cbar.ax.set_ylabel(units, rotation=0, ha='left', va='center') if long_name == '' or units == '': cbar.ax.set_xlabel('{}{}'.format(long_name, units)) else: cbar.ax.set_xlabel('{} [{}]'.format(long_name, units)) # remove the colorbar to avoid repeated colorbars if hide_cbar: cbar.remove() # set back the main axes as the current axes plt.sca(ax_current) return plot_obj
y = [ elem for elem in attracting_ridges_lat[i][:, t].data if elem < 99999 ] #m.plot(attracting_ridges_lon[i][:,t],attracting_ridges_lat[i][:,t],c='b',latlon=True) m.plot(x, y, c='b', latlon=True) for i in range(len(repelling_ridges_lat)): x = [ elem for elem in repelling_ridges_lon[i][:, t].data if elem < 99999 ] y = [ elem for elem in repelling_ridges_lat[i][:, t].data if elem < 99999 ] #m.plot(repelling_ridges_lon[i][:,t],repelling_ridges_lat[i][:,t],c='r',latlon=True) m.plot(x, y, c='r', latlon=True) m.scatter(t_lon[:, t], t_lat[:, t], latlon=True) hrs, mins = np.divmod(t * 10, 60) plt.title('{0:02d} hrs, {1:02d} mins'.format(int(hrs), int(mins))) m.drawcoastlines() m.drawstates() parallels = np.arange(round(lat_min, 0), lat_max + 2, 2) meridians = np.arange(round(lon_max, 0), lon_min - 2, -2) m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10) plt.savefig('OECS_{0:04d}.tif'.format(t), transparent=False, bbox_inches='tight') plt.close('all')
fig = plt.figure(1, figsize=(10, 8)) m = Basemap(projection='moll', resolution='c', lon_0=0.) m.drawcoastlines() m.fillcontinents(color='.9') m.drawparallels(np.arange(-90., 120., 30.)) m.drawmeridians(np.arange(0., 420., 60.)) m.drawmapboundary() ax = plt.gca() mymap = plt.get_cmap('viridis') #mycolor = mymap(p100) #if debug: # print(mycolor) x, y = m(lonSta, latSta) sc = m.scatter(x, y, s=50, c=col, zorder=3, cmap='viridis', marker="v") #days = np.asarray([0., 25., 50., 75., 100.])/100. #size = np.asarray([0., 25., 50., 75., 100.])/100. #frac = [(0.2 + (_i - min_size_)) / (max_size_ - min_size_) for _i in size] #size_plot = [(_i * (max_size - min_size)) ** 2 for _i in frac] #for pair in zip(days, size_plot): sc2 = m.scatter([0.], [0.], s=50., c='C0', cmap='viridis', zorder=3, marker='v', label='Station') sc2 = m.scatter([0.], [0.],
def plot_position_estimate_and_contours(sights, sampler): # begin plotting mean_lat = np.mean(sampler.chain[:, :, 0].flatten() * 180.0 / np.pi) mean_lon = np.mean(sampler.chain[:, :, 1].flatten() * 180.0 / np.pi) std_lat = np.std(sampler.chain[:, :, 0].flatten() * 180.0 / np.pi) std_lon = np.std(sampler.chain[:, :, 1].flatten() * 180.0 / np.pi) # compute a lat/lon range for the map plot, with a minimum span of +- 45 arcminutes lat_span = np.max(np.array((std_lat * 7, 45 / 60.0))) lon_span = np.max(np.array((std_lon * 7, 45 / 60.0))) # adjust the aspect ratio for a better plot if lat_span / lon_span > 2.0: # lattitude is much greater than longitude -- adjust longitude to be at least half the lattitude lon_span = lat_span / 2.0 if lon_span / lat_span > 2.0: # longitude is much greater than lattitude-- adjust lattitude to be at least half the longitude lat_span = lon_span / 2.0 # miller projection map = Basemap(projection='mill', llcrnrlat=mean_lat - lat_span, urcrnrlat=mean_lat + lat_span, llcrnrlon=mean_lon - lon_span, urcrnrlon=mean_lon + lon_span) # plot coastlines, draw label meridians and parallels. map.drawcoastlines() map.drawparallels(np.arange( np.floor(mean_lat) - 5, np.ceil(mean_lat) + 5, 1), labels=[1, 0, 0, 0]) map.drawmeridians(np.arange( np.floor(mean_lon) - 5, np.ceil(mean_lon) + 5, 1), labels=[0, 0, 0, 1]) # fill continents 'coral' (with zorder=0), color wet areas 'aqua' map.drawmapboundary(fill_color='aqua') map.fillcontinents(color='coral', lake_color='aqua') # use a Gaussian KDE gkde = scipy.stats.gaussian_kde([ sampler.chain[:, :, 1].flatten() * 180.0 / np.pi, sampler.chain[:, :, 0].flatten() * 180.0 / np.pi ], bw_method=0.4) # create a grid lonarray = np.linspace(mean_lon - 8 * std_lon, mean_lon + 8 * std_lon, 300) latarray = np.linspace(mean_lat - 8 * std_lat, mean_lat + 8 * std_lat, 300) lons, lats = np.meshgrid(lonarray, latarray) # find the 68%, 95%, and 99% scores at percentiles sarray = scipy.stats.scoreatpercentile(gkde(gkde.resample(1000)), [1, 5, 32]) z = np.array(gkde.evaluate([lons.flatten(), lats.flatten()])).reshape(lons.shape) x, y = map(lons, lats) map.contour(x, y, z, sarray, linewidths=2, alpha=1.0, colors='k') # convert lat/lons to x,y points # x, y = map(sampler.chain[0:100, 0:20, 1].flatten() * 180.0 / np.pi, # sampler.chain[0:100, 0:20, 0].flatten() * 180.0 / np.pi) # map.scatter(x, y, 3, marker='o', color='k') # plot the true value, which relies in the first Sight's nominal lon/lat x, y = map(sights[0].lonA.deg, sights[0].latA.deg) map.scatter(x, y, s=50, marker='o', color='r') plt.title('Position at {} is {} ± {} / {} ± {} '.format( sights[0].datetime.strftime("%Y/%m/%d -- %H:%M:%S"), nadeg(mean_lat / 180 * np.pi), nadeg(2.0 * std_lat / 180 * np.pi), nadeg(mean_lon / 180 * np.pi), nadeg(2.0 * std_lon / 180 * np.pi)), fontsize=12) plt.show() return
pass; else: map.drawgreatcircle( lona[i],lata[i],lonb[i],latb[i],linewidth=0.6, color='brown',zorder=0) else: if (330 < lona[i] <= 360) and (0 < lonb[i] <= 30): pass; elif (330 < lonb[i] <= 360) and (0 < lona[i] <= 30): pass; else: map.drawgreatcircle( lona[i],lata[i],lonb[i],latb[i],linewidth=0.3,color='black',zorder=0) # plot age grid lon, lat = np.meshgrid(lons, lats) xi, yi = map(lon, lat) age_plot = map.pcolor(xi,yi,ages,cmap='RdBu',vmin=0,vmax=160,zorder=1) # plot age points for j in range(num_DPs): xo, yo = map(sp_ages[j,0],sp_ages[j,1]) if np.isnan(sp_ages[j,2]) == 1 and iwall[j]==1: map.scatter(xo, yo, c='r',s=2.5,lw=0,zorder=2) elif iwall[j] == 1: ages_plot = map.scatter(xo, yo, c=sp_ages[j,2],s=5,cmap='RdBu',vmin=0,vmax=160,edgecolor='black',linewidth=0.2,zorder=2) cbar = map.colorbar(ages_plot,location='bottom',pad="5%",size="4%") cbar.set_ticks(np.array([0,40,80,120,160,180])) cbar.set_label('age, Ma',size=9) cbar.ax.tick_params(labelsize=8) test_plot_name=''.join(['plots/ages_and_boundary_tests/ages/',str(plates),'.pdf']) plt.savefig(test_plot_name, bbox_inches='tight', format='pdf')
query = ItpQuery(PATH, latitude=[70, 80], longitude=[-180, -130], date_time=TIME_RANGE, pressure=[400, 402]) query.set_max_results(10000) # override the 5000 result limit results = query.fetch() temp_400 = [] for profile in results: temp_400.append(profile.temperature[0]) longitude = np.array([p.longitude for p in results]) latitude = np.array([p.latitude for p in results]) m = Basemap(projection='npstere', boundinglat=70, lon_0=0, resolution='i') m.drawcoastlines() m.fillcontinents() m.drawparallels(range(70, 90, 5)) m.drawmeridians(range(-180, 180, 20), latmax=85) scatter = m.scatter(longitude, latitude, c=temp_400, latlon=True, vmin=0.3, vmax=1.0) colorbar = plt.colorbar(scatter) colorbar.ax.set_ylabel('Temperature (C)') plt.show()
def stis_saa_plot(data_df=None, i=5): stis = data_df['1997-02-01':'1997-02-28'] saa_eastern = (39.0, -30.0) # lon/lat saa_western = (267.0, -20.0) saa_northern = (312.0, 1.0) saa_southern = (300.0,-60.0) mask = (stis['latitude'] < saa_northern[1]) #& (stis['incident_cr_rate'] < 20) stis_saa_cut = stis[mask] fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(9,8)) # Create the lat/lon map m = Basemap(projection='cyl',llcrnrlon=-120, llcrnrlat= -60, urcrnrlon= 60, urcrnrlat= 10, ax=ax1) m.shadedrelief(scale=0.2) # lats and longs are returned as a dictionary lats = m.drawparallels(np.linspace(-90, 90, 13), labels=[True, True, False, False]) lons = m.drawmeridians(np.linspace(-180, 180, 13), labels=[False, False, False, True]) # keys contain the plt.Line2D instances lat_lines = chain(*(tup[1][0] for tup in lats.items())) lon_lines = chain(*(tup[1][0] for tup in lons.items())) all_lines = chain(lat_lines, lon_lines) # cycle through these lines and set the desired style for line in all_lines: line.set(linestyle='-', alpha=0.3, color='w') saa = [list(t) for t in zip(*costools.saamodel.saaModel(i))] # Ensure the polygon representing the SAA is a closed curve by adding # the starting points to the end of the list of lat/lon coords saa[0].append(saa[0][0]) saa[1].append(saa[1][0]) m.plot(saa[1], saa[0], c='r', latlon=True, label='SAA contour {}'.format(i)) hst_lon, hst_lat = stis_saa_cut['longitude'], stis_saa_cut['latitude'] shifted_lon = [] for i, lon in enumerate(hst_lon): if lon > 180.0: shifted_lon.append(lon - 360.0) else: shifted_lon.append(lon) x_coord, y_coord = m(shifted_lon, hst_lat) labels = [k for k in range(len(stis_saa_cut))] indices = [] for j, (lon, lat, label) in enumerate(zip(hst_lon, hst_lat, labels)): if j >= 4: indices.append(j) m.scatter(lon, lat, marker='o', s=10,c='r', latlon=True) ax1.annotate('{}'.format(j-4), xy=(x_coord[j], y_coord[j]), xycoords='data') ax2.scatter([k - 4 for k in indices], stis_saa_cut['incident_cr_rate'][indices]) ax1.legend(loc='best') ax2.set_xticks([k - 4 for k in indices]) ax2.set_ylabel('Cosmic Ray Flux [CR/s/cm^2]') ax2.set_xlabel('Observation Number') fig.savefig('stis_saa_crossing.png', format='png', dpi=350) plt.show()
if reptype == 120 or reptype == 132: color = 'b' platformname = 'ADPUPA(' + str(reptype) + ')' elif reptype == 130 or reptype == 131: color = 'r' platformname = 'AIRCFT(' + str(reptype) + ')' elif reptype == 133: color = 'g' platformname = 'AIRCAR(' + str(reptype) + ')' elif reptype == 180: color = 'g' platformname = 'SFCSHP(' + str(reptype) + ')' else: color = 'k' platformname = 'UNKNOWN(' + str(reptype) + ')' x, y = m(diag_conv.lon[indx], diag_conv.lat[indx]) m.scatter(x, y, 4, color=color, marker='o', edgecolors='none', zorder=20, label=platformname + ' - ' + str(nobs)) plt.legend(ncol=7, loc=8, bbox_to_anchor=(0.5, -0.1), markerscale=2) plt.title(' %s %s Assimilated ' % (dtg, obsname), fontsize=25) plt.savefig('Q' + '_' + str(dtg) + '.png', dpi=100) plt.show()
# Fill the land with grey #m.fillcontinents(color = 'gainsboro') #m.drawmapboundary(fill_color='steelblue') #m.bluemarble() #m.etopo() m.shadedrelief() m.drawcoastlines() m.drawparallels(np.arange(-80.,81.,5.),labels=[1,0,0,0]) m.drawmeridians(np.arange(-180.,181.,5.),labels=[0,0,0,1]) # Define our longitude and latitude points # We have to use .values because of a wierd bug when passing pandas data # to basemap. x,y = m(df['LON'].values, df['LAT'].values) # Plot them using round markers of size 6 #m.plot(x, y, 'ro', markersize=2) m.scatter(x,y,c=df['THICK'],marker="o",cmap=cm.terrain,s=20, edgecolors='none',vmin=0,vmax=1500)#,vmin=-150,vmax=50 c = plt.colorbar(orientation='vertical', shrink = 0.5) c.set_label("m") #plt.show() #plt.tight_layout() plt.suptitle('THICK Full', y=1.02) plt.savefig(infile+'_THICK_full_mapplot.png',bbox_inches='tight') # save the figure to file #plt.close(m) ######################################### ### FULL FAG070 import matplotlib.cm as cm from mpl_toolkits.basemap import Basemap fig = plt.figure(figsize=(8,8)) #create basemap m = Basemap(width=700000,height=1100000,
m.drawcoastlines(linewidth=1.5) m.drawcountries(linewidth=1.5) parallels = np.arange(10., 60, 10.) m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10) # 绘制纬线 meridians = np.arange(70., 135., 10.) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10) # 绘制经线 #m.readshapefile('CHN_adm_shp/CHN_adm1', 'states', drawbounds=True) #------------------read the data--------------------- #x,y=m(np.array([90,93]),np.array([20,43])) #m.scatter(x,y,10) filedata = pd.read_csv('id-level.csv') data_point = np.array(filedata['经纬度'][0:]) lon = [] #lon lat = [] #lat size = np.array for i in range(len(data_point)): try: data = data_point[i].split(',') lon.append(float(data[0])) lat.append(float(data[1])) except: pass else: del data_point x, y = m(lon, lat) m.scatter(x, y, s=40, color='red') plt.title('view-data in china ') plt.show()
population = city['POPULATION'].values dist=city['DIST_NAME'].values fig = plt.figure(figsize=(8, 8)) m = Basemap(projection='lcc', resolution='h', lat_0=27.0238, lon_0=74.2179, width=1.05E6, height=1.2E6) m.shadedrelief() m.drawcoastlines(color='blue',linewidth=3) m.drawcountries(color='gray',linewidth=3) m.drawstates(color='gray') # scatter city data, with c reflecting population m.scatter(lon,lat, latlon=True, c=population,s=700, cmap='YlGnBu_r', alpha=0.5) #create colorbar plt.colorbar(label=r'Population') plt.clim(300000, 4000000) dict1={} list1=[] list2=[] list3=[] n=0 #storing each value in different lists for z in lat: list1.append(z) for c in lon:
to_plot = '2 m Temperature' z_max = np.max(met[to_plot]) z_min = np.min(met[to_plot]) levels = np.arange(z_min, z_max + 0.1, 0.1) zi = interpolate.griddata( (met.ix[time_selection]['Lon'], met.ix[time_selection]['Lat']), met.ix[time_selection][to_plot], (xi, yi), method='linear') shapefile = 'UScounties/UScounties' maps = Basemap(llcrnrlon=xmin, llcrnrlat=ymin, urcrnrlon=xmax, urcrnrlat=ymax, projection='cyl') maps.readshapefile(shapefile, name='counties') maps.contourf(xi, yi, zi, levels, cmap=plt.cm.gist_earth_r) c = plt.colorbar() c.set_label('2 m Temperature') maps.scatter(met.ix[time_selection]['Lon'], met.ix[time_selection]['Lat'], marker='o', c='b', s=5) maps.barbs(met.ix[time_selection]['Lon'], met.ix[time_selection]['Lat'], met.ix[time_selection]['u'].values, met.ix[time_selection]['v'].values) plt.title(to_plot) plt.tight_layout() plt.show()
projection='cyl', lat_0=39.5, lon_0=-3.25) mapFig.drawmapboundary(fill_color=(0.85, 0.85, 0.85)) mapFig.fillcontinents(color=(0.5, 0.5, 0.5), zorder=1) mapFig.drawmeridians(np.arange(0, 360, 60), labels=[0, 0, 0, 1], color=(0.3, 0.3, 0.3), fontsize=ticksize) mapFig.drawparallels(np.arange(-90, 90, 30), labels=[1, 0, 0, 0], color=(0.3, 0.3, 0.3), fontsize=ticksize) mapFig.scatter(lons, lats, latlon=True, c=data.geostrophicProportions, marker='o', cmap=plt.cm.RdBu) cbar = plt.colorbar(orientation="horizontal", ticks=[0.0, 0.5, 1.0]) plt.clim(0, 1) cbar.set_label("relative strength of geostrophic versus Ekman current", fontsize=ticksize) cbar.ax.set_yticklabels(["0.0", "0.5", "1.0"]) cbar.ax.tick_params(labelsize=ticksize) plt.title("January, February, March, " + str(params.start_year) + "-" + str(params.end_year), fontsize=ticksize) #plt.savefig("plots/current_component_dominance/ekman_vs_geostrophic_123_"+str(params.start_year)+"_"+str(params.end_year)+".pdf"); plt.savefig( "plots/current_component_dominance/ekman_vs_geostrophic_123_" +
#Where we are coming from lastLon = None lastLat = None #Parse individual traceroute command lines for line in proc.stdout: print(line, end="") hopIP = line.split()[1] if hopIP == "*" or hopIP == "to": continue (lat, lon) = getLoc(hopIP) if (lat == None): continue if lastLat != None and (lastLat - lat + lastLon - lon) != 0.0: #print(lastLat,lastLon,lat,lon) x, y = m(lon, lat) m.scatter(x, y, 10, marker='o', color='r') line, = m.drawgreatcircle(lastLon, lastLat, lon, lat, color='b') lastLat = lat lastLon = lon plt.tight_layout() plt.show() elif platform.system() == 'Windows': proc = subprocess.Popen("C:\\Windows\\System32\\TRACERT.exe -h 25 -d -4 " + IP, stdout=subprocess.PIPE, shell=True, universal_newlines=True) fig = plt.figure(figsize=(10, 6), edgecolor='w') m = Basemap(projection='mill', lon_0=0, resolution='l')