def draw_map(plot_title, data_dict): """ Draws a map of North America with temperature station names and values. Positive values are drawn next to red dots and negative values next to blue dots. The location of values are determined by the latitude and longitude. A dictionary (data_dict) is used to provide a map from station_name names to a tuple containing the (latitude, longitude, value) used for drawing. :param plot_title: Title for the plot. :param data_dict: A dictionary mapping STATION NAME -> tuple(LATITUDE, LONGITUDE, VALUE) """ fig = plt.figure(figsize=(9, 9), dpi=100) map1 = Basemap(projection='ortho', resolution=None, lat_0=53, lon_0=-97, ) map1.etopo(scale=0.5, alpha=0.5) for station_name_name in data_dict: data = data_dict[station_name_name] print(station_name_name, data) x, y = map1(data[1], data[0]) value = data[2] color = 'black' if value < 0: color = 'blue' elif value > 0: color = 'red' plt.plot(x, y, 'ok', markersize=3, color=color) plt.text(x, y, '{}\n {:.2f}°C'.format(station_name_name, value), fontsize=8) plt.title(plot_title) plt.show() fig.savefig(plot_title+".png")
def draw_basemap(fig, ax, lonsize, latsize, interval_lon, interval_lat): ax = fig.sca(ax) ''' dmap = Basemap(projection='cyl', llcrnrlat=min(latsize)-0.01, urcrnrlat=max(latsize)+0.01, llcrnrlon=min(lonsize)-0.01, urcrnrlon=max(lonsize)+0.01, resolution='h',ax=ax) ''' dmap = Basemap(projection='cyl', llcrnrlat=min(latsize) - (max(latsize) - min(latsize)) / 6, urcrnrlat=max(latsize) + (max(latsize) - min(latsize)) / 6, llcrnrlon=min(lonsize) - (max(lonsize) - min(lonsize)) / 6, urcrnrlon=max(lonsize) + (max(lonsize) - min(lonsize)) / 6, resolution='h', ax=ax) dmap.drawparallels(np.arange(int(min(latsize)), int(max(latsize)) + 1, interval_lat), labels=[1, 0, 0, 0], linewidth=0.1, fontsize=20) dmap.drawmeridians(np.arange( int(min(lonsize)) - 1, int(max(lonsize)) + 1, interval_lon), labels=[0, 0, 0, 1], linewidth=0.1, fontsize=20) dmap.drawcoastlines() dmap.fillcontinents(color='grey') #dmap.etopo() dmap.etopo()
def plot_tracks_from_tab_files(trackfiles : [str], verbose = False): xmin, xmid, xmax, ymin, ymid, ymax = dc.get_min_mid_max_from_file_list(trackfiles) x_buffer = (xmax-xmin) / 5.0 y_buffer = (ymax-ymin) / 5.0 xmin -= x_buffer xmax += x_buffer ymin -= y_buffer ymax += y_buffer # Generate a basemap for the desired region m = Basemap(projection='merc', llcrnrlat=ymin, urcrnrlat=ymax, llcrnrlon=xmin, urcrnrlon=xmax, lat_ts=ymid, resolution='h') m.etopo(scale=2.0) m.drawcoastlines() # draw parallels and meridians. m.drawparallels(np.arange(ymin, ymax, 1.0)) m.drawmeridians(np.arange(xmin, xmax, 1.0)) for file in trackfiles: if verbose: print('plotting track: %s' %file) add_single_track_to_map(file, m, width=10.0) plt.show()
def europeMap(data, numberOfYears, longitude, latitude): lat1, lat2 = latitude latitude123 = numpy.arange(lat1, lat2 + 0.5, 0.5) lon1, lon2 = longitude longitude123 = numpy.arange(lon1, lon2 + 0.5, 0.5) years = int(numberOfYears) fig1, ax1 = plt.subplots(1, 1, figsize=(13, 13)) ax1.set_title(r'September mean of Div(vD) over Europe (1979-2014)') map1 = Basemap(projection='cyl',llcrnrlon=-10.0,llcrnrlat=35.0, \ urcrnrlon=40.0,urcrnrlat=75.0, lon_0 = 30, lat_0 = 30,\ rsphere=6371200., resolution = 'l', area_thresh=10000) lons, lats = numpy.meshgrid(longitude123, latitude123) x, y = map1(lons, lats) data = data / years myData = data.reshape((81, 101)) cmap = plt.get_cmap('jet') colormesh = map1.pcolormesh(x, y, myData, cmap=cmap) # ice = map1.contourf(x, y, myData, cmap=plt.cm.jet) # map1.colorbar(colormesh) cb = map1.colorbar(colormesh, location='bottom', pad="3%") cb.set_label(r'Dry Static Energy (Watt)') map1.drawcoastlines() map1.bluemarble() map1.etopo() map1.drawcountries() # cbar = map1.colorbar(ice,location='right',pad="3%") plt.show()
def Map_plot_subregion(subregions, ref_dataset, directory): lons, lats = np.meshgrid(ref_dataset.lons, ref_dataset.lats) fig = plt.figure() ax = fig.add_subplot(111) m = Basemap( ax=ax, projection='cyl', llcrnrlat=lats.min(), urcrnrlat=lats.max(), llcrnrlon=lons.min(), urcrnrlon=lons.max(), resolution='l') m.drawcoastlines(linewidth=0.75) m.drawcountries(linewidth=0.75) m.etopo() x, y = m(lons, lats) #subregion_array = ma.masked_equal(subregion_array, 0) #max=m.contourf(x, y, subregion_array, alpha=0.7, cmap='Accent') for subregion in subregions: draw_screen_poly(subregion[1], m, 'w') plt.annotate( subregion[0], xy=(0.5 * (subregion[1][2] + subregion[1][3]), 0.5 * (subregion[1][0] + subregion[1][1])), ha='center', va='center', fontsize=8) fig.savefig(directory + 'map_subregion', bbox_inches='tight')
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 map_plot(): import matplotlib.pyplot as plt, mpld3 import numpy as np from mpl_toolkits.basemap import Basemap fig, ax = plt.subplots() m = Basemap() #m = Basemap(projection='ortho',lat_0=0,lon_0=0,resolution='l') #m = Basemap(projection='moll',lon_0=0,resolution='l') # Shift 'lon' from [0,360] to [-180,180], make numpy array #tmp_lon = np.array([lon[n]-360 if l>=180 else lon[n] # for n,l in enumerate(lon)]) # => [0,180]U[-180,2.5] #i_east, = np.where(tmp_lon>=0) # indices of east lon #i_west, = np.where(tmp_lon<0) # indices of west lon #lon = np.hstack((tmp_lon[i_west], tmp_lon[i_east])) # stack the 2 halves # Correspondingly, shift the 'air' array #tmp_air = np.array(air) #air = np.hstack((tmp_air[:,i_west], tmp_air[:,i_east])) #poly_paths = m.drawcoastlines().get_paths() # coastline polygon paths #X,Y = np.meshgrid(lon,lat) m.etopo() #m.contourf(X, Y, air, 40, alpha=.75, cmap='jet') #ticks=range(-90,90,30) #ax.set_yticks(ticks) #ax.set_ylabel("Latitude", fontsize=16) #ax.set_xlabel("Longitude", fontsize=16) #plt.colorbar() # D3 Works! #mpld3.display(fig) return mpld3.fig_to_html(fig,template_type="general")
def figure_four(cur, conn): cur.execute('SELECT citystate FROM Salaries') topthree = cur.fetchall() topthree = topthree[0:3] #map plotting that works fig = plt.figure(figsize=(7, 7)) m = Basemap( projection='lcc', resolution=None, width=8E6, height=8E6, lat_0=45, lon_0=-100, ) m.etopo(scale=0.5, alpha=0.5) # Map (long, lat) to (x, y) for plotting x, y = m(-122.3, 39) plt.plot(x, y, 'ok', markersize=3) plt.text(x, y, topthree[0][0], fontsize=8) #second x, y = m(-122.3, 47) plt.plot(x, y, 'ok', markersize=3) plt.text(x, y, topthree[1][0], fontsize=8) #third x, y = m(-121, 36) plt.plot(x, y, 'ok', markersize=3) plt.text(x, y, topthree[2][0], fontsize=8) plt.show()
def plotMap(self, points=[]): import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap fig = plt.figure(figsize=(8, 8)) m = Basemap( projection='lcc', resolution=None, width=8E6, height=8E6, lat_0=45, lon_0=-100, ) m.etopo(scale=0.5, alpha=0.5) # Map (long, lat) to (x, y) for plotting bounding_box = [[self.latitudeMin, self.longitudeMin], [self.latitudeMin, self.longitudeMax], [self.latitudeMax, self.longitudeMax], [self.latitudeMax, self.longitudeMin]] for lat, long in bounding_box[:1]: plt.plot(long, lat, 'ok', markersize=10) plt.text(long, lat, ' box', fontsize=12) for lat, long in points: plt.plot(long, lat, 'ok', markersize=5) plt.text(long, lat, ' Seattle', fontsize=12)
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 draw_eastasia(): size = 6500 * 1000 # 6500km plt.figure(figsize=(10, 10), facecolor='w') m = Basemap(width=size, height=size, projection='lcc', resolution='c', lat_0=35.5, lon_0=103.3) m.drawcoastlines(linewidth=0.3, antialiased=False, color='#202020') # 海岸线 m.drawrivers(linewidth=0.05, linestyle='-', color=(0.1, 0.1, 0.1), antialiased=False) # 河流 m.drawcountries(linewidth=1, linestyle='-.', antialiased=False) # 国界 m.drawparallels(np.arange(0, 90, 10), labels=[True, True, False, False]) # 绘制平行线(纬线) [left,right,top,bottom] m.drawmeridians(np.arange(0, 360, 15), labels=[False, False, False, True], linewidth=1, dashes=[2, 2]) # 绘制子午线 m.etopo() # 地形高程 # m.bluemarble() plt.tight_layout(4) plt.title('东亚及附近区域遥感图', fontsize=21) # 东亚及附近区域地理地形图 plt.show()
def map2(): # setup Lambert Conformal basemap. # set resolution=None to skip processing of boundary datasets. m = Basemap(width=12000000,height=9000000,projection='lcc', resolution=None,lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.) m.etopo() plt.show()
def show_simple_position(stations_url, sat_name, times, description): # TO DO: FIND METHOD FOR HANDLING sexagesimal <=> decimal units conversion from skyfield.api import Topos, load # %matplotlib inline import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap satellites = load.tle(stations_url, reload=True) satellite = satellites[sat_name] t = times fig = plt.figure(figsize=(8, 8)) m = Basemap( projection='lcc', resolution=None, width=35E6, height=35E6, lat_0=1, lon_0=1, ) m.etopo(scale=0.5, alpha=0.5) geocentric = satellite.at(t) subpoint = geocentric.subpoint() sign1, d1, m1, s1 = subpoint.latitude.signed_dms() lat = sign1 * (d1 + m1 / 60 + s1 / 3600) sign2, d2, m2, s2 = subpoint.longitude.signed_dms() lon = sign2 * (d2 + m2 / 60 + s2 / 3600) x, y = m(lon, lat) plt.plot(x, y, 'ok', markersize=4) fig.suptitle(description, fontsize=20, fontweight='bold') return ()
def draw_map(plot_title, data_dict): fig = plt.figure(figsize=(9, 9), dpi=100) map1 = Basemap( projection='ortho', resolution=None, lat_0=53, lon_0=-97, ) map1.etopo(scale=0.5, alpha=0.5) for station_name_name in data_dict: data = data_dict[station_name_name] print(station_name_name, data) x, y = map1(data[1], data[0]) value = data[2] color = 'black' if value < 0: color = 'blue' elif value > 0: color = 'red' plt.plot(x, y, 'ok', markersize=3, color=color) plt.text(x, y, '{}\n {:.2f}°C'.format(station_name_name, value), fontsize=8) plt.title(plot_title) plt.show() fig.savefig(plot_title + ".png")
def map3(): # setup Lambert Conformal basemap. # set resolution=None to skip processing of boundary datasets. m = Basemap() m.drawcoastlines() m.etopo() plt.show()
def show_map(table_name=None): if table_name == "r": points = get_all_relational_points() figure_name = "Relational Point Map" elif table_name == "sc": points = get_all_spatial_core_points() figure_name = "Spatial Core Point Map" elif table_name == "sp": points = get_all_spatial_postgis_points() figure_name = "Spatial PostGIS Point Map" else: raise Exception("No table with name '{0}'".format(table_name)) x_coordinates = [point.x for point in points] y_coordinates = [point.y for point in points] plt.figure(num=figure_name, figsize=(12, 8), edgecolor="grey") plt.xlabel("Longitude") plt.xlim((-180.0, 180.0)) plt.ylabel("Latitude") plt.ylim((-90.0, 90.0)) m = Basemap(projection='cyl', resolution=None, llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180) m.scatter(x=x_coordinates, y=y_coordinates, c="red", s=0.1) m.etopo() plt.show()
def Map_plot_subregion(subregions, ref_dataset, directory): lons, lats = np.meshgrid(ref_dataset.lons, ref_dataset.lats) fig = plt.figure() ax = fig.add_subplot(111) m = Basemap(ax=ax, projection='cyl', llcrnrlat=lats.min(), urcrnrlat=lats.max(), llcrnrlon=lons.min(), urcrnrlon=lons.max(), resolution='l') m.drawcoastlines(linewidth=0.75) m.drawcountries(linewidth=0.75) m.etopo() x, y = m(lons, lats) #subregion_array = ma.masked_equal(subregion_array, 0) #max=m.contourf(x, y, subregion_array, alpha=0.7, cmap='Accent') for subregion in subregions: draw_screen_poly(subregion[1], m, 'w') plt.annotate(subregion[0], xy=(0.5 * (subregion[1][2] + subregion[1][3]), 0.5 * (subregion[1][0] + subregion[1][1])), ha='center', va='center', fontsize=8) fig.savefig(directory + 'map_subregion', bbox_inches='tight')
def draw_basemap(ax, points, interval_lon=0.3, interval_lat=0.3): ''' draw the basemap? ''' lons = points['lons'] lats = points['lats'] #size = max((max(lons)-min(lons)),(max(lats)-min(lats)))/2 size = 0 map_lon = [min(lons) - size, max(lons) + size] map_lat = [min(lats) - size, max(lats) + size] #ax = fig.sca(ax) dmap = Basemap(projection='cyl', llcrnrlat=map_lat[0], llcrnrlon=map_lon[0], urcrnrlat=map_lat[1], urcrnrlon=map_lon[1], resolution='h', ax=ax) # resolution: c,l,i,h,f. dmap.drawparallels(np.arange( int(map_lat[0]) - 1, int(map_lat[1]) + 1, interval_lat), labels=[1, 0, 0, 0]) dmap.drawmeridians(np.arange( int(map_lon[0]) - 1, int(map_lon[1]) + 1, interval_lon), labels=[0, 0, 0, 1]) dmap.drawcoastlines() dmap.fillcontinents(color='grey') dmap.drawmapboundary() dmap.etopo()
def draw_map_nogrid_static(bb, month=1, day=1, year=None, gfs_dict=None, latlon_df=None, marker='ro', draw_terrain=False, title=None): """ Plot a map with optional points and optional overlays :param bb: bounding box of region to plot of the form [min_lat, max_lat, min_lon, max_lon] :param month: Month we will plot :param day: Day we will plot :param gfs_dict: A dictionary from (month,day) tuples to gfs overlay values. Also contains special entries 'lat', 'lon', 'max', and 'min' :param points: Tuple of lat and lon coordinates for points to plot. If None, plot no points :param marker: Marker string to use for points :param draw_terrain: Boolean for whether or not to plot the terrain :return: """ mp = Basemap(projection="merc", lat_0=bb[0], lon_0=bb[2], llcrnrlat=bb[0], llcrnrlon=bb[2], urcrnrlat=bb[1], urcrnrlon=bb[3], resolution='i') mp.drawcoastlines() if draw_terrain: mp.etopo() if latlon_df is not None: mp_lons, mp_lats = mp(np.array(latlon_df.lon), np.array(latlon_df.lat)) mp.plot(mp_lons, mp_lats, marker) if gfs_dict is not None: lats = gfs_dict['lats'] lons = gfs_dict['lons'] n_lat, n_lon = lats.shape gfs_min = gfs_dict['min'] gfs_max = gfs_dict['max'] print "bb: " + str(bb[0]) print "lats: " + str(lats[:, 0]) print "where: " + str(np.where(lats[:, 0] <= bb[0])) plot_bb_0 = np.where(lats[:, 0] <= bb[0])[0][0] plot_bb_1 = np.where(lats[:, 0] <= bb[1])[0][0] plot_bb_2 = np.where(lons[0, :] >= (bb[2] % (n_lon / 2)))[0][0] plot_bb_3 = np.where(lons[0, :] >= (bb[3] % (n_lon / 2)))[0][0] if year is not None: vals = gfs_dict[(year, month, day)] else: vals = gfs_dict[(month, day)] mp.imshow(vals[plot_bb_0 - 1:plot_bb_1 - 1:-1, plot_bb_2:plot_bb_3], vmin=gfs_min, vmax=gfs_max) mp.colorbar() if title: plt.title(title)
def plot_multi_list_of_points_on_map(lats_arr, lons_arr, description): """Simple plotter of locations on earth from given lists of lat and lon and description. Parameters ---------- latitudes : list List of satellite information. See sat_info function for more details. longitudes : list List of satellite information. See sat_info function for more details. description: str Description of showed photo. Returns ------- """ import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap col = ['r', 'g', 'b', 'y', 'm', 'k', 'c', 'w'] if len(lats_arr) > 8: raise ValueError('Not enough colours defined!') fig = plt.figure(figsize=(8, 8)) mp = Basemap(projection='lcc', resolution=None, width=35E6, height=35E6, lat_0=1, lon_0=1, ) mp.etopo(scale=0.5, alpha=0.5) for i, (lat, lon) in enumerate(zip(lats_arr, lons_arr)): x, y = mp(lon, lat) plt.plot(x, y, 'ok', markersize=4, color=col[i]) fig.suptitle(description, fontsize=20, fontweight='bold') return ()
def getMapFromClasses(fileToLookFor): map = Basemap( projection='cyl', resolution=None, llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, ) map.etopo(scale=0.5, alpha=0.5) coordData = [] for torrentData in os.listdir("."): if fileToLookFor == None: tClass = pickle.load(open(torrentData, "r")) for tracker in tClass.trackerList: for peer in tracker.peers: if peer.ip != MY_IP_ADDR: lat = float(peer.loc.split(",")[0]) lon = float(peer.loc.split(",")[1]) if coordData.count((lon, lat)) == 0: coordData.append((lon, lat)) #tClass.printSelf() elif torrentData == fileToLookFor: tClass = pickle.load(open(torrentData, "r")) # plot coastlines, draw label meridians and parallels # Map (long, lat) to (x, y) for plotting for cord in coordData: #print "longitude - " + str(cord[0]) + " Latitude - " + str(cord[1]) x, y = map(cord[0], cord[1]) plt.plot(x, y, 'ok', markersize=2) plt.show()
def plotMap(latlim=[20, 65], lonlim=[-160, -70], center=[39, -86], parallels=[20,30,40,50], meridians = [-120,-110, -100, -90, -80,-70], epoto=False, totality=True): (fig,ax) = plt.subplots(1,1,facecolor='w', figsize=(12,8)) m = Basemap(lat_0=40, lon_0=-95,llcrnrlat=latlim[0],urcrnrlat=latlim[1], llcrnrlon=lonlim[0],urcrnrlon=lonlim[1], projection='merc')#, resolution='i', ax=ax) # m.drawparallels(parallels,labels=[False, True, True, True], linewidth=1) # m.drawmeridians(meridians,labels=[True,True,False,True], linewidth=1) m.drawcoastlines() m.drawstates() m.drawcountries() if epoto == True: m.etopo() if totality: totality_path = h5py.File('/home/smrak/Documents/eclipse/totality.h5', 'r') north_lat = np.array(totality_path['path/north_lat']) north_lon = np.array(totality_path['path/north_lon']) south_lat = np.array(totality_path['path/south_lat']) south_lon = np.array(totality_path['path/south_lon']) X1,Y1 = m(north_lon, north_lat) X2,Y2 = m(south_lon, south_lat) m.plot(X1,Y1, c='b') m.plot(X2,Y2, c='b') return fig, ax, m
def show_coord_topo(windpark, show = True): """Plot the topology of a given windpark Topographic Map with farms see: http://matplotlib.org/basemap/users/examples.html Basemap Parameters ---------- windpark : Windpark A given windpark to show the topology. """ mills = windpark.get_windmills() target = windpark.get_target() radius = windpark.get_radius() #pack latitude and longitude in lists rel_input_lat = [] rel_input_lon = [] for row in mills: rel_input_lat.append(np.float64(row.latitude)) rel_input_lon.append(np.float64(row.longitude)) targetcoord = [0.0, 0.0] targetcoord[0] = np.float64(target.latitude) targetcoord[1] = np.float64(target.longitude) graddiff = (radius/111.0) + 0.5 # degree in km m = Basemap(projection='stere', lon_0=targetcoord[1], lat_0=targetcoord[0],\ llcrnrlon = targetcoord[1]-graddiff, llcrnrlat = targetcoord[0]-graddiff ,\ urcrnrlon = targetcoord[1]+graddiff, urcrnrlat = targetcoord[0]+graddiff ,\ rsphere=6371200., resolution = 'l', area_thresh=1000) # Target x_target,y_target = m(targetcoord[1],targetcoord[0]) # Input Farms rel_inputs_lon, rel_inputs_lat = m(rel_input_lon, rel_input_lat) # labels = [left,right,top,bottom] parallels = np.arange(int(targetcoord[0]-3), int(targetcoord[0]+3), 1.) m.drawparallels(parallels,labels=[False,True,True,False]) meridians = np.arange(int(targetcoord[1]-3), int(targetcoord[1]+3), 1.) m.drawmeridians(meridians,labels=[True,False,False,True]) # plot farms in the radius m.plot(x_target, y_target, 'bo') m.plot(rel_inputs_lon, rel_inputs_lat, 'r*') #m.bluemarble() m.etopo() m.drawcoastlines() plt.title("Selected Wind Farms") if(show): plt.show()
def show_clouds_ortho(self, time, center, map_bkgd='bluemarble', out='show'): """ Equivalent function to the show function in Clouds. provide a map of the cloud fields at the specified time """ def col(x): c = 1. - 0.3*x**2. if x < 0.1: return (c,c,c,0) elif x > 0.8: return (c,c,c,1.) else: return (c,c,c,np.clip((x - 0.1)/0.7, 0., 1.)**2.) projection = Basemap(projection='ortho', lat_0=center[0], lon_0=center[1], resolution='l') if map_bkgd == 'bluemarble': projection.bluemarble(zorder=1) elif map_bkgd == 'etopo': projection.etopo(zorder=1) elif map_bkgd == 'mask': projection.drawlsmask(land_color='limegreen', ocean_color='dodgerblue', resolution='l', zorder=1) projection.drawcoastlines(linewidth=0.75, zorder=3) projection.drawcountries(linewidth=0.5, zorder=3) projection.drawmeridians(np.arange(-180, 181, 30), latmax=90, linewidth=0.5, zorder=3) projection.drawparallels(np.arange(-90, 91, 15), latmax=90, linewidth=0.5, zorder=3) else: raise ValueError('invalid map background specification') cf = self(time) lats = np.arange(-90., 90.25, 0.5) lons = np.arange(-180., 180.3125, 0.625) lons, lats = np.meshgrid(lons, lats) levs = np.linspace(0,1,256, endpoint=True) clevs = [col(x) for x in levs] x,y = projection(lons, lats) cfmask = np.ma.masked_greater(x, 1e15).mask cfmasked = np.ma.array(cf, mask=cfmask) plt.contourf(x, y, cfmasked, levs, colors=clevs, extend='both', zorder=2) if out == 'show': plt.show() elif out == '': pass else: plt.savefig(out)
def prim(distancia,nombre, dptos): pathDic = {} for a in range(len(dptos)): dpto = dptos[a] pathDic[dpto]=[] n = len(distancia[dpto]) dist = [math.inf]*n path = [None]*n visited = [False]*n q = [] hq.heappush(q, (0, 0)) contador=0 while len(q) > 0: #print(contador) contador+=1 _, u = hq.heappop(q) if not visited[u]: visited[u] = True for v, w in distancia[dpto][u]: if not visited[v] and w < dist[v] and w!=0 : dist[v] = w path[v] = nombre[dpto][v][u] hq.heappush(q, (w, v)) for i in range(len(path)): if nombre[dpto][v][i] not in path: path[0]=nombre[dpto][v][i] pathDic[dpto]=path print(pathDic) fig = plt.figure(figsize=(15, 15)) m = Basemap(projection='mill', resolution='h', lat_0=-9.1899672, lon_0=-75.015152,llcrnrlat = -18.384377, llcrnrlon = -84.342834, urcrnrlat = 0.936457, urcrnrlon = -68.225205) m.etopo(scale=4, alpha=0.6) # Map (long, lat) to (x, y) for plotting x, y = m(-72.531266212, -13.992029757) #plt.plot(x, y, 'ok', markersize=1) m.drawcoastlines(linewidth=2) m.drawcountries(linewidth=2) #plt.text(x, y, ' Seattle', fontsize=9); xs=[] ys=[] pD, pla, c = readCPxDto('test1008.csv') for i in range(len(pathDic)): d = pla[i] for j in range(len(pathDic[d])): x, y = m(pD[d][j]['x'], pD[d][j]['y']) xs.append(x) ys.append(y) plt.plot(x, y,'ok',markersize=1,color='purple') plt.text(x, y, pD[d][j]['name'], fontsize=7) del x del y m.plot(xs, ys, color='r', linewidth=3, label='Flight 98')
def get_map(tweetsp,tweetsn,tweetsnu,len_p,len_n,len_nu,df,sw): plt.figure(figsize=(13, 13)) m = Basemap(projection='cyl', resolution='c') m.drawcountries(linewidth=1, linestyle='solid', color='grey', antialiased=1, ax=None, zorder=None) m.etopo(scale=0.7, alpha=0.7) pos = mpatches.Patch(color='green', label='Positive') neg = mpatches.Patch(color='red', label='Negative') neu = mpatches.Patch(color='blue', label='Neutral') xx=[] yy=[] print("POSITIVE PLOTS") for i in range(len_p): lat,lon=tweetsp['tweet'][i]['Coordinates'] x,y=m(lat,lon) #xx.append(x) #yy.append(y) coordinates=[(x,y)] df=update_df(coordinates,df,'Positive') #print("x and y values",x,y) #print("Location",tweetsp['tweet'][i]['Location']) m.plot(lon, lat, marker= 'o', markersize=7, color='green', label = 'Positive') #plt.text(lon, lat, tweetsp['tweet'][i]['Location'], fontsize=7) print("NEGATIVE PLOTS") for i in range(len_n): lat,lon=tweetsn['tweet'][i]['Coordinates'] x,y=m(lat,lon) #xx.append(x) #yy.append(y) coordinates=[(x,y)] df=update_df(coordinates,df,'Negative') # print("x and y values",x,y) # print("Location",tweetsn['tweet'][i]['Location']) m.plot(lon, lat, marker= 'o', markersize=7, color='red', label='Negative') #plt.text(lon, lat, tweetsn['tweet'][i]['Location'], fontsize=7) print("NEUTRAL PLOTS") for i in range(len_nu): lat,lon=tweetsnu['tweet'][i]['Coordinates'] x,y=m(lat,lon) #xx.append(x) # yy.append(y) coordinates=[(x,y)] df=update_df(coordinates,df,'Neutral') # print("x and y values",x,y) # print("Location",tweetsnu['tweet'][i]['Location']) m.plot(lon, lat, marker= 'o', markersize=7, color='blue', label='Neutral') #plt.text(lon, lat, tweetsnu['tweet'][i]['Location'], fontsize=7) plt.legend(handles=[pos,neg,neu], loc=3) plt.show(block=False) Choroplet(df,sw)
def build_map(marker_size): map = Basemap(ax=ax1) # map = Basemap(projection='robin',lon_0=0,resolution='c') #plt.title("Robinson Projection") map.etopo() # 'contour' # map.bluemarble() #'satellite' # draw coastlines, parallels and meridians. map.drawcoastlines() map.drawparallels(np.arange(-90., 120., 5.)) map.drawmeridians(np.arange(0., 360., 5.)) # ------------------------------ # size/color marking points # msize = marker_size # global plot_handle # # global xs, ys # xs, ys = [], [] # for lon, lat, mag in zip(lons, lats, mags): # x, y = map(lon, lat) # xs.append(x) # ys.append(y) # msize = mag * min_marker_size # marker_string = get_marker_color(mag) # plot_handle, = map.plot(x, y, marker_string, markersize=msize) # draw filled contours. # global filename # grid = VG.load_from_csv(filename) # x_new_array, y_new_array, data_new_array = grid.get_values(0, 0) # cs = map.contourf(x_new_array, y_new_array, data_new_array, levels,colors = ('r', 'y', 'g', 'c', 'b')) x, y, data = grid.get_values(0, 0) mag_max = np.amax(data) levels = [ 0, (mag_max / 5) * 1, (mag_max / 5) * 2, (mag_max / 5) * 3, (mag_max / 5) * 4, (mag_max / 5) * 5 ] # colors = ('r', 'y', 'g', 'c', 'b') # transparent colors cols = colors.colorConverter.to_rgba_array([(1, 0, 0, 0.5), (1, 1, 0, 0.5), (0, 1, 0, 0.5), (0, 1, 1, 0.5), (0, 0, 1, 0.5)]) cs = map.contourf(x, y, data, levels, colors=cols) # add colorbar. global cbar if cbar: fig.delaxes(cbar) cbar = map.colorbar(cs, location='bottom', pad="5%") cbar.set_label('mm')
def plt_map(local_time): """ :param local_time: :return: """ plt.figure() map = Basemap(llcrnrlon=270., llcrnrlat=15., urcrnrlon=330., urcrnrlat=47., projection='lcc', lat_1=20., lat_2=40., lon_0=300., resolution='l', area_thresh=1000.) map.drawcoastlines() map.drawcountries() map.drawmapboundary() map.fillcontinents(color='0.', lake_color='#99ffff') map.drawparallels(np.arange(10, 70, 20), labels=[1, 1, 0, 0]) map.drawmeridians(np.arange(-100, 0, 20), labels=[0, 0, 0, 1]) plt.title("Simulated particule trajectories from AVISO maps") timestep_particule = np.ma.masked_where( (time > local_time + 2) | (time < local_time - 2), track) timestep_lon = np.ma.masked_where( (time > local_time + 2) | (time < local_time - 2), lon) timestep_lat = np.ma.masked_where( (time > local_time + 2) | (time < local_time - 2), lat) # loop over timestep particule trajectory for particule in np.unique(timestep_particule): particule_lon = np.ma.masked_where(timestep_particule != particule, timestep_lon).compressed() particule_lat = np.ma.masked_where(timestep_particule != particule, timestep_lat).compressed() XX, YY = map(particule_lon, particule_lat) if XX.size: map.scatter(XX[XX.size - 1], YY[YY.size - 1], c='orange', s=20, edgecolors=None, linewidths=0) map.plot(XX, YY, linewidth=1, color='orange') # np.random.rand(3,1)) map.etopo() plt.savefig('trajectories_%04d.png' % int(local_time)) plt.close()
def render_components(C, lats, lons, fname_tmpl=None, ndx=None): """ Render the components in C [with dims comp_id x lats x lons] onto a world map of appropriate size. The method assumes that the lons x lats generate a rectangle. """ m = Basemap(projection='mill', llcrnrlat=min(lats), urcrnrlat=max(lats), llcrnrlon=(min(lons)), urcrnrlon=max(lons), resolution='c') if ndx == None: ndx = np.arange(len(C)) + 1 rmax = np.max(C) # lattitudes may not be sorted in ascending order, rectify this lat_ndx = np.argsort(lats) lats_s = lats[lat_ndx] # render each topo plot for ci in range(len(C)): plt.figure(figsize=(12, 8 * (max(lats) - min(lats)) / 180)) plt.axes([0.05, 0.05, 0.9, 0.85]) m.drawcoastlines() #m.fillcontinents(color='coral',lake_color='aqua', zorder = 0) m.etopo(scale=0.2) # draw parallels and meridians. m.drawparallels(np.arange(-90., 91., 30.)) m.drawmeridians(np.arange(0., 361., 60.)) #m.drawmapboundary(fill_color='aqua') nx = int((m.xmax - m.xmin) / 20000) + 1 ny = int((m.ymax - m.ymin) / 20000) + 1 Ci = C[ci, lat_ndx, :] f = m.transform_scalar(Ci, lons, lats_s, nx, ny) # imlim seems to be equivalent to caxis() im MATLAB imgplt = m.imshow(f, alpha=0.8) imgplt.set_clim(-rmax, rmax) plt.colorbar() plt.title('Component %d' % (ndx[ci])) if fname_tmpl: plt.savefig(fname_tmpl % (ndx[ci])) if not fname_tmpl: plt.show()
def draw2DNetWorkOnMap(showOrSave, netWorkG, geoAgentShpPath, edgeColorF, nodeColorF): """ @param showOrSave 'show','save' @param netWorkG: netWorkG nx.DiGraph @param geoAgentShpPath: geoAgentShpPath shapefile by ESRI @param edgeColorF: edgeColorField str @param nodeColorF: nodeColorField str @return: just show Map """ plt.figure(figsize=(20, 15), dpi=300) worldMap = Basemap( projection='robin', lon_0=0, resolution='l', ) # Now draw the map # worldMap.drawcountries(linewidth=0.5) # worldMap.drawstates() # worldMap.drawcoastlines(linewidth=0.5) # fill in color # worldMap.fillcontinents(color='gray', lake_color='#7396FE') # worldMap.drawmapboundary(fill_color='#7396FE', color='#404243', linewidth=0.5) # draw lon and lat # worldMap.drawparallels(np.arange(-90., 91., 30.)) # worldMap.drawmeridians(np.arange(-180., 181., 30.)) # worldMap.bluemarble(scale=0.5, alpha=0.8) # worldMap.shadedrelief() worldMap.etopo(scale=0.5, alpha=0.5) worldMap.readshapefile(geoAgentShpPath, 'GeoAgent', color='#818487', linewidth=0.5) mapTitle = 'NetWork ' + netWorkG.graph['VarSou'] + ' to ' + netWorkG.graph['VarTar'] + ' By THRILLER' plt.title(mapTitle) pos = {} for n, d in netWorkG.nodes(data=True): # convert lat and lon to map projection mx, my = worldMap(d['longitude'], d['latitude']) pos[n] = (mx, my) nx.draw_networkx_edges(netWorkG, pos, width=0.2, alpha=0.8, edge_color=[float(d[edgeColorF]) for (u, v, d) in netWorkG.edges(data=True)], edge_cmap=plt.cm.Purples, arrows=True, arrowstyle='fancy', arrowsize=2, connectionstyle="arc3,rad=0.1") # first draw point's edge in black nx.draw_networkx_nodes(netWorkG, pos, node_size=[netWorkG.degree(n) * 1.7 for n in netWorkG], node_color='k') nx.draw_networkx_nodes(netWorkG, pos, node_size=[netWorkG.degree(n) * 1.5 for n in netWorkG], node_color=[d[nodeColorF] for n, d in netWorkG.nodes(data=True)], cmap=plt.cm.OrRd) # nx.draw_networkx_labels(netWorkG, pos, font_size=11, font_family='Times New Roman', font_color='k') if showOrSave == 'show': # max windows plt.get_current_fig_manager().window.showMaximized() plt.show() if showOrSave == 'save': plt.savefig(outPutPath + mapTitle + ".png")
def BrowseFigures(self, datadir='', dirPFX='', dirSFX='', datatype='All', depLimit=None, \ llcrnrlon=None, llcrnrlat=None,urcrnrlon=None,urcrnrlat=None, browseflag=True, saveflag=False): if llcrnrlon==None or llcrnrlat==None or urcrnrlon==None or urcrnrlat==None: llcrnrlon=self.minlon llcrnrlat=self.minlat urcrnrlon=self.maxlon urcrnrlat=self.maxlat # print llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat for geopoint in self.geopoints: print 'Plotting:'+geopoint.name if geopoint.depthP.size==0 and geopoint.DispGr.size==0 and geopoint.DispPh.size==0: continue plt.close('all') fig=plb.figure(num=None, figsize=(8, 12), dpi=80, facecolor='w', edgecolor='k') if datatype=='All': fig.add_subplot(3,1,1) else: fig.add_subplot(2,1,1) m = Basemap(llcrnrlon=llcrnrlon-1, llcrnrlat=llcrnrlat-1, urcrnrlon=urcrnrlon+1, urcrnrlat=urcrnrlat+1, \ rsphere=(6378137.00,6356752.3142), resolution='l', projection='merc') lon = geopoint.lon lat = geopoint.lat x,y = m(lon, lat) m.plot(x, y, 'ro', markersize=5) m.drawcoastlines() m.etopo() # m.fillcontinents() # draw parallels m.drawparallels(np.arange(-90,90,10),labels=[1,1,0,1]) # draw meridians m.drawmeridians(np.arange(-180,180,10),labels=[1,1,0,1]) plt.title('Longitude:'+str(geopoint.lon)+' Latitude:'+str(geopoint.lat), fontsize=15) if datatype=='All': geopoint.PlotDispBoth(ax=plt.subplot(3,1,2)) # geopoint.PlotDisp(datatype='GrV', ax=plt.subplot(3,1,2)) geopoint.PlotVProfile(ax=plt.subplot(3,1,3), depLimit=depLimit) elif datatype=='DISP': # geopoint.PlotDisp(datatype='PhV',ax=plt.subplot(3,1,2)) # geopoint.PlotDisp(datatype='GrV',ax=plt.subplot(3,1,2)) geopoint.PlotDispBoth(ax=plt.subplot(3,1,2)) elif datatype=='VPr': geopoint.PlotVProfile(depLimit=depLimit,ax=plt.subplot(2,1,2)) else: raise ValueError('Unknown datatype') fig.suptitle('Longitude:'+str(geopoint.lon)+' Latitude:'+str(geopoint.lat), fontsize=15) if browseflag==True: plt.draw() plt.pause(1) # <------- raw_input("<Hit Enter To Close>") plt.close('all') if saveflag==True and datadir!='': fig.savefig(datadir+'/'+dirPFX+geopoint.name+dirSFX+'/'+datatype+'_'+geopoint.name+'.ps', format='ps') return;
def prepare_background(map_type): """ Create an cylindrical equidistant map projection using low resolution coastlines. """ outfile = os.path.join(*PLOT_DIR, '%s_map.png' % map_type) print("Generating Background Map %s ..." % outfile) fig = plt.figure(1) left = 0.0 bottom = 0.0 width = 1.0 height = 1.0 ax = fig.add_axes([left, bottom, width, height]) print(' Creating Generic Basemap...') map = Basemap(projection='cyl', llcrnrlon=-180, llcrnrlat=-90, urcrnrlon=180, urcrnrlat=90, resolution='l', ax=ax) print(' Adding features - lines...') # draw coastlines, country boundaries, state boundaries map.drawcoastlines(linewidth=0.25) map.drawcountries(linewidth=0.25) map.drawstates(linewidth=0.15) print(' Adding features - land/ocean...') if map_type == 'basic': map.drawlsmask(land_color='white', ocean_color='aqua', resolution='l') map.drawlsmask(resolution='l') elif map_type == 'marble': map.bluemarble() elif map_type == 'etopo': map.etopo() else: # default 'shaded' map.shadedrelief() print(' Saving...') ax.axis('off') fig.savefig(outfile, frameon=False, bbox_inches='tight', pad_inches=0, dpi=600) plt.clf() plt.close() gc.collect()
def plt_area(fign): fig = plt.figure(fign, facecolor='w') ax = plt.gca() # Projection + Map properties m = Basemap(projection='ortho', lat_0=-30, lon_0=-15, resolution='l', ax=ax) # Meridians and parallels m.drawmeridians(np.arange(0, 360, 30)) m.drawparallels(np.arange(-90, 90, 30)) # Topography m.etopo() # Study Area Polygon rlon = [ -70., -60, -50, -40, -30, -20, -10, 0, 10, 20, 20, 20., 20, 20, 20, 20, 20, 20, 20, 10, 0, -10, -20, -30, -40, -50, -60, -70, -70., -70., -70, -70, -70, -70, -70, -70, -70 ] rlat = [ -5., -5., -5, -5, -5, -5, -5, -5, -5, -5, -10, -15, -20, -25, -30, -35, -40, -45, -50., -50, -50, -50, -50, -50, -50, -50, -50., -50, -45, -40, -35, -30, -25, -20, -15, -10, -5 ] rlon, rlat = m(rlon, rlat) ax.plot(rlon, rlat, color='k', linestyle='dashed', lw=5.) tkw = dict(fontsize=22, fontweight='demibold') # Box info tlon, tlat = m(25, -8) ax.text(tlon, tlat, ur'5$^{\circ}$S', **tkw) tlon, tlat = m(25, -53) ax.text(tlon, tlat, ur'50$^{\circ}$S', **tkw) tlon, tlat = m(-80, 8) ax.text(tlon, tlat, ur'70$^{\circ}$W', rotation=25, **tkw) tlon, tlat = m(20, -2) ax.text(tlon, tlat, ur'20$^{\circ}$E', **tkw) # plt.draw() # plt.show(block=False) return fig
def testMap(X): # setup Lambert Conformal basemap. # set resolution=None to skip processing of boundary datasets. (x_min,y_min),(x_max,y_max) = findLim(X) kx,ky = 0.,0. (x_min,y_min),(x_max,y_max) = (-1.42352-kx,50.930738-ky),(-0.956601+kx,51.086704+ky) x_mid,y_mid = (x_max-x_min)/2., (y_max-y_min)/2. m = Basemap(llcrnrlon=x_min,llcrnrlat=y_min,urcrnrlon=x_max,urcrnrlat=y_max, resolution='i',projection='tmerc',lon_0=x_mid,lat_0=y_min) #adapted from: http://matplotlib.org/basemap/users/tmerc.html m.drawcoastlines() #m.bluemarble() #m.shadedrelief() m.etopo() show()
def render_components(C, lats, lons, fname_tmpl = None, ndx = None): """ Render the components in C [with dims comp_id x lats x lons] onto a world map of appropriate size. The method assumes that the lons x lats generate a rectangle. """ m = Basemap(projection='mill',llcrnrlat=min(lats), urcrnrlat=max(lats), llcrnrlon=(min(lons)), urcrnrlon=max(lons),resolution='c') if ndx == None: ndx = np.arange(len(C)) + 1 rmax = np.max(C) # lattitudes may not be sorted in ascending order, rectify this lat_ndx = np.argsort(lats) lats_s = lats[lat_ndx] # render each topo plot for ci in range(len(C)): plt.figure(figsize=(12, 8 * (max(lats) - min(lats)) / 180)) plt.axes([0.05, 0.05, 0.9, 0.85]) m.drawcoastlines() #m.fillcontinents(color='coral',lake_color='aqua', zorder = 0) m.etopo(scale = 0.2) # draw parallels and meridians. m.drawparallels(np.arange(-90.,91.,30.)) m.drawmeridians(np.arange(0.,361.,60.)) #m.drawmapboundary(fill_color='aqua') nx = int((m.xmax-m.xmin) / 20000) + 1 ny = int((m.ymax-m.ymin) / 20000) + 1 Ci = C[ci, lat_ndx, :] f = m.transform_scalar(Ci, lons, lats_s, nx, ny) # imlim seems to be equivalent to caxis() im MATLAB imgplt = m.imshow(f, alpha = 0.8) imgplt.set_clim(-rmax, rmax) plt.colorbar() plt.title('Component %d' % (ndx[ci])) if fname_tmpl: plt.savefig(fname_tmpl % (ndx[ci])) if not fname_tmpl: plt.show()
def plot_map(year, disease, color_parameter, std_num_records): mpl.rcParams['font.size'] = 10. mpl.rcParams['font.family'] = 'Comic Sans MS' mpl.rcParams['axes.labelsize'] = 8. mpl.rcParams['xtick.labelsize'] = 6. mpl.rcParams['ytick.labelsize'] = 6. fig = plt.figure(figsize=(11.7, 8.3)) plt.style.use('fivethirtyeight') plt.subplots_adjust(left=0.05, right=0.95, top=0.90, bottom=0.05, wspace=0.15, hspace=0.05) ax = plt.subplot(111) m = Basemap(resolution='i', projection='merc', llcrnrlon=-132, llcrnrlat=22, urcrnrlon=-60, urcrnrlat=50) m.etopo() m.drawcountries() for record, shape, num in zip(records, shapes, std_num_records): lons, lats = zip(*shape.points) data = np.array(m(lons, lats)).T if len(shape.parts) == 1: segs = [ data, ] else: segs = [] for i in range(1, len(shape.parts)): index = shape.parts[i - 1] index2 = shape.parts[i] segs.append(data[index:index2]) segs.append(data[index2:]) lines = LineCollection(segs, antialiaseds=(1, )) color = colors.hsv_to_rgb((color_parameter, num, 1)) lines.set_facecolor(color) lines.set_edgecolors('k') lines.set_linewidth(0.1) ax.add_collection(lines) m.drawstates(linewidth=0.5) m.drawcoastlines(linewidth=0.5) plt.title('geo-heatmap for {} in {}'.format(disease, year)) plt.savefig('geo-heatmap for {} in {}.pdf'.format(disease, year))
def coolerProjections(): #m = Basemap(projection='mill',llcrnrlat=47.1,urcrnrlat=55.2, llcrnrlon=5.5,urcrnrlon=15.3, resolution='l') m = Basemap(width=12000000,height=9000000,projection='lcc', resolution='l',lat_1=5,lat_2=6,lat_0=52,lon_0=9) #m.drawcountries(linewidth=1.5) #m.drawcoastlines(linewidth=1.5) #m.drawstates() #m.bluemarble() m.etopo() plt.title("GCF") plt.show()
def plot_bounds(bounds, center, radius): coord_list = bounds2coords(bounds, center) fig = plt.figure(figsize=(8,8)) ax = fig.add_subplot(111) center = np.rad2deg(center) coord_list = np.rad2deg(coord_list) m = Basemap(projection='moll', resolution=None, width=12E6, height=12E6, lat_0=center[1], lon_0=center[0],) m.etopo(scale=0.5, alpha=0.5) for i, coord in enumerate(coord_list): x, y = m(coord[0], coord[1]) plt.plot(x, y, 'ok', markersize = 5) #plt.text(x, y, names[i], fontsize=12) circle1 = plt.Circle(xy=m(*center), radius=convert_rad_m(radius), edgecolor="blue", zorder=10) ax.add_artist(circle1) plt.show()
def plot_coords(coord_list, center=None, names=None): fig = plt.figure(figsize=(8,8)) if not center: print('no center') center = [0.0, 0.0] center = np.rad2deg(center) coord_list = np.rad2deg(coord_list) m = Basemap(projection='moll', resolution=None, width=12E6, height=12E6, lat_0=center[1], lon_0=center[0],) m.etopo(scale=0.5, alpha=0.5) if not names: names = ['N', 'S', 'E', 'W'] for i, coord in enumerate(coord_list): x, y = m(coord[0], coord[1]) plt.plot(x, y, 'ok', markersize = 5) plt.text(x, y, names[i], fontsize=12) plt.show()
def main(): ds = nC.Dataset("../../grid_arctic.nc") data = ds.variables["tas"][:].squeeze() lon2d_nc = ds.variables["lon"][:] lat2d_nc = ds.variables["lat"][:] rplon, rplat = -115.850877297, 21.1216893478 lon_0 = -123.403723307 basemap = Basemap(projection="rotpole", o_lon_p=rplon, o_lat_p=rplat, lon_0=lon_0 - 180, llcrnrlon=lon2d_nc[-1, -1], llcrnrlat=lat2d_nc[-1, -1], urcrnrlon=lon2d_nc[0, 0], urcrnrlat=lat2d_nc[0, 0], resolution="l") import matplotlib.pyplot as plt im = basemap.etopo() x, y = basemap(lon2d_nc, lat2d_nc) # basemap.contourf(x, y, data) # basemap.colorbar() # basemap.drawcoastlines() # basemap.drawmeridians(np.arange(-180, 180, 30)) # basemap.drawparallels(np.arange(-90, 90, 40)) plt.show() pass
def plt_area(fign): fig = plt.figure(fign,facecolor='w') ax = plt.gca() # Projection + Map properties m = Basemap(projection='ortho',lat_0=-30,lon_0=-15,resolution='l',ax=ax) # Meridians and parallels m.drawmeridians(np.arange(0,360,30)) m.drawparallels(np.arange(-90,90,30)) # Topography m.etopo() # Study Area Polygon rlon = [-70.,-60,-50,-40,-30,-20,-10,0,10,20, 20,20.,20,20,20,20,20,20,20, 10,0,-10,-20,-30,-40,-50,-60,-70, -70.,-70.,-70,-70,-70,-70,-70,-70,-70] rlat = [-5.,-5.,-5,-5,-5,-5,-5,-5,-5,-5, -10,-15,-20,-25,-30,-35,-40,-45,-50., -50,-50,-50,-50,-50,-50,-50,-50.,-50, -45,-40,-35,-30,-25,-20,-15,-10,-5] rlon,rlat = m(rlon,rlat) ax.plot(rlon,rlat,color='k',linestyle='dashed',lw=5.) tkw = dict(fontsize=22,fontweight='demibold') # Box info tlon,tlat = m(25,-8) ax.text(tlon,tlat,ur'5$^{\circ}$S',**tkw) tlon,tlat = m(25,-53) ax.text(tlon,tlat,ur'50$^{\circ}$S',**tkw) tlon,tlat = m(-80,8) ax.text(tlon,tlat,ur'70$^{\circ}$W',rotation=25,**tkw) tlon,tlat = m(20,-2) ax.text(tlon,tlat,ur'20$^{\circ}$E',**tkw) # plt.draw() # plt.show(block=False) return fig
def show_coord_topo_mill(windmill, show = True): """Plot the topology of a windmill Topographic Map with farms see: http://matplotlib.org/basemap/users/examples.html Basemap Parameters ---------- windmill : Windmill The given windmill to show the topology. """ radius = 20 coord = [0.0, 0.0] coord[0] = np.float64(windmill.latitude) coord[1] = np.float64(windmill.longitude) graddiff = (radius/111.0) + 0.5 # degree in km m = Basemap(projection='stere', lon_0=coord[1], lat_0=coord[0],\ llcrnrlon = coord[1]-graddiff, llcrnrlat = coord[0]-graddiff ,\ urcrnrlon = coord[1]+graddiff, urcrnrlat = coord[0]+graddiff ,\ rsphere=6371200., resolution = 'l', area_thresh=1000) # Target x_mill,y_mill = m(coord[1],coord[0]) # labels = [left,right,top,bottom] parallels = np.arange(int(coord[0]-3), int(coord[0]+3), 1.) m.drawparallels(parallels,labels=[False,True,True,False]) meridians = np.arange(int(coord[1]-3), int(coord[1]+3), 1.) m.drawmeridians(meridians,labels=[True,False,False,True]) # plot farms in the radius m.plot(x_mill, y_mill, 'bo') #m.bluemarble() m.etopo() m.drawcoastlines() plt.title("Topography around a Mill") if(show): plt.show()
def plot_tweets(lat=[0], long=[0], text='', heat=False): plt.style.use('ggplot') lon_0 = -125 #further west if negative, further east if not lon_1 = -66 lat_0 = 25 lat_1 = 52 # create figure and axes instances plt.clf() dim = 6 fig = plt.figure(figsize=(dim,(225/494)*dim)) #ax = fig.add_subplot(111) ax = fig.add_axes([0,0 ,1,1]) # create polar stereographic Basemap instance. m = Basemap(llcrnrlat=lat_0,urcrnrlat=lat_1, llcrnrlon=lon_0, urcrnrlon=lon_1, resolution='l') m.drawcoastlines() m.drawcountries() if random.random() > 0.5: m.fillcontinents(color='tan') elif random.random() > 0.5: m.bluemarble() elif random.random() > 0.5: m.shadedrelief() elif random.random() > 0.5: m.etopo() elif random.random() > 0.5: m.drawmapboundary(fill_color='aqua') if heat: for i, l in enumerate(lat): lat[i] = lat[i] + random.random()*0.1 long[i] = long[i] + random.random()*0.1 p = ax.plot(long, lat, 'p') else: p = ax.plot(long, lat, 'p') if text is not None: for i, ht in enumerate(text): if len(lat) > i: ax.annotate(ht, (long[i], lat[i]), rotation=random.random()*45.) plt.savefig('/tmp/twitmap.png')
def mapping(self, language, coordinates): self.path = path.join(path.dirname(__file__), 'geomap.png') #define path for result picture self.fig = plt.figure(figsize=(18, 4), dpi=150) #basemap figure details plt.title("Tweets zu #Legion #Warcraft und #WorldofWarcraft") #sets the title for the results m = Basemap(projection='merc', llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180,urcrnrlon=180, lat_ts=20, resolution='l') #basemap default settings m.etopo(scale=0.3) #basemap style plt.ion() plt.show() for elem in coordinates: #marking geo tags on map with language color self.x, self.y = m(coordinates[elem][0], coordinates[elem][1]) if language[elem] == 'en': m.plot(self.x, self.y, 'ro', markersize=4) #red for english elif language[elem] == 'en-gb': m.plot(self.x, self.y, 'ro', markersize=4) #red for english elif language[elem] == 'de': m.plot(self.x, self.y, 'go', markersize=4) #green for german elif language[elem] == 'fr': m.plot(self.x, self.y, 'bo', markersize=4) #blue for french elif language[elem] == 'es': m.plot(self.x, self.y, 'yo', markersize=4) #yellow for spanish elif language[elem] == 'ru': m.plot(self.x, self.y, 'co', markersize=4) #cyan for russian elif language[elem] == 'it': m.plot(self.x, self.y, 'mo', markersize=4) #magenta for italian elif language[elem] == 'und': m.plot(self.x, self.y, 'wo', markersize=4) #white for undefined plt.draw() plt.ioff() plt.show() self.fig.savefig(self.path, transparent=True, bbox_inches='tight') #saving result to geomap.png return plt.close()
def mapSubject(dataset,subject,box='tight',level='auto', longest=20,call='default',highlight=False, heatmap=True, mark = 'r', cmap='YlOrRd', show = True, offset = 0, subtitle = '', geobox = 'null', important = 'null',background = 'none'): if call == 'animate': plt.clf() else: fig = plt.figure(figsize=(9,9)) if geobox == 'null' or (type(box) is str and type(geobox) is str): box = fixBox(dataset,box) else: box = geobox lats, lons, times = getData(dataset,offset) mapped = Basemap(projection='mill', llcrnrlon=box['lon1'], llcrnrlat=box['lat1'], urcrnrlon=box['lon2'], urcrnrlat=box['lat2']) mapOpacity = 0.75 if background == 'etopo': mapped.etopo(zorder=0, alpha=mapOpacity) elif background == 'shaded relief': mapped.shadedrelief(zorder=0, alpha=mapOpacity) elif background == 'blue marble': mapped.bluemarble(zorder=0, alpha=mapOpacity) elif '/' in background or '.' in background: try: mapped.warpimage(image='maps/'+background, scale=None, zorder=0, alpha=mapOpacity) except: mapped.warpimage(image=background, scale=None, zorder=0, alpha=mapOpacity) else: background = 'null' smallest = min(box['lat2']-box['lat1'],box['lon2']-box['lon1']) mapped.drawcoastlines(zorder=3) if smallest < 5: mapped.drawcountries(zorder=3,linewidth = 3) mapped.drawstates(zorder=3, linewidth = 2) mapped.drawcounties(zorder=3,linewidth = 1) else: mapped.drawcountries(zorder=3,linewidth = 2) mapped.drawstates(zorder=3, linewidth = 1) if heatmap: # ###################################################################### # http://stackoverflow.com/questions/11507575/basemap-and-density-plots) density, lon_bins, lat_bins = getDensity(box,lats,lons,longest) lon_bins_2d, lat_bins_2d = np.meshgrid(lon_bins, lat_bins) xs, ys = mapped(lon_bins_2d, lat_bins_2d) # will be plotted using pcolormesh # ###################################################################### if level == 'auto': level = np.amax(density) density = fixDensity(density,xs,ys) if background == 'null': plt.pcolormesh(xs, ys, density, cmap = cmap,zorder=2, alpha = 1, vmin =1) else: extent = (xs[0][0],xs[0][-1],ys[0][0],ys[-1][0]) colorized = mapColors(density,level,cmap) colorized = mapTransparency(density,colorized,level) plt.imshow(colorized, extent=extent,cmap=cmap,origin='lower',interpolation='nearest',zorder=2) smallest = min(box['lat2']-box['lat1'],box['lon2']-box['lon1']) if smallest < 1.0: gridIncrement = 0.1 if smallest < 2.5: gridIncrement = 0.5 elif smallest < 5: gridIncrement = 1.0 elif smallest < 10: gridIncrement = 2.5 else: gridIncrement = 5.0 parallels = np.arange(-90.,90.,gridIncrement) mapped.drawparallels(parallels,labels=[1,0,0,0],fontsize=10, alpha = .75) meridians = np.arange(-180.,180.,gridIncrement) mapped.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10, alpha = .75) if important != 'null': xI,yI = mapped(important[0],important[1]) xM,yM = mapped(np.mean(lons),np.mean(lats)) mapped.plot(xI,yI,'o',markersize=15, zorder=6, markerfacecolor = "white", markeredgecolor=mark, alpha = 1.0) mapped.plot(xM,yM,'x',markersize=15, zorder=6, markerfacecolor = "white", markeredgecolor=mark, alpha = 1.0) x, y = mapped(lons, lats) # compute map proj coordinates. mapped.plot(x, y, 'o', markersize=4,zorder=6, markerfacecolor=mark,markeredgecolor="none", alpha=0.30) if highlight != False: mapped.plot(x, y, 'o', markersize=4,zorder=6, markerfacecolor=highlight,markeredgecolor="none", alpha=0.03) title = '%s search for "%s",\n%s Related Tweets Found from\n%s to %s' % (dataset['name'], subject, len(dataset['data']), times[0], times[-1]) plt.title(title) if subtitle != '': plt.xlabel(subtitle) if heatmap: divider = make_axes_locatable(plt.gca()) cax = divider.append_axes("right", "5%", pad="3%") cbar = plt.colorbar(orientation='vertical',cax=cax) if level != 'full': plt.clim([0,level]) cbar.set_label('Number of Tweets') if call != 'animate' and show: plt.show() return plt
fig, ax = plt.subplots(1) plt.suptitle(analyte) m = Basemap(projection='merc', resolution='c', llcrnrlon=ll[1], llcrnrlat=ll[0], urcrnrlon=ur[1], urcrnrlat=ur[0], ax=ax) m.readshapefile(datadir+'sd_river','sd_river',color='b') sc = m.scatter(df['Lon'].values,df['Lat'].values,latlon=True, s= scaleSeries(df['Avg'].values), c=df['Avg'].values,cmap=plt.get_cmap('rainbow'),edgecolor='None') for d in df.iterrows(): name = d[0] name d = d[1] x_i, y_i = m(float(d['Lon']), float(d['Lat'])) plt.text(x_i, y_i, name) m.etopo() m.drawparallels(np.arange(ll[0],ur[0],.02),labels=[1,0,0,0]) m.drawmeridians(np.arange(ll[1],ur[1],.02),labels=[0,0,1,0],rotation=60) from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(m.ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar=plt.colorbar(sc,cax=cax) plt.savefig(maindir+'Figures/'+analyte+' Long term avg.png') plt.show() plt.close('all')
def plot_event(catalog, projection='cyl', resolution='l', continent_fill_color='0.9', water_fill_color='white', label= None, color='depth', pretty = False, colormap=None, llat = -90, ulat = 90, llon = -180, ulon = 180, figsize=(16,24), par_range = (-90., 120., 30.), mer_range = (0., 360., 60.), showHour = False, M_above = 0.0, location = 'World', **kwargs): # @UnusedVariable """ Creates preview map of all events in current Catalog object. :type projection: str, optional :param projection: The map projection. Currently supported are * ``"cyl"`` (Will plot the whole world.) * ``"ortho"`` (Will center around the mean lat/long.) * ``"local"`` (Will plot around local events) Defaults to "cyl" :type resolution: str, optional :param resolution: Resolution of the boundary database to use. Will be based directly to the basemap module. Possible values are * ``"c"`` (crude) * ``"l"`` (low) * ``"i"`` (intermediate) * ``"h"`` (high) * ``"f"`` (full) Defaults to ``"l"`` :type continent_fill_color: Valid matplotlib color, optional :param continent_fill_color: Color of the continents. Defaults to ``"0.9"`` which is a light gray. :type water_fill_color: Valid matplotlib color, optional :param water_fill_color: Color of all water bodies. Defaults to ``"white"``. :type label: str, optional :param label:Events will be labeld based on the chosen property. Possible values are * ``"magnitude"`` * ``None`` Defaults to ``"magnitude"`` :type color: str, optional :param color:The events will be color-coded based on the chosen proberty. Possible values are * ``"date"`` * ``"depth"`` Defaults to ``"depth"`` :type colormap: str, optional, any matplotlib colormap :param colormap: The colormap for color-coding the events. The event with the smallest property will have the color of one end of the colormap and the event with the biggest property the color of the other end with all other events in between. Defaults to None which will use the default colormap for the date encoding and a colormap going from green over yellow to red for the depth encoding. .. rubric:: Example >>> cat = readEvents( \ "http://www.seismicportal.eu/services/event/search?magMin=8.0") \ # doctest:+SKIP >>> cat.plot() # doctest:+SKIP """ from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt from matplotlib.colors import Normalize from matplotlib.cm import ScalarMappable import matplotlib as mpl if color not in ('date', 'depth'): raise ValueError('Events can be color coded by date or depth. ' "'%s' is not supported." % (color,)) if label not in (None, 'magnitude', 'depth'): raise ValueError('Events can be labeled by magnitude or events can' ' not be labeled. ' "'%s' is not supported." % (label,)) if location == 'US': llon=-125 llat=20 ulon=-60 ulat=60 lat_0=38 lon_0=-122.0 par_range = (20, 61, 10) mer_range = (-120, -59, 20) elif location == 'CA': llat = '30' ulat = '45' llon = '-130' ulon = '-110' lat_0=38 lon_0=-122.0 par_range = (30, 46, 5) mer_range = (-130, -109, 10) else: lat_0=0 lon_0=0 lats, lons, mags, times, labels, colors = get_event_info(catalog, M_above, llat, ulat, llon, ulon, color, label) min_color = min(colors) max_color = max(colors) # Create the colormap for date based plotting. if colormap is None: if color == "date": colormap = plt.get_cmap() else: # Choose green->yellow->red for the depth encoding. colormap = plt.get_cmap("RdYlGn_r") scal_map = ScalarMappable(norm=Normalize(min_color, max_color), cmap=colormap) scal_map.set_array(np.linspace(0, 1, 1)) fig = plt.figure(figsize = figsize) # The colorbar should only be plotted if more then one event is # present. if len(catalog) > 1: map_ax = fig.add_axes([0.03, 0.13, 0.94, 0.82]) #cm_ax = fig.add_axes([0.03, 0.05, 0.94, 0.05]) #rect = [left, bottom, width, height] cm_ax = fig.add_axes([0.98, 0.39, 0.04, 0.3]) plt.sca(map_ax) else: map_ax = fig.add_axes([0.05, 0.05, 0.90, 0.90]) if projection == 'cyl': map = Basemap(resolution=resolution, lat_0 = lat_0, lon_0 = lon_0, llcrnrlon=llon,llcrnrlat=llat,urcrnrlon=ulon,urcrnrlat=ulat) elif projection == 'ortho': map = Basemap(projection='ortho', resolution=resolution, area_thresh=1000.0, lat_0=sum(lats) / len(lats), lon_0=sum(lons) / len(lons)) 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) + min(lats)) / 2. lon_0 = (max_lons + 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 map = Basemap(projection='aeqd', resolution=resolution, area_thresh=1000.0, lat_0=lat_0, lon_0=lon_0, width=width, height=height) # 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))) delta = round(2. * dval / N, round_pos) / 2 new_val1 = np.ceil(val1 / delta) * delta new_val2 = np.floor(val2 / delta) * delta N = (new_val2 - new_val1) / delta + 1 return np.linspace(new_val1, new_val2, N) N1 = int(np.ceil(height / max(width, height) * 8)) N2 = int(np.ceil(width / max(width, height) * 8)) map.drawparallels(linspace2(lat_0 - height / 2 / deg2m_lat, lat_0 + height / 2 / deg2m_lat, N1), 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, N2) meridians[meridians > 180] -= 360 map.drawmeridians(meridians, labels=[1, 0, 0, 1]) else: msg = "Projection %s not supported." % projection raise ValueError(msg) # draw coast lines, country boundaries, fill continents. map.drawcoastlines(color="0.4") map.drawcountries(color="0.75") if location == 'CA' or location == 'US': map.drawstates(color="0.75") # draw lat/lon grid lines map.drawparallels(np.arange(par_range[0], par_range[1], par_range[2]), labels=[1,0,0,0], linewidth=0) map.drawmeridians(np.arange(mer_range[0],mer_range[1], mer_range[2]), labels=[0,0,0,1], linewidth=0) if pretty: map.etopo() else: map.drawmapboundary(fill_color=water_fill_color) map.fillcontinents(color=continent_fill_color, lake_color=water_fill_color) # compute the native map projection coordinates for events. x, y = map(lons, lats) # plot labels if 100 > len(mags) > 1: for name, xpt, ypt, colorpt in zip(labels, x, y, colors): # Check if the point can actually be seen with the current map # projection. The map object will set the coordinates to very # large values if it cannot project a point. if xpt > 1e25: continue plt.text(xpt, ypt, name, weight="heavy", color=scal_map.to_rgba(colorpt)) elif len(mags) == 1: plt.text(x[0], y[0], labels[0], weight="heavy", color="red") min_size = 6 max_size = 30 min_mag = min(mags) max_mag = max(mags) if len(mags) > 1: frac = [(_i - min_mag) / (max_mag - min_mag) for _i in mags] magnitude_size = [(_i * (max_size - min_size)) ** 2 for _i in frac] #magnitude_size = [(_i * min_size) for _i in mags] #print magnitude_size colors_plot = [scal_map.to_rgba(c) for c in colors] else: magnitude_size = 15.0 ** 2 colors_plot = "red" map.scatter(x, y, marker='o', s=magnitude_size, c=colors_plot, zorder=10) if len(mags) > 1: plt.title( "{event_count} events ({start} to {end}) " "- Color codes {colorcode}, size the magnitude".format( event_count=len(lats), start=min(times).strftime("%Y-%m-%d"), end=max(times).strftime("%Y-%m-%d"), colorcode="origin time" if color == "date" else "depth")) else: plt.title("Event at %s" % times[0].strftime("%Y-%m-%d")) # Only show the colorbar for more than one event. if len(mags) > 1: cb = mpl.colorbar.ColorbarBase(ax=cm_ax, cmap=colormap, orientation='vertical') cb.set_ticks([0, 0.25, 0.5, 0.75, 1.0]) color_range = max_color - min_color if showHour: cb.set_ticklabels([ _i.strftime('%Y-%b-%d, %H:%M:%S %p') if color == "date" else '%.1fkm' % (_i) for _i in [min_color, min_color + color_range * 0.25, min_color + color_range * 0.50, min_color + color_range * 0.75, max_color]]) else: cb.set_ticklabels([_i.strftime('%Y-%b-%d') if color == "date" else '%.1fkm' % (_i) for _i in [min_color, min_color + color_range * 0.25, min_color + color_range * 0.50, min_color + color_range * 0.75, max_color]]) plt.show()
def plot_mt(earthquakes, mt, event_id, location = None, M_above = 5.0, show_above_M = True, llat = '-90', ulat = '90', llon = '-170', ulon = '190', figsize = (12,8), radius = 25, dist_bt = 600, mt_width = 2, angle_step = 20, show_eq = True, par_range = (-90., 120., 30.), mer_range = (0, 360, 60), pretty = False, legend_loc = 4, title = '', resolution = 'l'): ''' Function to plot moment tensors on the map Input: earthquakes - list of earthquake information mt - list of focal/moment_tensor information event_id - event ID corresponding to the earthquakes location - predefined region, choose from 'US' or 'CA', default is 'None' which will plot the whole world M_above - Only show the events with magnitude larger than this number default is 5.0, use with show_above_M show_above_M - Flag to turn on the M_above option, default is True, llat - bottom left corner latitude, default is -90 ulat - upper right corner latitude, default is 90 llon - bottom left corner longitude, default is -170 ulon - upper right corner longitude, default is 190 figsize - figure size, default is (12,8) radius - used in checking collisions (MT), put the MT on a circle with this radius, default is 25 dist_bt - used in checking collisions (MT), if two events within dist_bt km, then we say it is a collision, default is 600 angle_step - used in checking collisions (MT), this is to decide the angle step on the circle, default is 20 degree mt_width - size of the MT on the map. Different scale of the map may need different size, play with it. show_eq - flag to show the seismicity as well, default is True par_range - range of latitudes you want to label on the map, start lat, end lat and step size, default is (-90., 120., 30.), mer_range - range of longitudes you want to label on the map, start lon, end lon and step size, default is (0, 360, 60), pretty - draw a pretty map, default is False to make faster plot legend_loc - location of the legend, default is 4 title - title of the plot resolution - resolution of the map, Possible values are * ``"c"`` (crude) * ``"l"`` (low) * ``"i"`` (intermediate) * ``"h"`` (high) * ``"f"`` (full) Defaults to ``"l"`` ''' if location == 'US': llon=-125 llat=20 ulon=-70 ulat=60 M_above = 4.0 radius = 5 dist_bt = 200 par_range = (20, 60, 15) mer_range = (-120, -60, 15) mt_width = 0.8 drawCountries = True elif location == 'CAL': llat = '30' ulat = '45' llon = '-130' ulon = '-110' M_above = 3.0 radius = 1.5 dist_bt = 50 mt_width = 0.3 drawStates = True else: location = None print earthquakes,mt,event_id times = [event[6] for event in earthquakes] if show_above_M: mags = [row[3] for row in mt] index = np.array(mags) >= M_above mt_select = np.array(mt)[index] evid = np.array(event_id)[index] times_select = np.array(times)[index] else: evid = [row[0] for row in event_id] times_select = times mt_select = mt lats = [row[0] for row in mt_select] lons = [row[1] for row in mt_select] depths = [row[2] for row in mt_select] mags = [row[3] for row in mt_select] focmecs = [row[4:] for row in mt_select] lats_m, lons_m, indicator = check_collision(lats, lons, radius, dist_bt, angle_step) count = 0 colors=[] min_color = min(times_select) max_color = max(times_select) colormap = plt.get_cmap() for i in times_select: colors.append(i) scal_map = ScalarMappable(norm=cc.Normalize(min_color, max_color),cmap=colormap) scal_map.set_array(np.linspace(0, 1, 1)) colors_plot = [scal_map.to_rgba(c) for c in colors] ys = np.array(lats_m) xs = np.array(lons_m) url = ['http://earthquake.usgs.gov/earthquakes/eventpage/' + tmp + '#summary' for tmp in evid] stnm = np.array(evid) fig, ax1 = plt.subplots(1,1, figsize = figsize) #map_ax = fig.add_axes([0.03, 0.13, 0.94, 0.82]) if show_eq: cm_ax = fig.add_axes([0.98, 0.39, 0.04, 0.3]) plt.sca(ax1) cb = mpl.colorbar.ColorbarBase(ax=cm_ax, cmap=colormap, orientation='vertical') cb.set_ticks([0, 0.25, 0.5, 0.75, 1.0]) color_range = max_color - min_color cb.set_ticklabels([_i.strftime('%Y-%b-%d, %H:%M:%S %p') for _i in [min_color, min_color + color_range * 0.25, min_color + color_range * 0.50, min_color + color_range * 0.75, max_color]]) m = Basemap(projection='cyl', lon_0=142.36929, lat_0=38.3215, llcrnrlon=llon,llcrnrlat=llat,urcrnrlon=ulon,urcrnrlat=ulat,resolution=resolution) m.drawcoastlines() m.drawmapboundary() m.drawcountries() m.drawparallels(np.arange(par_range[0], par_range[1], par_range[2]), labels=[1,0,0,0], linewidth=0) m.drawmeridians(np.arange(mer_range[0],mer_range[1], mer_range[2]), labels=[0,0,0,1], linewidth=0) if pretty: m.etopo() else: m.fillcontinents() x, y = m(lons_m, lats_m) for i in range(len(focmecs)): index = np.where(focmecs[i] == 0)[0] #note here, if the mrr is zero, then you will have an error #so, change this to a very small number if focmecs[i][0] == 0: focmecs[i][0] = 0.001 width = mags[i] * mt_width if depths[i] <= 50: color = '#FFA500' #label_ elif depths[i] > 50 and depths [i] <= 100: color = '#FFFF00' elif depths[i] > 100 and depths [i] <= 150: color = '#00FF00' elif depths[i] > 150 and depths [i] <= 200: color = 'b' else: color = 'r' if indicator[i] == 1: m.plot([lons[i],lons_m[i]],[lats[i], lats_m[i]], 'k') #m.plot([10,20],[0,0]) try: b = Beach(focmecs[i], xy=(x[i], y[i]),width=width, linewidth=1, facecolor= color, alpha=1) count += 1 line, = ax1.plot(x[i],y[i], 'o', picker=5, markersize=30, alpha =0) except: pass b.set_zorder(3) ax1.add_collection(b) d=5 circ1 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="#FFA500") circ2 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="#FFFF00") circ3 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="#00FF00") circ4 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="b") circ5 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="r") M4 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize= 4*d, markerfacecolor="k") M5 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize= 5*d, markerfacecolor="k") M6 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize= 6*d, markerfacecolor="k") M7 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize= 7*d, markerfacecolor="k") if location == 'World': title = str(count) + ' events with focal mechanism - color codes depth, size the magnitude' elif location == 'US': title = 'US events with focal mechanism - color codes depth, size the magnitude' elif location == 'CAL': title = 'California events with focal mechanism - color codes depth, size the magnitude' elif location is None: pass legend1 = plt.legend((circ1, circ2, circ3, circ4, circ5), ("depth $\leq$ 50 km", "50 km $<$ depth $\leq$ 100 km", "100 km $<$ depth $\leq$ 150 km", "150 km $<$ depth $\leq$ 200 km","200 km $<$ depth"), numpoints=1, loc=legend_loc) plt.title(title) plt.gca().add_artist(legend1) if location == 'World': plt.legend((M4,M5,M6,M7), ("M 4.0", "M 5.0", "M 6.0", "M 7.0"), numpoints=1, loc=legend_loc) x, y = m(lons, lats) min_size = 6 max_size = 30 min_mag = min(mags) max_mag = max(mags) if show_eq: if len(lats) > 1: frac = [(_i - min_mag) / (max_mag - min_mag) for _i in mags] magnitude_size = [(_i * (max_size - min_size)) ** 2 for _i in frac] magnitude_size = [(_i * min_size/2)**2 for _i in mags] else: magnitude_size = 15.0 ** 2 colors_plot = "red" m.scatter(x, y, marker='o', s=magnitude_size, c=colors_plot, zorder=10) plt.show() print 'Max magnitude ' + str(np.max(mags)), 'Min magnitude ' + str(np.min(mags))
def plot_hist_mt(psmeca_dict, figsize = (16,24), mt_size = 10, pretty = False, resolution='l'): if psmeca_dict['psmeca'] != []: psmeca = psmeca_dict['psmeca'] #get the latitudes, longitudes, and the 6 independent component lats = psmeca[:,1] lons = psmeca[:,0] focmecs = psmeca[:,3:9] depths = psmeca[:,2] (llat, ulat, llon, ulon) = psmeca_dict['range'] evla = psmeca_dict['evloc'][0] evlo = psmeca_dict['evloc'][1] plt.figure(figsize=figsize) m = Basemap(projection='cyl', lon_0=142.36929, lat_0=38.3215, llcrnrlon=llon,llcrnrlat=llat,urcrnrlon=ulon,urcrnrlat=ulat,resolution=resolution) m.drawcoastlines() m.drawmapboundary() if pretty: m.etopo() else: m.fillcontinents() llat = float(llat) ulat = float(ulat) llon = float(llon) ulon = float(ulon) m.drawparallels(np.arange(llat, ulat, (ulat - llat) / 4.0), labels=[1,0,0,0]) m.drawmeridians(np.arange(llon, ulon, (ulon - llon) / 4.0), labels=[0,0,0,1]) ax = plt.gca() x, y = m(lons, lats) for i in range(len(focmecs)): ''' if x[i] < 0: x[i] = 360 + x[i] ''' if depths[i] <= 50: color = '#FFA500' #label_ elif depths[i] > 50 and depths [i] <= 100: color = 'g' elif depths[i] > 100 and depths [i] <= 200: color = 'b' else: color = 'r' index = np.where(focmecs[i] == 0)[0] #note here, if the mrr is zero, then you will have an error #so, change this to a very small number if focmecs[i][0] == 0: focmecs[i][0] = 0.001 try: b = Beach(focmecs[i], xy=(x[i], y[i]),width=mt_size, linewidth=1, facecolor=color) except: pass b.set_zorder(10) ax.add_collection(b) x_0, y_0 = m(evlo, evla) m.plot(x_0, y_0, 'r*', markersize=25) circ1 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="#FFA500") circ2 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="g") circ3 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="b") circ4 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="r") plt.legend((circ1, circ2, circ3, circ4), ("depth $\leq$ 50 km", "50 km $<$ depth $\leq$ 100 km", "100 km $<$ depth $\leq$ 200 km", "200 km $<$ depth"), numpoints=1, loc=3) plt.show() else: print 'No historical MT found!'
def mapAll(lat, lon, criteria, projection = 'robin', lat_0 = "", lon_0 = "",\ llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, \ countries = False, counties = False, rivers = False, states = False,\ figsize = [10,4], ax = None,\ background = 'none', scale = 0.5, palette="", markersize = 50): """ Map the location of all lat/lon according to some criteria Map the location of all lat/lon according to some criteria. The choice of plotting color/marker is passed through palette according to unique criteria (e.g., record name, archive type, proxy observation type). Args: lat (list): a list of latitude. lon (list): a list of longitude. criteria (list): a list of criteria for plotting purposes. For instance, a map by the types of archive present in the dataset or proxy observations. projection (string): the map projection. Refers to the Basemap documentation for a list of available projections. Only projections supporting setting the map center with a single lat/lon or with the coordinates of the rectangle are currently supported. Default is to use a Robinson projection. lat_0, lon_0 (float): the center coordinates for the map. Default is mean latitude/longitude in the list. If the chosen projection doesn't support it, Basemap will ignore the given values. llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon (float): The coordinates of the two opposite corners of the rectangle. countries (bool): Draws the countries border. Defaults is off (False). counties (bool): Draws the USA counties. Default is off (False). rivers (bool): Draws the rivers. Default is off (False). states (bool): Draws the American and Australian states borders. Default is off (False). background (string): Plots one of the following images on the map: bluemarble, etopo, shadedrelief, or none (filled continents). Default is none. scale (float): Useful to downgrade the original image resolution to speed up the process. Default is 0.5. palette (dict): A dictionary of plotting color/marker by criteria. The keys should correspond to ***unique*** criteria with a list of associated values. The list should be in the format ['color', 'marker']. markersize (int): The size of the marker. figsize (list): the size for the figure ax: Return as axis instead of figure (useful to integrate plot into a subplot) Returns: The figure """ #Check that the lists have the same length and convert to numpy arrays if len(lat)!=len(lon) or len(lat)!=len(criteria) or len(lon)!=len(criteria): sys.exit("Latitude, Longitude, and criteria list must be the same" +\ "length") # Grab the center latitude/longitude if not lat_0: lat_0 = np.mean(np.array(lat)) if not lon_0: lon_0 = np.mean(np.array(lon)) # If palette is not given, then make a random one. if not palette: marker_list = ['o','v','^','<','>','8','s','p','*','h','D'] color_list = ['#FFD600','#FF8B00','k','#86CDFA','#00BEFF','#4169E0',\ '#8A4513','r','#FF1492','#32CC32','#FFD600','#2F4F4F'] # select at random for unique entries in criteria marker = [random.choice(marker_list) for _ in range(len(set(criteria)))] color = [random.choice(color_list) for _ in range(len(set(criteria)))] crit_unique = [crit for crit in set(criteria)] #initialize the palette palette = {crit_unique[0]:[color[0],marker[0]]} for i in range(len(crit_unique)): d1 = {crit_unique[i]:[color[i],marker[i]]} palette.update(d1) #Make the figure if not ax: fig, ax = plt.subplots(figsize=figsize) map = Basemap(projection = projection, lat_0 = lat_0, lon_0 = lon_0,\ llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat,\ llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon) map.drawcoastlines() # Background if background == "shadedrelief": map.shadedrelief(scale = scale) elif background == "bluemarble": map.bluemarble(scale=scale) elif background == "etopo": map.etopo(scale=scale) elif background == "none": map.fillcontinents(color='0.9', lake_color = 'w') else: sys.exit("Enter either 'shadedrelief','bluemarble','etopo',or'None'") #Other extra information if countries == True: map.drawcountries() if counties == True: map.drawcounties() if rivers == True: map.drawrivers() if states == True: map.drawrivers() # Get the indexes by criteria for crit in set(criteria): # Grab the indices with same criteria index = [i for i,x in enumerate(criteria) if x == crit] X,Y =map(np.array(lon)[index],np.array(lat)[index]) map.scatter(X,Y, s= markersize, facecolor = palette[crit][0], marker = palette[crit][1], zorder = 10, label = crit) plt.legend(loc = 'center', bbox_to_anchor=(1.25,0.5),scatterpoints = 1, frameon = False, fontsize = 8, markerscale = 0.7) return ax
def draw(args): # draw Basemap lat_0 = (args.llcrnrlat+args.urcrnrlat)/2 lon_0 = (args.llcrnrlon+args.urcrnrlon)/2 m = Basemap( projection=projection, resolution = 'l', lat_0=lat_0, lon_0=lon_0, llcrnrlon=args.llcrnrlon, llcrnrlat=args.llcrnrlat, urcrnrlon=args.urcrnrlon, urcrnrlat=args.urcrnrlat, ) m.drawcoastlines() m.drawcountries() if args.mapbackground == 'bluemarble': m.bluemarble() elif args.mapbackground == 'fillcontinents': m.fillcontinents(color = args.fillcontinents_color) elif args.mapbackground == 'etopo': m.etopo() elif args.mapbackground == 'shadedrelief': m.shadedrelief() m.drawmapboundary() if args.drawmeridians: m.drawmeridians(np.arange(0, 360, 1), labels=[1, 1, 1, 1], fontsize='xx-small') if args.drawparallels: m.drawparallels(np.arange(-90, 90, 1), labels=[1, 1, 1, 1], fontsize='xx-small') l_colors_VGA16 = ( (1,0,0), # red (0,1,0), # green/lime (0,0,1), # blue (0,1,1), # cyan/aqua (1,0,1), # magenta/fuchsia (1,1,0), # yellow (1,.5,0), # orange (1,1,1), # white # '#800000', # maroon '#800080', # purple # '#008000', # dark green # '#808000', # olive '#000080', # navy '#008080', # teal (0,0,0), # black '#808080', # dark grey / silver? '#C0C0C0', # light grey / silver? # (.5,1,0), # green yellow (0,1,.5), # green cyan (0,.5,1), # blue cyan (.5,0,1), # blue magenta (1,0,.5), # red magenta (1,.5,.5), ## red? (.5,1,.5), ## green? (.5,.5,1), ## blue? ) l_colors_colorbrewer = [ (166,206,227), (31,120,180), (178,223,138), (51,160,44), (251,154,153), (227,26,28), (253,191,111), (255,127,0), (202,178,214), (106,61,154), (255,255,153), (177,89,40), ] for i, color in enumerate(l_colors_colorbrewer): l_colors_colorbrewer[i] = (l_colors_colorbrewer[i][0]/255,l_colors_colorbrewer[i][1]/255,l_colors_colorbrewer[i][2]/255) ## ## https://docs.python.org/3/library/colorsys.html ## l_colors = [(1,1,1),'#808080','#C0C0C0']+[Color(hue=h/360., saturation=1, luminance=.5).rgb for h in range(0,360,int(360/10))] l_colors = [(1,1,1),'#808080','#C0C0C0']+l_colors_colorbrewer l_colors = l_colors+l_colors # l_colors = l_colors_VGA16 # l_colors = ['#f1a340', '#998ec3'] # colorbrewer2.org, 3 data classes, diverging, scheme 4 # l_colors = ['#e41a1c', '#984ea3'] # colorbrewer2.org, 4 data classes, qualitative, scheme 6 # l_colors = ['#d01c8b', '#4dac26'] # colorbrewer2.org, 4 data classes, diverging, scheme 2 # l_colors = ['#e41a1c', '#4daf4a'] # l_colors = ['rgb(27,158,119)','rgb(217,95,2)','rgb(117,112,179)','rgb(231,41,138)','rgb(102,166,30)'] # 5 classes, qual, scheme 2 # l_colors = ['rgb(27,158,119)','rgb(217,95,2)','rgb(117,112,179)','rgb(231,41,138)','rgb(102,166,30)','rgb(230,171,2)'] # l_colors = ['rgb(27,158,119)','rgb(217,95,2)','rgb(117,112,179)','rgb(231,41,138)','rgb(102,166,30)','rgb(230,171,2)','rgb(166,118,29)'] # l_colors = ['rgb(228,26,28)','rgb(55,126,184)','rgb(77,175,74)','rgb(152,78,163)','rgb(255,127,0)','rgb(255,255,51)','rgb(166,86,40)'] # l_colors_blue = ['rgb(222,235,247)','rgb(158,202,225)','rgb(49,130,189)'] # 3, sequential, single hue 1 (blue) # l_colors_green = ['rgb(229,245,224)','rgb(161,217,155)','rgb(49,163,84)'] # 3, seq, single hue 2 (green) # l_colors_orange = ['rgb(254,230,206)','rgb(253,174,107)','rgb(230,85,13)'] # 3, seq, single hue 4 (orange) # l_colors_red = ['rgb(254,224,210)','rgb(252,146,114)','rgb(222,45,38)'] # 3, seq, single hue 6 (red) # l_colors = [l_colors_red[0], l_colors_red[2], l_colors_green[0], l_colors_green[2], l_colors_blue[0], l_colors_blue[2],] # l_colors = [l_colors_red[0], l_colors_red[2], l_colors_green[0], l_colors_green[2], l_colors_blue[2],] # l_colors = [tuple(int(i)/255 for i in color[4:-1].split(',')) for color in l_colors] # tmp!!! for colorbrewer2.org export # ## 4, qual, colorblind safe # l_colors = ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c'] ## 9, qual, printer friendly (4,5,6,7,8 are subsets) l_colors = [ '#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33', '#a65628', '#f781bf', '#999999', ] l_markerstyles = ['o','s','^','v','*','D','p'] # for i, color in enumerate(l_colors_colorbrewer): # l_colors_colorbrewer[i] = (l_colors_colorbrewer[i][0]/255,l_colors_colorbrewer[i][1]/255,l_colors_colorbrewer[i][2]/255) if args.colorlist: l_colors = ['#{}'.format(color) for color in args.colorlist] with open(args.input_file) as f: lines = f.readlines() d_colors = {} d_markerstyles = {} set_labels = set() for line in lines: ## skip blank lines if not line.strip(): continue ## skip comment lines if line[0] == '#': continue ## split line into list of column fields l = line.rstrip().split('\t') ## parse values from line lat = float(l[args.lat]) lon = float(l[args.lon]) label = l[args.labels] text = l[args.text] ## tmp!!! try: label = { # '1': 'REC approval, SEQUENCED', # '2': 'REC approval, SEQUENCING', '1': 'Sequenced/Sequencing', '2': 'Sequenced/Sequencing', # '3': 'REC approval, OTHERS', # '5': 'EXISTING STUDIES NOT YET APPROVED', '3': 'Other collections, Approved', '5': 'Other collections, Not yet approved', # '4': 'NEW COLLECTIONS', '4': 'Planned collections', 'MENTOR': 'MENTOR Initiative', # '6': '1000G phase 3', '6': 'Sequenced/Sequencing', }[label] except: pass ## markersize if args.markersize: if l[args.markersize] != 'NA': markersize = float(l[args.markersize]) else: markersize = 10 else: markersize = 10 if args.log: markersize = cnt2markersize(markersize) ## markerstyle if args.markerstyle: try: markerstyle = d_markerstyles[l[args.markerstyle]] except KeyError: markerstyle = l_markerstyles[len(list(d_markerstyles.keys()))] d_markerstyles[l[args.markerstyle]] = markerstyle else: markerstyle = 'o' ## color if args.colors: color = l[args.colors] elif args.markerfacecolor: color = args.markerfacecolor else: try: color = d_colors[label] except KeyError: color = l_colors[len(list(d_colors.keys()))] d_colors[label] = color ## convert lon and lat to x and y x, y = m(lon, lat) if args.offsetx and args.offsety: offset_extra = (float(l[args.offsetx]), float(l[args.offsety])) else: offset_extra = (0, 0) ## get text position x_text, y_text = m(lon+offset_extra[0], lat+args.offset+offset_extra[1]) if args.no_text_labels == False: text = plt.text( x_text, y_text, text.replace('\\n','\n'), horizontalalignment='center', size=args.text_size, color=color) text.set_path_effects([ path_effects.Stroke(linewidth=2, foreground='black'), path_effects.Normal()]) ## plot data point m.plot( x, y, markerstyle, markersize=markersize, markerfacecolor=color, label="") ## plot outside map to have label appear (not very elegant solution...) x, y = m(-60, -60) if not label in set_labels: set_labels.add(label) m.plot(x, y, 'o', markersize=10, markerfacecolor=color, label=label) if args.markersize: # for i in range(1,3): for i in range(0,3): # make this log dependent and input range dependent... m.plot( x, y, 'o', markersize=cnt2markersize(pow(10, i)), markerfacecolor='white', label=pow(10, i)) if args.markerstyle: for label, markerstyle in sorted(d_markerstyles.items()): m.plot( x, y, markerstyle, markersize=cnt2markersize(10), markerfacecolor='white', label='Sequencing depth of coverage '+label) distance_from_plot = 0.05 print('ncol', args.ncol) plt.legend( ncol=args.ncol, shadow=True, ## prop={'size':8.5}, prop={'size':6.5}, numpoints=1, labelspacing=1.0, loc=args.loc, fancybox=True, ## handleheight=2.5, borderpad=0.7, framealpha=0.5, ) if args.out: out = '{}.jpg'.format(args.out) else: out = '{}_{}_{}.jpg'.format( os.path.splitext(os.path.basename(args.input_file))[0], projection, args.mapbackground) plt.savefig(out, dpi=args.dpi) plt.title('{} {} {}'.format( getpass.getuser(), '.'.join(platform.node().split('.')[1:]), time.strftime('%a %Y%b%d', time.gmtime()))) plt.close() return
def geramapa(delt): deltatime = delt*u.s datas1 = datas[idx] + TimeDelta(deltatime) datas1.delta_ut1_utc = 0 lon = stars[idx].ra - datas1.sidereal_time('mean', 'greenwich') m = Basemap(projection='ortho',lat_0=stars[idx].dec.value,lon_0=lon.value,resolution=resolution) # m = Basemap(projection='ortho',lat_0=stars[idx].dec.value,lon_0=lon.value,resolution=resolution, llcrnrx=-7000000,llcrnry=-7000000,urcrnrx=7000000,urcrnry=7000000) m.drawcoastlines(linewidth=0.5) m.drawcountries(linewidth=0.5) m.drawstates(linewidth=0.5) m.drawmeridians(np.arange(0,360,30)) m.drawparallels(np.arange(-90,90,30)) m.drawmapboundary() ptcolor = 'black' lncolor = 'black' dscolor = 'black' if mapstyle == '2': m.drawmapboundary(fill_color='aqua') m.fillcontinents(color='coral',lake_color='aqua') ptcolor = 'red' lncolor = 'blue' dscolor = 'red' elif mapstyle == '3': m.shadedrelief() ptcolor = 'red' lncolor = 'blue' dscolor = 'red' elif mapstyle == '4': m.bluemarble() ptcolor = 'red' lncolor = 'red' dscolor = 'red' elif mapstyle == '5': m.etopo() ptcolor = 'red' lncolor = 'red' dscolor = 'red' if os.path.isfile(sitearq) == True: xpt,ypt = m(sites['lon'],sites['lat']) m.plot(xpt,ypt,'bo') CS=m.nightshade(datas1.datetime, alpha=0.2) a, b =m(lon.value, stars[idx].dec.value) a = a*u.m b = b*u.m dista = (dist[idx].to(u.km)*ca[idx].to(u.rad)).value*u.km disterr = (dist[idx].to(u.km)*erro.to(u.rad)).value*u.km ax = a + dista*np.sin(pa[idx]) + (deltatime*vel[idx])*np.cos(pa[idx]) by = b + dista*np.cos(pa[idx]) - (deltatime*vel[idx])*np.sin(pa[idx]) m.plot(ax,by, 'o', color=ptcolor, markersize=mapsize[0].value*20/46) # plt.legend(fontsize=mapsize[0].value*21/46) fig = plt.gcf() fig.set_size_inches(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value) plt.title('-{} D={}- dots each 60 s <> offsets (mas): obj=({:.1f},{:.1f}), star=({:.1f},{:.1f})\n' .format(obj, tamanho, ob_off_ra[idx].value, ob_off_de[idx].value, st_off_ra[idx].value, st_off_de[idx].value), fontsize=mapsize[0].value*25/46, fontproperties='FreeMono', weight='bold') plt.xlabel('\n year-m-d h:m:s UT ra__dec__J2000__candidate C/A P/A vel Delta R* K* long\n\ {} {:02d} {:02d} {:07.4f} {:+02d} {:02d} {:06.3f} {:6.3f} {:6.2f} {:6.2f} {:5.2f} {:5.1f} {:4.1f} {:3.0f}' .format(datas1.iso, int(stars[idx].ra.hms.h), int(stars[idx].ra.hms.m), stars[idx].ra.hms.s, int(stars[idx].dec.dms.d), np.absolute(int(stars[idx].dec.dms.m)), np.absolute(stars[idx].dec.dms.s), ca[idx].value, pa[idx].value, vel[idx].value, dist[idx].value, magR[idx], magK[idx], longi[idx]), fontsize=mapsize[0].value*21/46, fontproperties='FreeMono', weight='bold') plt.savefig('{}_{:05d}.png'.format(obj, np.where(g==delt)[0][0] + 1),dpi=100) print 'Gerado: {}_{:05d}.png'.format(obj, np.where(g==delt)[0][0] + 1) plt.clf()
def makemap(edilist,mapstretchfactor,symbolsize,labelsize,showlabel): #import of modules here due to warnings from Matplotlib packages #these warnings distract the 'usage' information from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import matplotlib as mpl import mtpy.utils.filehandling as MTfh import mtpy.core.edi as EDI import mtpy.utils.filehandling as MTfh lats = [] lons =[] names=[] for i in edilist: e = EDI.Edi() e.readfile(i) lats.append(e.lat) lons.append(e.lon) names.append(e.head['dataid'].lower()) coords = zeros((len(edilist),2)) coords[:,0] = lats coords[:,1] = lons latrange = max(lats) - min(lats) lonrange = max(lons) - min(lons) #center point for projection: c = [mean(lats),mean(lons)] #----------------------- #Matplotlib options mpl.rcParams['font.size'] = 10. mpl.rcParams['axes.labelsize'] = 8. mpl.rcParams['xtick.labelsize'] = 6. mpl.rcParams['ytick.labelsize'] = 6. plt.close('all') fig = plt.figure()#figsize=(5.7,4.3)) plt.subplots_adjust(left=0.2,right=0.9,top=0.90,bottom=0.1,wspace=0.15,hspace=0.05) ax = plt.subplot(111) stretch = float(mapstretchfactor) total_latmin = min(lats)-stretch*latrange total_lonmin = min(lons)-stretch*lonrange total_latmax = max(lats)+stretch*latrange total_lonmax = max(lons)+stretch*lonrange total_latrange = total_latmax - total_latmin total_lonrange = total_lonmax - total_lonmin #determine number of axes labels: maximumlabels = 5 latnum=maximumlabels lonnum=maximumlabels lonlat_stretch = total_lonrange/total_latrange if int(lonlat_stretch) > 2: #significantly more long than lat factor = int(int(lonlat_stretch)/2.) latnum = int(maximumlabels/factor) + 1 lonnum = maximumlabels elif int(lonlat_stretch) <0.5 : #significantly more long than lat factor = int(int(1./lonlat_stretch)/2.) lonnum = int(maximumlabels/factor) + 1 latnum = maximumlabels m = Basemap( projection='merc', lon_0=c[1],lat_0=c[0],lat_ts=c[0], llcrnrlat=total_latmin, urcrnrlat=total_latmax, llcrnrlon=total_lonmin, urcrnrlon=total_lonmax, rsphere=6371200.,resolution='h',ax=ax) lons.append(total_lonmin) lons.append(total_lonmax) lats.append(total_latmin) lats.append(total_latmax) xgrid, ygrid = m(*meshgrid(lons,lats)) xdiff = xgrid.max()-xgrid.min() ydiff = ygrid.max()-ygrid.min() largest_extent = max(ydiff,xdiff) m.drawcoastlines(linewidth=0.25,ax=ax) m.drawcountries(linewidth=0.25,ax=ax) m.fillcontinents(color='coral',lake_color='aqua',ax=ax) m.drawmapboundary(fill_color='aqua',ax=ax) m.drawparallels( [round(i,3) for i in linspace(total_latmin,total_latmax,latnum+1,False)][1:], labels=[1,0,0,0], fmt='%.1f' ) m.drawmeridians( [round(i,3) for i in linspace(total_lonmin,total_lonmax,lonnum+1,False)][1:], labels=[0,0,0,1], fmt='%.1f' ) m.drawrivers() m.etopo() m.drawmapscale( total_lonmax-0.15*total_lonrange, total_latmax-0.2*total_latrange, c[1],c[0], 2*10**(int(log10(largest_extent/1000.))-1), barstyle='simple', labelstyle='simple',fontsize=12, fontcolor='k', fillcolor1='r', fillcolor2='g', ax=None, format='%d', ) for x,y,name in zip(xgrid[0,:], ygrid[:,0],names): plt.plot(x,y,'v',ms=symbolsize,color='k',label=name) if showlabel is True: plt.text(x,y,name,fontsize=labelsize,ha='center',va='bottom',color='k',backgroundcolor='r')#, labelfontsize=5) plt.title('locations of {0} MT stations'.format(len(names))) f1 = 'station_locations_map.png' f2 = 'station_locations_map.svg' f1 = MTfh.make_unique_filename(f1) f2 = MTfh.make_unique_filename(f2) plt.savefig(f1,format='png',dpi=200) plt.savefig(f2,format='svg',transparent=True) return op.abspath(f1),op.abspath(f2)
bmap.shadedrelief() # as above, but use etopo image as map background. fig = plt.figure() bmap.drawmapboundary() bmap.drawmeridians(np.arange(0,360,30)) bmap.drawparallels(np.arange(-90,90,30)) # plot filled circles at the locations of the cities. bmap.plot(xc,yc,'wo') # plot the names of five cities. for name,xpt,ypt in zip(cities,xc,yc): plt.text(xpt+50000,ypt+50000,name,fontsize=9,color='w') # contour data over the map. cs = bmap.contour(x,y,wave+mean,15,linewidths=1.5) plt.title('etopo background') bmap.etopo() # as above, but use etopo image as map background overlaid with # land-sea mask image where land areas are transparent (so etopo # image shows through over land). fig = plt.figure() bmap.drawmapboundary() bmap.drawmeridians(np.arange(0,360,30)) bmap.drawparallels(np.arange(-90,90,30)) # plot filled circles at the locations of the cities. bmap.plot(xc,yc,'wo') # plot the names of five cities. for name,xpt,ypt in zip(cities,xc,yc): plt.text(xpt+50000,ypt+50000,name,fontsize=9,color='w') # contour data over the map. cs = bmap.contour(x,y,wave+mean,15,linewidths=1.5)
def particleplotting(filename, psize, recordedvar, rcmap, backgroundfield, dimensions, cmap, drawland, limits, display, start=1, mode='movie2d', plot_mfregion=False, mfregion_start=1, mf_focus=0, output='particle_plot'): """Quick and simple plotting of PARCELS trajectories""" pfile = Dataset(filename, 'r') lon = pfile.variables['lon'] lat = pfile.variables['lat'] #time = pfile.variables['time'] #z = pfile.variables['z'] active = pfile.variables['active'] if display is not 'none': title = pfile.variables[display] if plot_mfregion: mf_cols = [] colmap = {1: 'red', 2: 'blue', 3: 'orange', 4: 'green', 5: 'purple', 6: 'grey'} if mf_focus == 0: for p in range(lon.shape[0]): mf_cols.append(colmap[getMFRegion(lon[p,mfregion_start], lat[p,mfregion_start])]) else: for p in range(lon.shape[0]): r = getMFRegion(lon[p,mfregion_start], lat[p,mfregion_start]) mf_cols.append(colmap[r] if r is mf_focus else 'lightgrey') if limits is -1: limits = [np.min(lon), np.max(lon), np.min(lat), np.max(lat)] if recordedvar is not 'none': print('Particles coloured by: %s' % recordedvar) rMin = np.min(pfile.variables[recordedvar]) rMax = np.max(pfile.variables[recordedvar]) print('Min = %f, Max = %f' % (rMin, rMax)) record = (pfile.variables[recordedvar]-rMin)/(rMax-rMin) if backgroundfield is not 'none': bfile = Dataset(backgroundfield.values()[0], 'r') bX = bfile.variables[dimensions[0]] bY = bfile.variables[dimensions[1]] bT = bfile.variables[dimensions[2]] # Find the variable that exists across at least two spatial and one time dimension if backgroundfield.keys()[0] is 'none': def checkShape(var): print(np.shape(var)) if len(np.shape(var)) > 2: return True for v in bfile.variables: if checkShape(bfile.variables[v]): bVar = bfile.variables[v] print('Background variable is %s' % v) break else: bVar = bfile.variables[backgroundfield.keys()[0]] if mode == '3d': fig = plt.figure(1) ax = fig.gca(projection='3d') for p in range(len(lon)): ax.plot(lon[p, :], lat[p, :], z[p, :], '.-') ax.set_xlabel('Longitude') ax.set_ylabel('Latitude') ax.set_zlabel('Depth') plt.show() elif mode == '2d': fig, ax = plt.subplots(1, 1) #subsample indices = np.rint(np.linspace(0, len(lon)-1, 100)).astype(int) #indices = range(len(lon[:,0])) if backgroundfield is not 'none': time=18 plt.contourf(bX[:], bY[:], bVar[time, 0, :, :], zorder=-1, vmin=0, vmax=np.max(bVar[time, 0, :, :]), levels=np.linspace(0, np.max(bVar[time, 0, :, :]), 100), xlim=[limits[0], limits[1]], ylim=[limits[2], limits[3]], cmap=cmap) #plt.plot(np.transpose(lon[indices,:]), np.transpose(lat[indices,:]), '.-', linewidth=psize, # markersize=psize, c='blue') plt.quiver(np.transpose(lon[indices,:-1]), np.transpose(lat[indices,:-1]), np.transpose(lon[indices,1:])-np.transpose(lon[indices,:-1]), np.transpose(lat[indices,1:])-np.transpose(indices,lat[:-1]), scale_units='xy', angles='xy', scale=1) plt.xlim([limits[0], limits[1]]) plt.ylim([limits[2], limits[3]]) else: lines = ax.plot(np.transpose(lon[indices,:]), np.transpose(lat[indices,:]), 'k-', linewidth=psize, markersize=psize, c='white') plt.xlim([limits[0], limits[1]]) plt.ylim([limits[2], limits[3]]) add_arrow_to_line2D(ax, lines, arrow_locs=np.linspace(0., 1., 200), arrowstyle='->') plt.xlabel('Longitude') plt.ylabel('Latitude') if drawland: m = Basemap(width=12000000, height=9000000, projection='cyl', resolution='f', llcrnrlon=limits[0], llcrnrlat=limits[2], urcrnrlon=limits[1], urcrnrlat=limits[3], epsg=4714, area_thresh = 0.1) m.drawcoastlines() m.etopo() #m.arcgisimage(service='ESRI_Imagery_World_2D', xpixels = 2000, verbose= True) m.fillcontinents(color='forestgreen', lake_color='aqua') plt.show() elif mode == 'movie2d': fig = plt.figure(1) ax = plt.axes(xlim=[limits[0], limits[1]], ylim=[limits[2], limits[3]]) ax.set_xlim(limits[0], limits[1]) ax.set_ylim(limits[2], limits[3]) indices = np.rint(np.linspace(0, len(lon)-1, 100)).astype(int) scat = ax.scatter(lon[indices, 0], lat[indices, 0], s=psize, c='black') # Offline calc contours still to do def animate(i): ax.cla() active_list = np.where(active[:, i] == 1)[0] if len(active_list) < 1: active_list = 0 #active_list = range(len(lon[:,i]))#indices # if len(np.where(active_list)) > 1: if drawland: m.drawcoastlines() m.fillcontinents(color='forestgreen', lake_color='aqua') if recordedvar is not 'none': scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, c=record[active_list, i], cmap=rcmap, vmin=0, vmax=1) elif plot_mfregion: scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, color=mf_cols, cmap='summer', vmin=0, vmax=1) else: scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, c='blue', edgecolors='black') ax.set_xlim([limits[0], limits[1]]) ax.set_ylim([limits[2], limits[3]]) if backgroundfield is not 'none': field_time = np.argmax(bT > time[0, i]) - 1 plt.contourf(bY[:], bX[:], bVar[field_time, :, :], vmin=0, vmax=np.max(bVar[field_time, :, :]), levels=np.linspace(0, np.max(bVar[field_time, :, :]), 100), xlim=[limits[0], limits[1]], zorder=-1,ylim=[limits[2], limits[3]], cmap=cmap) plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) if display is not 'none': if display == 'time': plt.suptitle(datetime.fromtimestamp(title[0,i])) else: plt.suptitle("Cohort age %s months" % display)#"Cohort age = %s months" % title[0,i]) plt.title("Region %s" % mf_focus) return scat, if drawland: m = Basemap(width=12000000, height=9000000, projection='cyl', resolution='c', llcrnrlon=np.round(np.amin(lon)), llcrnrlat=np.amin(lat), urcrnrlon=np.amax(lon), urcrnrlat=np.amax(lat), area_thresh = 10) anim = animation.FuncAnimation(fig, animate, frames=np.arange(start, lon.shape[1]), interval=1, blit=False) plt.show() elif mode == 'to_file': fig = plt.figure(1, figsize=(16, 8), dpi=100) ax = plt.axes(xlim=[limits[0], limits[1]], ylim=[limits[2], limits[3]]) ax.set_xlim(limits[0], limits[1]) ax.set_ylim(limits[2], limits[3]) indices = np.rint(np.linspace(0, len(lon)-1, 100)).astype(int) scat = ax.scatter(lon[indices, 0], lat[indices, 0], s=psize, c='black') if drawland: m = Basemap(width=12000000, height=9000000, projection='cyl', resolution='c', llcrnrlon=np.round(np.amin(lon)), llcrnrlat=np.amin(lat), urcrnrlon=np.amax(lon), urcrnrlat=np.amax(lat), area_thresh = 10) for i in np.arange(start, lon.shape[1]): ax.cla() #active_list = active[:, i] > 0 active_list = range(len(lon[:,i]))#indices if drawland: m.drawcoastlines() m.fillcontinents(color='forestgreen', lake_color='aqua') if recordedvar is not 'none': scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, c=record[active_list, i], cmap=rcmap, vmin=0, vmax=1) elif plot_mfregion: scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, color=mf_cols, cmap='summer', vmin=0, vmax=1) else: scat = ax.scatter(lon[active_list, i], lat[active_list, i], s=psize, c='blue', edgecolors='black') ax.set_xlim([limits[0], limits[1]]) ax.set_ylim([limits[2], limits[3]]) if backgroundfield is not 'none': field_time = np.argmax(bT > time[0, i]) - 1 plt.contourf(bY[:], bX[:], bVar[field_time, :, :], vmin=0, vmax=np.max(bVar[field_time, :, :]), levels=np.linspace(0, np.max(bVar[field_time, :, :]), 100), xlim=[limits[0], limits[1]], zorder=-1,ylim=[limits[2], limits[3]], cmap=cmap) plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) if display is not 'none': plt.suptitle("Region %s\nCohort age %s months" % (mf_focus if mf_focus != 0 else 'All', title[0,i])) plt.savefig('Plots/%s%s.png' % (output, i))
def geramapa(star, data, title, labelx, nameimg, mapstyle='1', resolution='l', centermap=None, lats=None, erro=None, ring=None, atm=None, clat=None, sitearq=None, fmt='png', dpi=100, mapsize=None, cpoints=60, off=0): lon = star.ra - data.sidereal_time('mean', 'greenwich') center_map = EarthLocation(lon.value, star.dec.value) if not centermap == None: center_map = EarthLocation(centermap[0],centermap[1]) m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution) # m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution,llcrnrx=-2000000.,llcrnry=-1500000.,urcrnrx=2000000.,urcrnry=1500000.) # kx = fig.add_axes([-0.003,-0.001,1.006,1.002]) # kx.set_rasterization_zorder(1) m.nightshade(data.datetime, alpha=0.3, zorder=0.5) ## desenha a sombra da noite m.drawcoastlines(linewidth=0.5) ## desenha as linhas da costa m.drawcountries(linewidth=0.5) ## desenha os paises m.drawstates(linewidth=0.5) ## Desenha os estados m.drawmeridians(np.arange(0,360,30)) ## desenha os meridianos m.drawparallels(np.arange(-90,90,30)) ## desenha os paralelos m.drawmapboundary() ## desenha o contorno do mapa style = {'1': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'blue', 'rncolor':'blue', 'atcolor':'blue', 'outcolor':'red'}, '2': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'}, '3': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'}, '4': {'ptcolor': 'red', 'lncolor': 'red', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'}, '5': {'ptcolor': 'red', 'lncolor': 'red', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'}} if mapstyle == '2': m.drawmapboundary(fill_color='aqua') m.fillcontinents(color='coral',lake_color='aqua') elif mapstyle == '3': m.shadedrelief() elif mapstyle == '4': m.bluemarble() elif mapstyle == '5': m.etopo() if not lats == None: xs, ys = m(lats[0], lats[1]) xs = [i for i in xs if i < 1e+30] ys = [i for i in ys if i < 1e+30] m.plot(xs, ys, color=style[mapstyle]['lncolor']) xt, yt = m(lats[2], lats[3]) xt = [i for i in xt if i < 1e+30] yt = [i for i in yt if i < 1e+30] m.plot(xt, yt, color=style[mapstyle]['lncolor']) m.plot(lats[4], lats[5], color=style[mapstyle]['outcolor'], clip_on=False, zorder=-0.2) m.plot(lats[6], lats[7], color=style[mapstyle]['outcolor'], clip_on=False, zorder=-0.2) # else: # m.plot(lats[4], lats[5], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2) # m.plot(lats[6], lats[7], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2) if not erro == None: xs, ys = m(erro[0], erro[1]) xs = [i for i in xs if i < 1e+30] ys = [i for i in ys if i < 1e+30] m.plot(xs, ys, '--', color=style[mapstyle]['ercolor']) xt, yt = m(erro[2], erro[3]) xt = [i for i in xt if i < 1e+30] yt = [i for i in yt if i < 1e+30] m.plot(xt, yt, '--', color=style[mapstyle]['ercolor']) if not ring == None: xs, ys = m(ring[0], ring[1]) xs = [i for i in xs if i < 1e+30] ys = [i for i in ys if i < 1e+30] m.plot(xs, ys, '--', color=style[mapstyle]['rncolor']) xt, yt = m(ring[2], ring[3]) xt = [i for i in xt if i < 1e+30] yt = [i for i in yt if i < 1e+30] m.plot(xt, yt, '--', color=style[mapstyle]['rncolor']) if not atm == None: xs, ys = m(atm[0], atm[1]) xs = [i for i in xs if i < 1e+30] ys = [i for i in ys if i < 1e+30] m.plot(xs, ys, color=style[mapstyle]['atcolor']) xt, yt = m(atm[2], atm[3]) xt = [i for i in xt if i < 1e+30] yt = [i for i in yt if i < 1e+30] m.plot(xt, yt, color=style[mapstyle]['atcolor']) if not clat == None: xc, yc, lab = [], [], [] cp = Time(clat[5], format='iso') vec = np.arange(0, (cp[-1] - data).sec, cpoints) vec = np.sort(np.concatenate((vec,-vec[1:]), axis=0))*u.s for i in vec: g = data + TimeDelta(i) + TimeDelta(off*u.s) if g.iso in clat[2]: a = np.where(np.array(clat[2]) == g.iso) x, y = m(np.array(clat[0])[a], np.array(clat[1])[a]) xc.append(x) yc.append(y) lab.append(g.iso.split()[1][0:8]) elif g.iso in clat[5]: a = np.where(np.array(clat[5]) == g.iso) xc.append(np.array(clat[3])[a]) yc.append(np.array(clat[4])[a]) lab.append(g.iso.split()[1][0:8]) else: if len(clat[2]) == 0: a = [0] else: co = Time(clat[2], format='iso') a = np.argsort(np.absolute(co - g))[0:2] if 0 not in a and len(co)-1 not in a: b = np.absolute((co[a] - g).sec) x, y = m(np.array(clat[0])[a], np.array(clat[1])[a]) xc.append(np.sum(x*(1/b))/np.sum(1/b)) yc.append(np.sum(y*(1/b))/np.sum(1/b)) lab.append(g.iso.split()[1][0:8]) else: co = Time(clat[5], format='iso') a = np.argsort(np.absolute(co - g))[0:2] b = np.absolute((co[a] - g).sec) xc.append(np.sum(np.array(clat[3])[a]*(1/b))/np.sum(1/b)) yc.append(np.sum(np.array(clat[4])[a]*(1/b))/np.sum(1/b)) lab.append(g.iso.split()[1][0:8]) m.plot(xc, yc, 'o', color=style[mapstyle]['ptcolor'], clip_on=False, markersize=mapsize[0].value*8/46) m.plot(clat[6][0], clat[6][1], 'o', color=style[mapstyle]['ptcolor'], clip_on=False, markersize=mapsize[0].value*20/46) # for label, axpt, bypt in zip(lab, xc, yc): # plt.text(axpt + 0, bypt + 350000, label, rotation=60, weight='bold') # m.plot(ax,by, 'o', color=ptcolor, markersize=int(mapsize[0].value*20/46)) # m.plot(ax2.to(u.m),by2.to(u.m), 'o', color=ptcolor, markersize=int(mapsize[0].value*12/46)) # m.plot(ax3.to(u.m), by3.to(u.m), color='red') # m.plot(ax4.to(u.m), by4.to(u.m), color='red') # m.quiver(a-0*u.m,b-600000*u.m, 20, 0, width=0.005) # ax2 = a + dista*np.sin(pa) + [(i - datas).sec for i in temposplot]*u.s*vel*np.cos(paplus) # by2 = b + dista*np.cos(pa) - [(i - datas).sec for i in temposplot]*u.s*vel*np.sin(paplus) # # labels = [i.iso.split()[1][0:8] for i in temposplot] # m.plot(ax2, by2, 'ro') # if os.path.isfile(sitearq) == True: # xpt,ypt = m(sites['lon'],sites['lat']) # m.plot(xpt,ypt,'bo') # offset = [[xpt[0] + 100000,xpt[0] + 100000,xpt[0] + 100000,xpt[3] + 400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000],[10000,-30000,-60000,70000,30000,-20000,-70000,-30000,-70000]] # for i in np.arange(len(xpt)): # ax.text(offset[0][i],ypt[i]+offset[1][i],sites['nome'][i], weight='bold') # m.plot(ax5.to(u.m), by5.to(u.m), '--', color=dscolor, label='+-{} error'.format(erro)) # m.plot(ax6.to(u.m), by6.to(u.m), '--', color=dscolor) # plt.legend(fontsize=mapsize[0].value*21/46) fig = plt.gcf() fig.set_size_inches(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value) plt.title(title, fontsize=mapsize[0].value*25/46, fontproperties='FreeMono', weight='bold') plt.xlabel(labelx, fontsize=mapsize[0].value*21/46, fontproperties='FreeMono', weight='bold') plt.savefig('{}.{}'.format(nameimg, fmt), format=fmt, dpi=dpi) print 'Gerado: {}.{}'.format(nameimg, fmt) plt.clf()
def geramapa(idx): lons1, lats1, lons2, lats2 = calcfaixa(idx) lon = stars[idx].ra - datas[idx].sidereal_time('mean', 'greenwich') m = Basemap(projection='ortho',lat_0=stars[idx].dec.value,lon_0=lon.value,resolution=resolution) # m = Basemap(projection='ortho',lat_0=stars[idx].dec.value,lon_0=lon.value,resolution=resolution, llcrnrx=-7000000,llcrnry=-7000000,urcrnrx=7000000,urcrnry=7000000) m.drawcoastlines(linewidth=0.5) m.drawcountries(linewidth=0.5) m.drawstates(linewidth=0.5) m.drawmeridians(np.arange(0,360,30)) m.drawparallels(np.arange(-90,90,30)) m.drawmapboundary() ptcolor = 'black' lncolor = 'black' dscolor = 'black' if mapstyle == '2': m.drawmapboundary(fill_color='aqua') m.fillcontinents(color='coral',lake_color='aqua') ptcolor = 'red' lncolor = 'blue' dscolor = 'red' elif mapstyle == '3': m.shadedrelief() ptcolor = 'red' lncolor = 'blue' dscolor = 'red' elif mapstyle == '4': m.bluemarble() ptcolor = 'red' lncolor = 'red' dscolor = 'red' elif mapstyle == '5': m.etopo() ptcolor = 'red' lncolor = 'red' dscolor = 'red' if os.path.isfile(sitearq) == True: xpt,ypt = m(sites['lon'],sites['lat']) m.plot(xpt,ypt,'bo') CS=m.nightshade(datas[idx].datetime, alpha=0.2) a, b =m(lon.value, stars[idx].dec.value) a = a*u.m b = b*u.m dista = (dist[idx].to(u.km)*ca[idx].to(u.rad)).value*u.km disterr = (dist[idx].to(u.km)*erro.to(u.rad)).value*u.km vec = np.arange(0,7000,(np.absolute(vel[idx])*(60*u.s)).value)*u.km + np.absolute(vel[idx])*(60*u.s) vec = np.concatenate((vec.value,-vec.value), axis=0)*u.km ax = a + dista*np.sin(pa[idx]) ax2 = ax + vec*np.cos(pa[idx]) ax3 = ax2 - tamanho/2*np.sin(pa[idx]) ax4 = ax2 + tamanho/2*np.sin(pa[idx]) ax5 = a + (dista-disterr)*np.sin(pa[idx]) + vec*np.cos(pa[idx]) ax6 = a + (dista+disterr)*np.sin(pa[idx]) + vec*np.cos(pa[idx]) by = b + dista*np.cos(pa[idx]) by2 = by - vec*np.sin(pa[idx]) by3 = by2 - tamanho/2*np.cos(pa[idx]) by4 = by2 + tamanho/2*np.cos(pa[idx]) by5 = b + (dista-disterr)*np.cos(pa[idx]) - vec*np.sin(pa[idx]) by6 = b + (dista+disterr)*np.cos(pa[idx]) - vec*np.sin(pa[idx]) xs, ys = m(lons1, lats1) xs = [i for i in xs if i < 1e+30] ys = [i for i in ys if i < 1e+30] m.plot(xs, ys, 'b') xt, yt = m(lons2, lats2) xt = [i for i in xt if i < 1e+30] yt = [i for i in yt if i < 1e+30] m.plot(xt, yt, 'b') # m.plot(ax,by, 'o', color=ptcolor, markersize=mapsize[0].value*20/46) # m.plot(ax2.to(u.m),by2.to(u.m), 'o', color=ptcolor, markersize=mapsize[0].value*8/46) # m.plot(ax3.to(u.m), by3.to(u.m), color=lncolor) # m.plot(ax4.to(u.m), by4.to(u.m), color=lncolor) # m.plot(ax5.to(u.m), by5.to(u.m), '--', color=dscolor, label='+-{} error'.format(erro)) # m.plot(ax6.to(u.m), by6.to(u.m), '--', color=dscolor) # plt.legend(fontsize=mapsize[0].value*21/46) fig = plt.gcf() fig.set_size_inches(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value) plt.title('-{} D={}- dots each 60 s <> offsets (mas): obj=({:.1f},{:.1f}), star=({:.1f},{:.1f})\n' .format(obj, tamanho, ob_off_ra[idx].value, ob_off_de[idx].value, st_off_ra[idx].value, st_off_de[idx].value), fontsize=mapsize[0].value*25/46, fontproperties='FreeMono', weight='bold') plt.xlabel('\n year-m-d h:m:s UT ra__dec__J2000__candidate C/A P/A vel Delta R* K* long\n\ {} {:02d} {:02d} {:07.4f} {:+02d} {:02d} {:06.3f} {:6.3f} {:6.2f} {:6.2f} {:5.2f} {:5.1f} {:4.1f} {:3.0f}' .format(datas[idx].iso, int(stars[idx].ra.hms.h), int(stars[idx].ra.hms.m), stars[idx].ra.hms.s, int(stars[idx].dec.dms.d), np.absolute(int(stars[idx].dec.dms.m)), np.absolute(stars[idx].dec.dms.s), ca[idx].value, pa[idx].value, vel[idx].value, dist[idx].value, magR[idx], magK[idx], longi[idx]), fontsize=mapsize[0].value*21/46, fontproperties='FreeMono', weight='bold') plt.savefig('{}_{}.png'.format(obj, datas[idx].isot),dpi=100) print 'Gerado: {}_{}.png'.format(obj, datas[idx].isot) plt.clf()
def plotIce(u, cmap, scale='lin', name='', units='', numLvls=12, tp=False, tpAlpha=0.5): """ INPUTS : u : solution to plot. cmap : colormap to use - see images directory for sample and name scale : scale to plot, either 'log' or 'lin' name : title of the plot, latex accepted units : units for the colorbar, latex approved numLvls : number of levels for field values tp : boolean determins plotting of triangle overlay tpAlpha : alpha level of triangles 0.0 (transparent) - 1.0 (opaque) OUTPUT : A sigle 250 dpi .png in the source directory. """ #============================================================================= # format stuff that needs to be formatted : dec = 1 field = '' dec = 1 # data gathering : mesh = u.function_space().mesh() coord = mesh.coordinates() fi = mesh.cells() vv = u.compute_vertex_values(mesh) vx = coord[:,0] vy = coord[:,1] #============================================================================= # map functions : fig = plt.figure(figsize=(13.5,7), dpi=80) ax = fig.add_axes() # map projection that the data is based on : m = Basemap(projection='stere', lat_ts=70.0, lat_0=90.0, lon_0=-45.0, resolution='l', llcrnrlat=55,llcrnrlon=-55,urcrnrlat=80,urcrnrlon=0.0) # adjustment of x, y coordinates for N. polar projection : x = vx + m.projparams['x_0'] y = vy + m.projparams['y_0'] v = vv # conversion to lon, lat coordinates : lon, lat = m(x, y, inverse = True) # new projection of our choosing : m = Basemap(ax=ax, width=62000.0, height=26000.0, resolution='h',projection='stere', lat_ts=67.03, lon_0=-48.675, lat_0=67.03) m.etopo() # conversion to projection coordinates from lon, lat : x, y = m(lon, lat) m.drawcoastlines(linewidth=0.25, color = 'black') # draw lat/lon grid lines every 5 degrees. # labels = [left,right,top,bottom] m.drawmeridians(np.arange(0, 360, 0.25), color = 'black', labels = [False, False, False, True]) m.drawparallels(np.arange(-90, 90, 0.25), color = 'black', labels = [True, False, False, False]) m.drawmapscale(-48.25, 66.94, -48.675, 67.675, 10, yoffset=(0.01*(m.ymax-m.ymin)), barstyle='fancy') #============================================================================= # plotting : # countour levels : if scale == 'log': vmax = ceil(max(v)) if field == 'melt_rate': v[where(v<=0.0)] = 0.00001 #v[where(v<=0.0)] = 0.0 + min(v[where(v>0.0)])/10 levels = logspace(log10(0.001), log10(vmax), numLvls) #levels = [0.0001, 0.0002, 0.001, 0.002, 0.01, 0.02, # 0.04, 0.08, 0.20, 0.40,0.80 ] elif field == 'sliding_ratio': v[where(v<=0.0)] = 0.001 levels = logspace(log10(0.1), log10(2), numLvls) else: vmin = floor(min(v)) v[where(v<=0.0)] = 1.0 levels = logspace(0.0, log10(vmax+1), numLvls) from matplotlib.ticker import LogFormatter formatter = LogFormatter(10, labelOnlyBase=False) norm = colors.LogNorm() elif scale == 'lin': vmin = floor(min(v)) vmax = ceil(max(v)) levels = linspace(vmin, vmax+1, numLvls) from matplotlib.ticker import ScalarFormatter formatter = ScalarFormatter() norm = None elif scale == 'bool': levels = [0, 1, 2] from matplotlib.ticker import ScalarFormatter formatter = ScalarFormatter() norm = None # plots with generated triangles : cs = tripcolor(x, y, fi, v, shading='gouraud', cmap=get_cmap(cmap), norm=norm) #cs = tricontourf(x, y, fi, v, #levels=levels, # cmap=get_cmap(cmap), norm=norm) # plot triangles : if tp == True: tp = triplot(x, y, fi, '-', lw=0.2, alpha=tpAlpha) # include colorbar : if field != 'melted' : if field == 'beta2' or field == 'U_observed' or field == 'U_surface'\ or field == 'U_bed' or field == 'sliding_ratio': levels[0] = 0.0 cbar = m.colorbar(cs, format=formatter, ticks=around(levels,decimals=dec), location='right', pad="5%") elif field == 'T_surf' or field == 'T_basal': cbar = m.colorbar(cs, format=formatter, ticks=around(levels,decimals=dec), location='right', pad="5%") elif field == 'melt_rate': cbar = m.colorbar(cs, format=formatter, ticks=levels, location='right', pad="5%") elif field == 'sliding_ratio': levels[0] = 0.0 cbar = m.colorbar(cs, format=formatter, ticks=levels, location='right', pad="5%") else : cbar = m.colorbar(cs, format=formatter, ticks=around(levels,decimals=dec), location='right', pad="5%") # colorbar label : txt = figtext(.95, .50, units) txt.set_fontsize(20.0) tit = title(name) savefig(name + '.png', dpi=250) show()
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt map = Basemap(llcrnrlon=-10.5,llcrnrlat=33,urcrnrlon=10.,urcrnrlat=46., resolution='i', projection='cass', lat_0 = 39.5, lon_0 = 0.) map.etopo() map.drawcoastlines() plt.show()