def figures(): from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt plt.figure() # setup north polar stereographic basemap. # The longitude lon_0 is at 6-o'clock, and the # latitude circle boundinglat is tangent to the edge # of the map at lon_0. Default value of lat_ts # (latitude of true scale) is pole. m = Basemap(projection='spstere', boundinglat=-30, lon_0=90, resolution='l') #X,Y=np.repeat(np.repeat(lat2,5,axis=0),5,axis=1).reshape(2030,1350, order='F'),np.repeat(np.repeat(lon2,5,axis=0),5,axis=1).reshape(2030,1350,order='F') m.fillcontinents(color='coral', lake_color='aqua') #m.pcolormesh(Y,X,colour[1,:,:1350]) plt.show() #doesnt quite work #TODO fix the bug in this code # draw parallels and meridians. m.drawparallels(np.arange(-80., 81., 20.)) m.drawmeridians(np.arange(-180., 181., 20.)) m.drawmapboundary(fill_color='aqua') # draw tissot's indicatrix to show distortion. ax = plt.gca() for y in np.linspace(19 * m.ymin / 20, m.ymin / 20, 10): for x in np.linspace(19 * m.xmin / 20, m.xmin / 20, 10): lon, lat = m(x, y, inverse=True) poly = m.tissot(lon, lat, 2.5, 100, \ facecolor='green', zorder=10, alpha=0.5) plt.title("South Polar Stereographic Projection")
def plot_south_steradian_view(ra, dec, numPoints=100, radius=1.75, boundary=20., ax=None, show_frame=True): """ """ if ax is None: fig, ax = plt.subplots() m = Basemap(projection='spstere', boundinglat=boundary, lon_0=0., ax=ax) if show_frame: m.drawparallels(np.arange(-80., 81., 20.)) m.drawmeridians(np.arange(-180., 181., 20.)) for ra_val, dec_val in zip(ra, dec): m.tissot(ra_val, dec_val, radius, numPoints, ax, **dict(fill=False)) return fig
from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt # lat_1、lat_2 分别是第一、二标准纬线,lat_2默认值等于lat_1 # rsphere=(6378137.00,6356752.3142)指定了WGS84投影椭球 m = Basemap(width=12000000,height=9000000, rsphere=(6378137.00,6356752.3142),\ resolution='l',area_thresh=1000.,projection='lcc',\ lat_1=45.,lat_2=55,lat_0=50,lon_0=108.) m.drawcoastlines() m.fillcontinents(color='y', lake_color='c') m.drawparallels(np.arange(-80., 81., 20.)) m.drawmeridians(np.arange(0., 361., 20.)) m.drawmapboundary(fill_color='c') # 绘制tissot's indicatrix以展示失真程度 ax = plt.gca() for y in np.linspace(m.ymax / 20, 19 * m.ymax / 20, 9): for x in np.linspace(m.xmax / 20, 19 * m.xmax / 20, 12): lon, lat = m(x, y, inverse=True) poly = m.tissot(lon,lat,2.,100,\ facecolor='red',zorder=10,alpha=0.5) plt.title("Lambert Conformal Projection") plt.show()
def draw_market_map(ls_market_ids, directory, zoom = 12, delta_lng = 0.18, delta_lat = 0.10): ls_close_ids = [x[0] for market_id in ls_market_ids for x in dict_ls_close[market_id]] ls_outside_ids = list(set(ls_close_ids).difference(set(ls_market_ids))) ls_market_coordinates = [df_info.ix[x][['lat', 'lng']].tolist() for x in ls_market_ids] lat_ref = (np.max([x[0] for x in ls_market_coordinates]) +\ np.min([x[0] for x in ls_market_coordinates])) / 2 lng_ref = (np.max([x[1] for x in ls_market_coordinates]) +\ np.min([x[1] for x in ls_market_coordinates])) / 2 ls_outside_coordinates = [df_info.ix[x][['lat', 'lng']].tolist() for x in ls_outside_ids] ## todo: see how to get dist of X km? #zoom = 12 # defines how many tiles are collected (precision) #delta_lat = 0.10 # height 0.10 #delta_lng = 0.18 # width 0.18 adj_lng_c = 0 # -0.01 a, bbox = getImageCluster(lat_ref - delta_lat, # need 1/2 delta_lat lng_ref - delta_lng + adj_lng_c, # need 1/2 delta_lng delta_lat * 2, delta_lng * 2, zoom) fig = plt.figure(figsize=(10, 10)) ax = plt.subplot(111) m = Basemap( llcrnrlon=bbox[0], llcrnrlat=bbox[1], urcrnrlon=bbox[2], urcrnrlat=bbox[3], projection='merc', ax=ax) # display image composed of OSM times m.imshow(a, interpolation='lanczos', origin='upper') # convert coord (caution: inversion) for ls_gps_points, marker_c, marker in [[ls_market_coordinates, 'b', 'o'], [ls_outside_coordinates, 'r', 's']]: ls_points = [m(x[1], x[0]) for x in ls_gps_points] ax.scatter([point[0] for point in ls_points], [point[1] for point in ls_points], alpha = 0.8, s = 30, color = marker_c, marker = marker, zorder = 9) # add circles def radius_for_tissot(dist_km): return np.rad2deg(dist_km/6367.) for ls_gps_points, marker_c, radius in [[ls_market_coordinates, 'b', 3], [ls_outside_coordinates, 'r', 5]]: for lat_x, lng_x in ls_gps_points: m.tissot(lng_x, lat_x, radius_for_tissot(radius), 256, facecolor=marker_c, alpha=0.1, zorder = 8) # need to cut again (otherwise get whole loaded tiles displayed) xmin, ymin = m(lng_ref - delta_lng + adj_lng_c, lat_ref - delta_lat) xmax, ymax = m(lng_ref + delta_lng + adj_lng_c, lat_ref + delta_lat) ax.set_xlim((xmin, xmax)) ax.set_ylim((ymin, ymax)) plt.tight_layout() #plt.show() # add correct map scale (or try using tmerc?) xmin_deg, ymin_deg = m(xmin, ymin, inverse = True) xmax_deg, ymax_deg = m(xmax, ymax, inverse = True) dref = 3.0 lat0 = ymin_deg + 0.005 #0.012 distance=dref/np.cos(lat0*np.pi/180.) scale = m.drawmapscale(lon = xmin_deg + 0.02, lat = ymin_deg + 0.005, #0.012, lon0 = lng_ref, #m.llcrnrlon, lat0 = lat_ref, #m.llcrnrlat, barstyle = 'fancy', labelstyle = 'simple', length = distance, yoffset = 0.01*(m.ymax-m.ymin), format = '%.1f') scale[12].set_text(dref/2.0) scale[13].set_text(dref) nb_ids = len(ls_market_ids) subdir = 'maps_market_6_plus' if nb_ids < 6: subdir = 'maps_market_{:d}'.format(nb_ids) plt.savefig(os.path.join(path_dir_built_graphs, directory, '{:d}_{:s}_map.png'.format(nb_ids, ls_market_ids[0])), dpi=90, alpha=True, bbox_inches = 'tight') plt.close()
def plotTilePointings(self, tileID, raCol='ditheredRA', decCol='ditheredDec', radius=1.75, paddingFactors=1, query=None, ax=None, projection='cyl', tile_centers=None, corners=None, drawPointings=True, **kwargs): """ Plot the Healpix Tile and the maximal set of pointings overlapping with it. Parameters ---------- tileID : int, mandatory Healpix tileID in the nested scheme raCol : string, defaults to 'ditheredRA' column name with ra that should be used decCol : string, defaults to 'ditheredDec' column name with dec that should be used radius : float, defaults to 1.75, degrees radius of the field of view paddingFactors: float, defaults to 1.0 controls the size of the figure wrt angular dimensions of the tile. paddingFactors=1 is designed to get all the centers of pointings overlapping the tile inside the figure query : string query for the pandas dataframe to select only some of the observations ax : instance of matplotlib.figure.axes axes for figure. New figure created insitue if not provided projections: string, defaults to `cyl` string to specify the `Basemap.projection` tile_centers : tuples of 2 floats, degrees, defaults to None (ra of the center of the figure, dec of the center of the figure) in degrees if None, the center is set by using the center of the Healpixel of tileID and `self.nside` corners: tuple of floats, defaults to None kwargs: passed to the plotting of the the field of veiw drawPointings : Bool, defaults to True if False, draws only Tiles Returns ------- fig, tile_centers, corners ..notes: Have not thought about wrapover """ # if axes object not provided setup figure if ax is None: fig, ax = plt.subplots() # size of box padding = np.degrees(hp.max_pixrad(self.nside)) + radius # center of the figure if tile_centers is None: ra_tile = self.tileCenter(tileID)[0][0] dec_tile = self.tileCenter(tileID)[1][0] else: ra_tile, dec_tile = tile_centers # corner of the figure if corners is not None: llcrnrlat, llcrnrlon, urcrnrlat, urcrnrlon = corners else: llcrnrlat = dec_tile - padding * paddingFactors urcrnrlat = dec_tile + padding * paddingFactors llcrnrlon = ra_tile - padding * paddingFactors urcrnrlon = ra_tile + padding * paddingFactors # Instantiate basemap m = Basemap(llcrnrlat=llcrnrlat, llcrnrlon=llcrnrlon, urcrnrlat=urcrnrlat, urcrnrlon=urcrnrlon, projection=projection, lon_0=ra_tile, lat_0=dec_tile, ax=ax) # Draw some parallels and meridians to get a spatial sense parallels = np.linspace(llcrnrlat, urcrnrlat, 3) meridians = np.linspace(llcrnrlon, urcrnrlon, 3) m.drawparallels(parallels, labels=(1, 0, 0, 0)) m.drawmeridians(meridians, labels=(0, 1, 1, 1)) # obtain the boundaries of the Healpixels and create the polygon patch lon, lat = healpix_boundaries(tileID, nside=self.nside, units='degrees', convention='celestial', step=10, nest=True) x, y = m(lon, lat) xy = zip(x, y) healpixels = Polygon(xy, facecolor='w', fill=False, alpha=1., edgecolor='k', lw=2) if drawPointings: # Obtain the centers of pointings ra, dec = self.pointingCenters(tileID, raCol=raCol, decCol=decCol, query=query) for ra, dec in zip(ra, dec): m.tissot(ra, dec, radius, 100, **kwargs) # Draw patch ax.add_patch(healpixels) # really important for the case where ax is None if ax is not None: fig = ax.figure return fig, (ra_tile, dec_tile), (llcrnrlat, llcrnrlon, urcrnrlat, urcrnrlon)
fig.set_size_inches(12.5, 10) p1 = plt.subplot(221) # lon_0, lat_0 are the center point of the projection. # resolution = 'l' means use low resolution coastlines. m = Basemap(projection='ortho', lon_0=20, lat_0=0, resolution='c') m.drawcoastlines(color="#999999") # m.fillcontinents(color='coral', lake_color='aqua') # draw parallels and meridians. m.drawparallels(np.arange(-90., 120., 30.)) m.drawmeridians(np.arange(0., 420., 60.)) # m.drawmapboundary(fill_color='aqua') for lon in range(0, 360, 20): for lat in range(-60, 90, 30): m.tissot(lon, lat, 4, 50) # plt.show() ########################################################################### ########################################################################## p2 = plt.subplot(222) my_map = Basemap(projection='robin', lat_0=0, lon_0=105, resolution='l', area_thresh=1000.0) my_map.drawparallels(np.arange(-90., 120., 30.))
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt map = Basemap(width=8000000,height=7000000, resolution='l',projection='aea',\ lat_1=40.,lat_2=60,lon_0=35,lat_0=50) map.drawmapboundary(fill_color='aqua') map.fillcontinents(color='coral',lake_color='aqua') map.drawcoastlines() for lon in range(-160, 180, 20): for lat in range(-60, 90, 10): map.tissot(lon, lat, 2, 50) plt.show()
Path.LINETO, Path.LINETO, Path.CLOSEPOLY, ] path = Path(verts, codes2) return path plt.close() fig,ax = plt.subplots(nrows=1,ncols=1,figsize=(6,6)) m = Basemap(projection='ortho',lon_0=-50,lat_0=20,resolution='l',ax=ax) m.bluemarble(scale=0.2) # Maria on 800 AM AST Tue Sep 19 2017 http://www.nhc.noaa.gov/archive/2017/al15/al152017.public_a.013.shtml? m.tissot(-62.8, 16.2, 205/40000.*360, 50, color='white',alpha=0.4) m.tissot(-62.8, 16.2, 95/40000.*360, 50, color='white',alpha=0.4) for lon in np.arange(-80,-40,2): for lat in np.arange(0,30,2): path = projected_polygon(m,[(lon,lat),(lon+2,lat),(lon+2,lat+2),(lon,lat+2),(lon,lat)]) patch = patches.PathPatch(path, facecolor='r',lw=1.5,edgecolor='r',alpha=0.2) ax.add_patch(patch) plt.tight_layout() plt.savefig('plots/GCM_Maria_.png') plt.close() fig,ax = plt.subplots(nrows=1,ncols=1,figsize=(6,6)) m = Basemap(lat_0=16.2,lon_0=-62.8,width=1400000,height=1400000,projection='lcc',lat_1=10.,lat_2=20.,resolution ='l',area_thresh=1000.,ax=ax) m.bluemarble(scale=0.2)
lat_0=ar_lat, epsg=4326, llcrnrlat=-57, urcrnrlat=-20, llcrnrlon=-75, urcrnrlon=-52) m.drawmapboundary(fill_color='#A6CAE0', linewidth=0) m.fillcontinents(color='grey', alpha=0.7, lake_color='grey') m.drawcoastlines(linewidth=0.1, color="white") m.drawcountries(linestyle='--') for e in estaciones.itertuples(): if e.tipo == "Central": m.tissot(e.longitud, e.latitud, np.rad2deg(300 / 6367.), 256, facecolor='b', alpha=0.5) m.plot(e.longitud, e.latitud, linestyle='none', marker="o", markersize=7, alpha=0.6, c='red' if e.tipo == 'Central' else 'orange' if e.tipo == 'Vecina' else 'green', markeredgecolor="black", markeredgewidth=1) plt.show()
plon2.append(float(tmp[7])) for s in range(len(slats)): print(s + 1, len(slats)) m.drawgreatcircle(elon, elat, slons[s], slats[s], linewidth=0.5, color='gray', alpha=0.5, zorder=1) m.drawgreatcircle(plon1[s], plat1[s], plon2[s], plat2[s], linewidth=0.5, color='g', zorder=2) x1, y1 = m(slons[s], slats[s]) m.scatter(x1, y1, s=40, marker='^', facecolors='white', alpha=1, zorder=2) x, y = m(elon + 360., elat) if (i == 2): m.scatter(x, y, s=265, marker='*', facecolors='y', alpha=1, zorder=2, label='Event') m.scatter(x1, y1, s=40, marker='^', facecolors='white', alpha=1, zorder=2, label='Station') else: m.scatter(x, y, s=265, marker='*', facecolors='y', alpha=1, zorder=2) x0, y0 = -167.5, 17.5 R = 7.5 m.tissot(x0, y0, R, 100, facecolor='b', alpha=0.4, label='ULVZ') plt.legend(loc=4) fig.savefig('Plots/eventMap.png', bbox_inches='tight') fig.savefig('Plots/eventMap.pdf', bbox_inches='tight') plt.show()
def map_plot(self, time, TLE): start_mode = self.mode_choice.GetSelection() m = Basemap(projection='mill', area_thresh=1000.0, llcrnrlat=south, urcrnrlat=north, llcrnrlon=west, urcrnrlon=east) #m.shadedrelief() im = Image.open(resource_path('default_map.png')) m.imshow(im, alpha=1) m.nightshade(time + datetime.timedelta(hours=10)) #m.drawcoastlines() # 一分ごとの人工衛星の位置をプロット time_list = [] for t in range(-10, 100): time_list.append(time + datetime.timedelta(minutes=t)) for t in time_list: satellite = ephem.readtle(TLE[0], TLE[1], TLE[2]) satellite.compute(t) latitude = satellite.sublat / ephem.degree longitude = satellite.sublong / ephem.degree - 150 if longitude < -180: longitude += 360 x1, y1 = m(longitude, latitude) m.plot(x1, y1, marker=".", markersize=1, c='blue') if self.mode_choice.GetSelection() != start_mode: if self.mode_choice.GetSelection(): time = datetime.datetime.utcnow() else: time = self.get_time() self.map_plot(time, TLE) return 0 satellite = ephem.readtle(TLE[0], TLE[1], TLE[2]) satellite.compute(time) latitude = satellite.sublat / ephem.degree longitude = satellite.sublong / ephem.degree - 150 if longitude < -180: longitude += 360 earth_radius = 6371000. sat_loc = (latitude, longitude) # define the position of the satellite orbit = Orbital(TLE[0], line1=TLE[1], line2=TLE[2]) lon_dum, lat_dum, altitude = orbit.get_lonlatalt(time) print(altitude) position = [altitude * 1000, latitude, longitude] radius = math.degrees( math.acos(earth_radius / (earth_radius + position[0]))) print(longitude) x1, y1 = m(longitude, latitude) m.plot(x1, y1, marker="*", markersize=5, c='red') if longitude < -90: diff = longitude - (-180) m = Basemap(projection='mill', area_thresh=1000.0, llcrnrlat=south, urcrnrlat=north, llcrnrlon=0, urcrnrlon=360) m.tissot(diff, latitude, radius, 100, facecolor='white', alpha=0.5) m = Basemap(projection='mill', area_thresh=1000.0, llcrnrlat=south, urcrnrlat=north, llcrnrlon=-360, urcrnrlon=0) m.tissot(diff, latitude, radius, 100, facecolor='white', alpha=0.5) elif longitude > 90: diff = longitude - 180 m = Basemap(projection='mill', area_thresh=1000.0, llcrnrlat=south, urcrnrlat=north, llcrnrlon=0, urcrnrlon=360) m.tissot(diff, latitude, radius, 100, facecolor='white', alpha=0.5) m = Basemap(projection='mill', area_thresh=1000.0, llcrnrlat=south, urcrnrlat=north, llcrnrlon=-360, urcrnrlon=0) m.tissot(diff, latitude, radius, 100, facecolor='white', alpha=0.5) else: m.tissot(longitude, latitude, radius, 100, facecolor='white', alpha=0.5) plt.gca().spines['right'].set_visible(False) plt.gca().spines['top'].set_visible(False) plt.gca().spines['left'].set_visible(False) plt.gca().spines['bottom'].set_visible(False) plt.subplots_adjust(left=0, right=1, bottom=0, top=1) buf = io.BytesIO() plt.savefig(buf, format='png', dpi=300, transparent=False, bbox_inches='tight', pad_inches=0) #plt.savefig('map.png',format='png', dpi = 600, transparent = False, bbox_inches = 'tight', pad_inches = 0) plt.close() buf.seek(0) self.output_map = buf if self.mode_choice.GetSelection() != start_mode: if self.mode_choice.GetSelection(): time = datetime.datetime.utcnow() else: time = self.get_time() self.map_plot(time, TLE) return 0 self.Image = wx.Image(buf, wx.BITMAP_TYPE_ANY) self.wxImage = wx.Bitmap(self.Image) #画像リサイズ対象=wx.Bitmap self.wxImage_re = scale_bitmap(self.wxImage, int(16 * self.ratio), int(9 * self.ratio)) self.tracking_map.SetBitmap(self.wxImage_re)
class GlobeMap: def __init__(self, ax, lat=50, lon=-100): # set up orthographic map projection with # perspective of satellite looking down at 50N, 100W. # use low resolution coastlines. # don't plot features that are smaller than 1000 square km. self.ax = ax self.dispSize = 2. # twice bigger than actual size self.map = Basemap(projection='ortho', lat_0=lat, lon_0=lon, resolution='l', area_thresh=1000., ax=ax) def drawGlobe(self, grid=10, gridopt=True): # draw coastlines, country boundaries, fill continents. self.map.drawcoastlines(ax=self.ax) self.map.drawcountries(ax=self.ax) #self.map.fillcontinents(color = 'green') #self.map.drawmapboundary() #self.map.drawlsmask(land_color='#FFFFCC', ocean_color='#6699FF', lakes=True, ax=self.ax) self.map.drawlsmask(land_color='yellowgreen', ocean_color='#CCFFFF', lakes=True, ax=self.ax) # draw the edge of the self.map projection region (the projection limb) # draw lat/lon grid lines every 2 degrees. if gridopt: self.map.drawmeridians(np.arange(0, 360, grid), ax=self.ax) self.map.drawparallels(np.arange(-90, 90, grid), ax=self.ax) plt.draw() def drawSatellite(self): self.map.bluemarble() plt.draw() def drawHurricanes(self, hurricanes): # lat/lon coordinates lats = list(hurricanes[:, 0]) lons = list(hurricanes[:, 1]) # compute the native self.map projection coordinates for cities. x, y = self.map(lons, lats) # by __call__ function definition # take the positions on the backside of globe display out subidx = 0 for i in xrange(len(x)): if x[i - subidx] > 1e20 or y[i - subidx] > 1e20: x.pop(i - subidx) y.pop(i - subidx) subidx = subidx + 1 # plot filled circles at the locations of the cities. self.map.plot(x, y, 'ro', markersize=5 * self.dispSize) plt.draw() def fillGrids(self, gridsCoord): for grid in gridsCoord: #self.map.drawgreatcircle(grid[1],grid[0],grid[3],grid[2]) x, y = self.map([grid[1], grid[3]], [grid[0], grid[2]]) if 1e30 in x or 1e30 in y: continue self.map.tissot((grid[1] + grid[3]) / 2., (grid[0] + grid[2]) / 2., (grid[3] - grid[1]) * self.dispSize / 2., 100) plt.draw()
[df_lsa_ot_S_og, 'r', 'S']] from matplotlib.font_manager import FontProperties for df_temp, marker_c, marker_l in ls_groups: ls_points = [m(row['longitude'], row['latitude']) for row_ind, row\ in df_temp.iterrows()] ax.scatter([point[0] for point in ls_points], [point[1] for point in ls_points], alpha = 0.8, s = 50, color = marker_c, zorder = 9, marker = TextPath((0,0), marker_l, color = marker_c, size = 7)) # display circle def radius_for_tissot(dist_km): return np.rad2deg(dist_km/6367.) m.tissot(lng_ref, lat_ref, radius_for_tissot(30), 256, facecolor='b', alpha=0.1, zorder = 8) # print ax.get_xlim() # print ax.get_ylim() xmin, xmax = 10000, 156367 ymin, ymax = 50000, 150000 ax.set_xlim((xmin, xmax)) ax.set_ylim((ymin, ymax)) xmin_deg, ymin_deg = m(xmin, ymin, inverse = True) xmax_deg, ymax_deg = m(xmax, ymax, inverse = True) ## mapscale has a bug with merc projection (use tmerc if needed) #m.drawmapscale(lon = xmin_deg + 0.1, # lat = ymin_deg + 0.05,
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt map = Basemap(width=8000000,height=7000000, resolution='l',projection='aea',\ lat_1=40.,lat_2=60,lon_0=35,lat_0=50) map.drawmapboundary(fill_color='aqua') map.fillcontinents(color='coral', lake_color='aqua') map.drawcoastlines() for lon in range(-160, 180, 20): for lat in range(-60, 90, 10): map.tissot(lon, lat, 2, 50) plt.show()
from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt # setup lambert conformal basemap. # lat_1 is first standard parallel. # lat_2 is second standard parallel (defaults to lat_1). # lon_0,lat_0 is central point. # rsphere=(6378137.00,6356752.3142) specifies WGS4 ellipsoid # area_thresh=1000 means don't plot coastline features less # than 1000 km^2 in area. m = Basemap(width=12000000,height=9000000, rsphere=(6378137.00,6356752.3142),\ resolution='l',area_thresh=1000.,projection='lcc',\ lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.) m.drawcoastlines() m.fillcontinents(color='coral', lake_color='aqua') # draw parallels and meridians. m.drawparallels(np.arange(-80., 81., 20.)) m.drawmeridians(np.arange(-180., 181., 20.)) m.drawmapboundary(fill_color='aqua') # draw tissot's indicatrix to show distortion. ax = plt.gca() for y in np.linspace(m.ymax / 20, 19 * m.ymax / 20, 9): for x in np.linspace(m.xmax / 20, 19 * m.xmax / 20, 12): lon, lat = m(x, y, inverse=True) poly = m.tissot(lon,lat,1.5,100,\ facecolor='green',zorder=10,alpha=0.5) plt.title("Lambert Conformal Projection") plt.savefig('lcc.png')
# Plot previous exposures nexp_kwargs = dict(exp_kwargs) nexp_kwargs.update(zorder=exp_zorder-1,alpha=0.2,edgecolor='none')#,lw=0) logging.debug("Plotting last %i exposures"%opts.numexp) m.scatter(x[select],y[select],color=color[select],**nexp_kwargs) # Plot zenith position & focal plane scale zen_x,zen_y = m(lon_0,lat_0) zen_kwargs = dict(color='green',alpha=0.75,lw=1,zorder=0) if opts.zenith: logging.debug("Plotting zenith: (%.2f,%.2f)"%(lon_0,lat_0)) m.plot(zen_x,zen_y,'+',ms=10,**zen_kwargs) logging.debug("Plotting focal plane scale.") m.tissot(lon_0, lat_0, 1.0, 100, fc='none', **zen_kwargs) # Plot airmass circle if not np.isnan(opts.airmass): logging.debug("Plotting airmass: %s"%opts.airmass) angle = airmass_angle(opts.airmass) m.tissot(lon_0, lat_0, angle, 100, fc='none',**zen_kwargs) # Moon location and phase if opts.moon: (moon_ra,moon_dec),moon_phase = moon(utc) logging.debug("Plotting moon: %i%%,(%.1f,%.1f)"%(moon_phase,moon_ra,moon_dec)) moon_txt = '%i%%'%moon_phase moon_kwargs = dict(zorder=exp_zorder-1,fontsize=10,va='center',ha='center', bbox=dict(boxstyle='circle,pad=0.4',fc='k',ec='k',alpha=0.25,lw=2))
parallels = np.arange(-90,90,10) m.drawparallels(parallels,labels=[True,True,True,False]) meridians = np.arange(-180.,180.,10) m.drawmeridians(meridians,labels=[True,False,False,True]) m.arcgisimage(service='ESRI_Imagery_World_2D', xpixels = 2000, verbose= True) #m.etopo() xs, ys = [],[] for lon, lat, gcarc, stat, statlon, statlat in zip(lons, lats, gcarcs, stations, statlons, statlats): x,y = m(lon, lat) # coordenadas da estacao xs.append(x) ys.append(y) m.plot(x, y, 'v', markersize=10) plt.text(x+10000,y-100000,stat, fontsize=8 ) m.tissot(lon, lat, gcarc/111.1,100,zorder=10,edgecolor='red',linewidth=0.6,facecolor='none') x,y = m(statlon, statlat) xs.append(x) ys.append(y) m.plot(x, y, '*', markersize=10) m.plot(xs, ys, color='black', linewidth=0.5, label='Raio')# Plot the line station to event #m.drawmapscale(-47.50, -33, 0, 0, 1000, barstyle='fancy', yoffset=20000)# drawmapscale #plt.title("Evento 09\n") plt.legend() plt.savefig('job_mestrado2.png',dpi = 600) plt.show()
class PlotSkyPatch: """ Class to plot a close-up look of a region of interest (ROI) in the sky. To use this class you need to install the Basemap package: https://matplotlib.org/basemap/users/installing.html .. code-block:: python from astrotools.skymap import PlotSkyPatch patch = PlotSkyPatch(lon0, lat0, r_roi, title='My Skypatch') mappable = patch.plot_crs("/path/to/cosmic_rays.CosmicRaysSets.npz", set_idx=0) patch.mark_roi() patch.plot_grid() patch.colorbar(mappable) patch.savefig("/tmp/test-skypatch.png") """ def __init__(self, lon_roi, lat_roi, r_roi, ax=None, title=None, **kwargs): """ :param lon_roi: Longitude of center of ROI in radians (0..2*pi) :param lat_roi: Latitude of center of ROI in radians (0..2*pi) :param r_roi: Radius of ROI to be plotted (in radians) :param ax: Matplotlib axes in case you want to plot on certain axes :param title: Optional title of plot (plotted in upper left corner) :param kwargs: keywords passed to matplotlib.figure() """ from mpl_toolkits.basemap import Basemap # pylint: disable=import-error,no-name-in-module import matplotlib as mpl with_latex_style = { "text.usetex": True, "font.family": "serif", "axes.labelsize": 30, "font.size": 30, "legend.fontsize": 30, "xtick.labelsize": 26, "ytick.labelsize": 26, "legend.fancybox": False, "lines.linewidth": 3.0, "patch.linewidth": 3.0 } mpl.rcParams.update(with_latex_style) assert (isinstance(lon_roi, (float, int))) and (isinstance(lat_roi, (float, int))) and \ (isinstance(r_roi, (float, int))), "Keywords 'lon_roi', 'lat_roi' and 'r_roi' have to be floats or ints!" self.vec_0 = coord.ang2vec(lon_roi, lat_roi) self.lon_0 = np.rad2deg(lon_roi) self.lat_0 = np.rad2deg(lat_roi) self.r_roi = r_roi self.scale = 5500000 * (r_roi / 0.3) self.fig = None self.ax = ax if ax is None: kwargs.setdefault('figsize', [8, 8]) self.fig = plt.figure(**kwargs) self.ax = plt.axes() self.title = title if title is not None: self.text(0.02, 0.98, title, verticalalignment='top', fontsize=36) self.m = Basemap(width=self.scale, height=self.scale, resolution='l', projection='stere', celestial=True, lat_0=self.lat_0, lon_0=-360 - self.lon_0 if self.lon_0 < 0 else -self.lon_0, ax=ax) def plot_crs(self, crs, set_idx=0, zorder=0, cmap='viridis', **kwargs): """ Plot cosmic ray events in the sky. :param crs: Either cosmic_rays.CosmicRaysBase or cosmic_rays.CosmicRaysSets object (or path) or dict object :param set_idx: In case of CosmicRaysSets object, chose the respective set index :param zorder: Usual matplotlib zorder keyword (order of plotting) :param cmap: Matplotlib colormap object or string """ if isinstance(crs, str): from astrotools import cosmic_rays try: crs = cosmic_rays.CosmicRaysBase(crs) except AttributeError: crs = cosmic_rays.CosmicRaysSets(crs) if hasattr(crs, 'type') and (crs.type == "CosmicRaysSet"): crs = crs[set_idx] if 'log10e' in crs.keys(): log10e = crs['log10e'] assert np.all( log10e < 25 ), "Input energies ('log10e' key) are too high for being plotted" kwargs.setdefault('s', 10**(log10e - 18.)) kwargs.setdefault('c', log10e) kwargs.setdefault('lw', 0) return self.scatter(crs['lon'], crs['lat'], zorder=zorder, cmap=cmap, **kwargs) def plot(self, lons, lats, **kwargs): """ Replaces matplotlib.pyplot.plot() function """ kwargs.setdefault('rasterized', True) x, y = self.m(np.rad2deg(lons), np.rad2deg(lats)) return self.m.plot(x, y, **kwargs) def scatter(self, lons, lats, **kwargs): """ Replaces matplotlib.pyplot.scatter() function """ kwargs.setdefault('rasterized', True) x, y = self.m(np.rad2deg(lons), np.rad2deg(lats)) return self.m.scatter(x, y, **kwargs) def tissot(self, lon, lat, radius, npts=1000, **kwargs): """ Replaces the Basemap tissot() function (plot circles) """ kwargs.setdefault('fill', False) kwargs.setdefault('lw', 1) kwargs.setdefault('color', 'grey') return self.m.tissot(np.rad2deg(lon), np.rad2deg(lat), np.rad2deg(radius), npts, **kwargs) def mark_roi(self, alpha=0.4, **kwargs): """ Marks the ROI by a circle ans shades cosmic rays outside the ROI. :param kwargs: Passed to Basemaps tissot() function """ from matplotlib import path, collections kwargs.setdefault('lw', 2) kwargs.setdefault('zorder', 3) try: t = self.tissot(np.deg2rad(self.lon_0), np.deg2rad(self.lat_0), self.r_roi, **kwargs) xyb = np.array([[0., 0.], [1., 0.], [1., 1.], [0., 1.], [0., 0.] ]) * self.scale p = path.Path(np.concatenate([xyb, t.get_xy()[::-1]])) p.codes = np.ones(len(p.vertices), dtype=p.code_type) * p.LINETO p.codes[0] = path.Path.MOVETO p.codes[4] = path.Path.CLOSEPOLY p.codes[5] = path.Path.MOVETO p.codes[-1] = path.Path.CLOSEPOLY col = collections.PathCollection([p], facecolor='white', alpha=alpha, zorder=1) self.ax.add_collection(col) except ValueError: print( "Warning: Could not plot ROI circle due to undefined inverse geodesic!" ) self.mark_roi_center() def mark_roi_center(self, **kwargs): """ Mark the ROI center :param kwargs: keywords for matplotlib.pyplot.plot() function """ kwargs.setdefault('marker', '+') kwargs.setdefault('markersize', 20) kwargs.setdefault('color', 'k') kwargs.setdefault('lw', 2) x, y = self.m(self.lon_0, self.lat_0) self.m.plot((x), (y), **kwargs) def plot_grid(self, meridians=None, parallels=None, mer_labels=None, par_labels=None): """ Plot the longitude and latitude grid in the skypatch """ if meridians is None: meridians = np.arange(-180, 181, 60) if abs(self.lat_0) > 60 else np.arange( -180, 181, 20) if parallels is None: parallels = np.arange(-90, 91, 15) if abs(self.lat_0) > 60 else np.arange( -90, 91, 20) self.m.drawmeridians(meridians, labels=[False, False, True, False] if mer_labels is None else mer_labels) self.m.drawparallels(parallels, labels=[True, True, False, False] if par_labels is None else par_labels) def plot_thrust(self, n, t, **kwargs): """ Visualize the thrust observables in the ROI. :param n: Thrust axis as given by astrotools.obs.thrust()[1] :param t: Thrust values as returned by astrotools.obs.thrust()[0] :param kwargs: Keywords passed to matplotlib.pyplot.plot() for axis visualization """ kwargs.setdefault('c', 'red') linestyle_may = kwargs.pop('linestyle', 'solid') alpha_may = kwargs.pop('alpha', 0.5) lon, lat = coord.vec2ang(n[0]) # fill thrust array (unit vector phi runs in negative lon direction) e_phi = coord.sph_unit_vectors(lon, lat)[1] sign = np.sign(e_phi[2] - n[1][2]) phi_major = sign * coord.angle(e_phi, n[1])[0] phi_minor = sign * coord.angle(e_phi, n[2])[0] if np.abs(phi_major - phi_minor) < 0.99 * np.pi / 2.: phi_minor = 2 * np.pi - phi_minor t23_ratio = t[1] / t[2] # mark the principal axes n3 u = np.array(np.cos(phi_minor)) v = -1. * np.array(np.sin(phi_minor)) urot, vrot, x, y = self.m.rotate_vector(u, v, np.rad2deg(lon), np.rad2deg(lat), returnxy=True) _phi = np.arctan2(vrot, urot) s = self.r_roi * (t[1] / 0.15) * self.scale / t23_ratio self.m.plot([x - np.cos(_phi) * s, x + np.cos(_phi) * s], [y - np.sin(_phi) * s, y + np.sin(_phi) * s], linestyle='dashed', alpha=0.5, **kwargs) # mark the principal axes n2 u = np.array(np.cos(phi_major)) v = -1. * np.array(np.sin(phi_major)) urot, vrot, x, y = self.m.rotate_vector(u, v, np.rad2deg(lon), np.rad2deg(lat), returnxy=True) _phi = np.arctan2(vrot, urot) s = self.r_roi * (t[1] / 0.15) * self.scale self.m.plot([x - np.cos(_phi) * s, x + np.cos(_phi) * s], [y - np.sin(_phi) * s, y + np.sin(_phi) * s], linestyle=linestyle_may, alpha=alpha_may, **kwargs) # mark the center point self.m.plot((x), (y), 'o', color=kwargs.pop('c'), markersize=10) def colorbar(self, mappable, cblabel='Energy [eV]', labelsize=12, ticks=None, **kwargs): """ Adds a colorbar to a mappable in matplotlib. Replaces matplotlib colorbar() function. Use e.g: patch = PlotSkyPatch(...) mappable = patch.plot_crs(crs) patch.colorbar(mappable) :param mappable: Mappable in matplotlib. :param clabel: Label for the colorbar :param ticks: Ticks for the colorbar (either array-like or integer for number of ticks) :param kwargs: Keywords passed to matplotlib colorbar() function """ # add a colorbar try: kwargs.setdefault('location', 'bottom') cb = self.m.colorbar(mappable, **kwargs) if (ticks is None) or isinstance(ticks, (int, float)): vmin, vmax = mappable.get_clim() vmin, vmax = smart_round(vmin), smart_round(vmax) n_ticks = float(3) if ticks is None else float(ticks) step = smart_round((vmax - vmin) / n_ticks, order=1) ticks = np.arange(vmin, vmax, step) ticks = ticks[(ticks >= vmin) & (ticks <= vmax)] cb.set_ticks(ticks) cb.set_label(cblabel, fontsize=3 * labelsize) t = ['$10^{%.1f}$' % (f) for f in ticks] cb.ax.set_xticklabels(t, fontsize=int(max(0.8 * 3 * labelsize, 1))) except KeyError: print("Can not plot colorbar on axis.") def text(self, x, y, s, **kwargs): """ Substitudes matplotlib.pyplot.text() function """ kwargs.setdefault('transform', self.ax.transAxes) self.ax.text(x, y, s, **kwargs) def savefig(self, path, **kwargs): """ Substitudes matplotlib savefig() function """ kwargs.setdefault('dpi', 150) kwargs.setdefault('bbox_inches', 'tight') self.fig.savefig(path, **kwargs)
# Plots your own location home(my_map) # Plots satellite on the map lon = tle_sat.sublong / degree lat = tle_sat.sublat / degree x, y = my_map(lon, lat) my_map.plot(x, y, 'bo', markersize=4) plt.text(x, y, tle_sat.name) # Plots satellite footprint sat_radius = get_radius() my_map.tissot(x, y, sat_radius, 100, color='black', alpha=0.4, linestyle='dashed') # Plots the satellite groundpath in next 90min sat_lon_pred, sat_lat_pred = sat_groundpath(tle_sat) my_map.plot(sat_lon_pred, sat_lat_pred, 'wo', markersize=1) # Creates Observer and recomputes TLE user = observer() tle_sat.compute(user) # Try catch checks if satellite is never above horizon or the oppsite try: # Finds next satellite pass for the Observer
def show_igraph(fvert, fgmls, n_subgr, outfile, minsup, scale, labels, fontsize): (nx, ny, lons, lats) = read_areas_def(fvert) (narea, area_name, area_lon_wmc, area_lat_wmc, area_poly, vcolor, vcol_loop) = read_areas(fvert) ## MFS frame ## F_lon_min = min(lons) F_lon_max = max(lons) F_lat_min = min(lats) F_lat_max = max(lats) ## MFS frame ## F_lon_min = -5.5 F_lon_max = 36.0 F_lat_min = 30.24 F_lat_max = 45.9587212 ## AFS frame ## F_lon_min = 12.0 F_lon_max = 20.25 F_lat_min = 39.6 F_lat_max = 45.9587212 map = Basemap(llcrnrlon=F_lon_min,llcrnrlat=F_lat_min,urcrnrlon=F_lon_max,urcrnrlat=F_lat_max,\ rsphere=(6378137.00,6356752.3142),\ resolution='h',projection='merc') ax = plt.gca() #colors = ['blue','green','magenta','yellow','white','cyan','burlywood' ] #colors = ['blue','green','magenta','yellow','cyan','burlywood' ] #colors = ['blue','red','green','magenta','yellow','cyan','burlywood' ] colors = ['blue', 'red', 'green'] radii = 0. countr = 0 circleScale = 0.5 shape = [] rulea = [] fout = open(outfile, 'w') gcnt = 0 for fgml in fgmls: g = Graph.Read_GraphML(fgml) support = g["support"] support_season = g["support_season"] season = g["season"] if (support >= minsup): gcnt = gcnt + 1 print[gcnt, support, support_season, season] nrules = g.ecount() is_loop = g.es.is_loop() areas1 = g.vs.get_attribute_values('name') lon_wmc = g.vs.get_attribute_values('lon_wmc') lat_wmc = g.vs.get_attribute_values('lat_wmc') edges = g.get_edgelist() vertices = [] vert_loop = [] for i in range(nrules): if (not (is_loop[i])): vertices.append(areas1[edges[i][0]]) vertices.append(areas1[edges[i][1]]) if (is_loop[i]): vert_loop.append(areas1[edges[i][0]]) colr = 'black' if (len(vertices) > 0): gcolors = [] for vert in vertices: gcolors.append(vcolor[area_name.index(vert)]) col_avail = list( set(colors) - set(reduce(lambda x, y: x + y, gcolors, []))) if (len(col_avail) > 0): colr = col_avail[0] for vert in vertices: vcolor[area_name.index(vert)].append(colr) for vert in vert_loop: vcol_loop[area_name.index(vert)].append(colr) if (n_subgr > 1): m_lon_wmc = mean(lon_wmc) m_lat_wmc = mean(lat_wmc) (xt, yt) = map(m_lon_wmc, m_lat_wmc) # labels will be added manually in adobe acrobat ## ax.add_artist(plt.text(xt,yt,str(gcnt),fontsize=18, ## fontweight='normal', ha='center', va='center', color=colr,zorder=2000)) fout.write('%d %s\n' % (gcnt, g["support_season"])) area_this_epoch = [] area_next_epoch = [] lonm_this_epoch = [] latm_this_epoch = [] lonm_next_epoch = [] latm_next_epoch = [] conf = g.es.get_attribute_values("weight") for i in range(nrules): area_this_epoch.append(areas1[edges[i][0]]) area_next_epoch.append(areas1[edges[i][1]]) lonm_this_epoch.append(lon_wmc[edges[i][0]]) latm_this_epoch.append(lat_wmc[edges[i][0]]) lonm_next_epoch.append(lon_wmc[edges[i][1]]) latm_next_epoch.append(lat_wmc[edges[i][1]]) first = True for i in range(nrules): if (is_loop[i]): for j in range(narea): ## area A472 removed (Brindisi) if area_name[j] == area_this_epoch[ i] and area_this_epoch[i] != 'A472': x = [] y = [] polygon = area_poly[j].exterior.coords lp = len(polygon) for kk in range(lp): x.append(polygon[kk][0]) y.append(polygon[kk][1]) (xp, yp) = map(x, y) xpyp = zeros((lp, 2), dtype=float) for kk in range(lp): xpyp[kk, 0] = xp[kk] xpyp[kk, 1] = yp[kk] bounds = area_poly[i].bounds radius = (bounds[2] - bounds[0] + bounds[3] - bounds[1]) / 2 / 2 * (conf[i] / 3) * circleScale if (conf[i] == 3): radii = radii + radius countr = countr + 1 if (n_subgr == 1 or n_subgr == 8): # ec = 'r' ec = 'g' else: ec = colr cols = unique(vcol_loop[j]) cols = cols[1:] radius1 = radius if (len(cols) > 1): lenc = len(cols) - 1 for ic in range(len(cols) - 1): #radius1 = radius1 * 0.7 radius1 = radius * float(3 - ic) / 4 map.tissot(lonm_this_epoch[i], latm_this_epoch[i], radius1, 100, edgecolor='black', facecolor=ec, linewidth=1, zorder=500) if (len(cols) > 1): pie_size = [1. / len(cols)] * len(cols) (xt, yt) = map(lonm_this_epoch[i], latm_this_epoch[i]) draw_pie(ax, pie_size, xt, yt, size=775, colors=cols) if (labels == 2): (xt, yt) = map(lonm_this_epoch[i], latm_this_epoch[i]) ## plt.text(xt, yt, str(int(round(conf[i] * 100, 1))), fontsize=fontsize, ## fontweight='normal', ha='center', va='center', color='black') plt.text(xt, yt, area_this_epoch[i], fontsize=fontsize, fontweight='normal', ha='center', va='center', color='black', zorder=1000) break for i in range(nrules): ## the arrow A473 --> A472 removed (Brindisi) if (not (is_loop[i])) and area_next_epoch[i] != 'A472': (xbm, ybm) = map(lonm_this_epoch[i], latm_this_epoch[i]) (xm, ym) = map(lonm_next_epoch[i], latm_next_epoch[i]) if (n_subgr == 1 or n_subgr == 8): ec = 'g' else: ec = colr arr = ptch.FancyArrow(xbm, ybm, xm - xbm, ym - ybm, width=scale * conf[i], shape='full', length_includes_head=True, facecolor=ec, edgecolor='black', zorder=1000) ax = plt.gca() ax.add_patch(arr) if (labels == 2): att = plt.text(xbm + (xm - xbm) / 3, ybm + (ym - ybm) / 3, str(int(round(conf[i] * 100, 0))), fontsize=fontsize, fontweight='normal', ha='center', va='center', color='green') ax.add_artist(att) for iarea in range(narea): x = [] y = [] polygon = area_poly[iarea].exterior.coords lp = len(polygon) for kk in range(lp): x.append(polygon[kk][0]) y.append(polygon[kk][1]) (xp, yp) = map(x, y) xpyp = zeros((lp, 2), dtype=float) for kk in range(lp): xpyp[kk, 0] = xp[kk] xpyp[kk, 1] = yp[kk] ax.add_patch( ptch.Polygon(xpyp, closed=True, facecolor='none', edgecolor='black')) # draw coastlines, country boundaries, fill continents. map.drawcoastlines(linewidth=0.25) map.drawcountries(linewidth=0.25) land_color = (199, 233, 192) land_color = tuple(x / 255. for x in land_color) #map.fillcontinents(color='coral', lake_color='aqua') map.fillcontinents(color=land_color, lake_color='aqua') # draw the edge of the map projection region (the projection limb) map.drawmapboundary(fill_color='white') # draw lat/lon grid lines every five degrees. map.drawmeridians(arange(0, 360, 1), labels=[0, 0, 1, 0], fontsize=16, linewidth=0) map.drawparallels(arange(-90, 90, 1), labels=[1, 0, 0, 0], fontsize=16, linewidth=0) # legend of edges (adriatic) LXPosStart = 17.0 # legend edge start x position LXPosEnd = 18.0 # legend edge end x position LYPosStart = 45.35 # legend edge start y position LYPosEnd = LYPosStart # legend edge end y position #LYStepFactor = -1. / 4. # legend edges step factor LYStepFactor = -1. / 3. # legend edges step factor LXPosCircleStart = 18.5 LYPosCircleStart = 45.3 LXPosTextStart = 19.0 LYPosTextStart = 45.3 confText = ['low', 'medium', 'high'] #radii = radii / countr #return radii = radius for confl in range(3): xpos1 = LXPosStart ypos1 = LYPosStart - 0.05 + confl * LYStepFactor xpos2 = LXPosEnd ypos2 = ypos1 (xbm, ybm) = map(xpos1, ypos1) (xm, ym) = map(xpos2, ypos2) if (n_subgr == 1 or n_subgr == 8): arr = ptch.FancyArrow(xbm, ybm, xm - xbm, ym - ybm, width=scale * (confl + 1), length_includes_head=True, facecolor='g', edgecolor='black', zorder=100) else: arr = ptch.FancyArrow(xbm, ybm, xm - xbm, ym - ybm, width=scale * (confl + 1), length_includes_head=True, facecolor='b', edgecolor='black', zorder=100) ax.add_patch(arr) xpos3 = LXPosCircleStart ypos3 = LYPosCircleStart + confl * LYStepFactor radius = radii * ((confl + 1.) / 3.) #radius = radii * float(confl+1) / 4 if (n_subgr == 1 or n_subgr == 8): map.tissot(xpos3, ypos3, radius, 100, edgecolor='black', facecolor='g', linewidth=1, zorder=100) else: map.tissot(xpos3, ypos3, radius, 100, edgecolor='black', facecolor='b', linewidth=1, zorder=100) xtext = LXPosTextStart ytext = LYPosTextStart + confl * LYStepFactor (xt, yt) = map(xtext, ytext) att = plt.text(xt, yt, confText[confl], fontsize=14, fontweight='normal', ha='left', va='center', color='k', zorder=100) ax.add_artist(att) lats = [ ypos1 + LYStepFactor, ypos1 + LYStepFactor, LYPosStart - LYStepFactor, LYPosStart - LYStepFactor ] lons = [ LXPosStart + LYStepFactor, LXPosTextStart - LYStepFactor * 3, LXPosTextStart - LYStepFactor * 3, LXPosStart + LYStepFactor ] x, y = map(lons, lats) xy = zip(x, y) poly = ptch.Polygon(xy, facecolor='white', edgecolor='k', zorder=99) ax.add_patch(poly) xtext = LXPosStart ytext = LYPosTextStart - LYStepFactor * 0.6 (xt, yt) = map(xtext, ytext) att = plt.text(xt, yt, 'Probability of transition:', fontsize=14, fontweight='normal', ha='left', va='center', color='k', zorder=101) ax.add_artist(att) ## Gargano (xt, yt) = map(15.35, 41.70) att = plt.text(xt, yt, 'Gargano', fontsize=14, fontweight='normal', ha='left', va='center', color='k', zorder=101, rotation=30) ax.add_artist(att) ## Capitals ## Rome 41°54′N 12°30′E (xt, yt) = map(12.5, 41.9 + 0.02) map.tissot(12.5, 41.9, 0.02, 100, edgecolor='black', facecolor='black', linewidth=1, zorder=101) att = plt.text(xt, yt, 'Rome', fontsize=12, fontweight='normal', ha='center', va='bottom', color='k', zorder=101) ax.add_artist(att) ## Zagreb 45°49′0″N 15°59′0″E (xt, yt) = map(15.983, 45.817 + 0.02) map.tissot(15.983, 45.817, 0.02, 100, edgecolor='black', facecolor='black', linewidth=1, zorder=101) att = plt.text(xt, yt, 'Zagreb', fontsize=12, fontweight='normal', ha='center', va='bottom', color='k', zorder=101) ax.add_artist(att) ## Sarajevo 43°52′N 18°25′E (xt, yt) = map(18.417, 43.867 + 0.02) map.tissot(18.417, 43.867, 0.02, 100, edgecolor='black', facecolor='black', linewidth=1, zorder=101) att = plt.text(xt, yt, 'Sarajevo', fontsize=12, fontweight='normal', ha='center', va='bottom', color='k', zorder=101) ax.add_artist(att) ## Podgorica 42°26′28.63″N 19°15′46.41″E xcc = 19 + 15. / 60 + 46.41 / 3600 ycc = 42 + 26. / 60 + 28.63 / 3600 (xt, yt) = map(xcc, ycc + 0.02) map.tissot(xcc, ycc, 0.02, 100, edgecolor='black', facecolor='black', linewidth=1, zorder=101) att = plt.text(xt, yt, 'Podgorica', fontsize=12, fontweight='normal', ha='center', va='bottom', color='k', zorder=101) ax.add_artist(att) ## Tirana 41°19′44″N 19°49′04″E xcc = 19 + 49. / 60 + 4. / 3600 ycc = 41 + 19. / 60 + 44 / 3600 (xt, yt) = map(xcc, ycc + 0.02) map.tissot(xcc, ycc, 0.02, 100, edgecolor='black', facecolor='black', linewidth=1, zorder=101) att = plt.text(xt, yt, 'Tirana', fontsize=12, fontweight='normal', ha='center', va='bottom', color='k', zorder=101) ax.add_artist(att) ## Sea names ## Adriatic Sea (xt, yt) = map(16, 42.3) att = plt.text(xt, yt, 'Adriatic Sea', fontsize=14, bbox=dict(boxstyle="square", ec='black', fc='white'), fontweight='normal', ha='left', va='center', color='k', zorder=1100, rotation=-30) ax.add_artist(att) ## Tyrrhenian Sea (xt, yt) = map(12.2, 41) att = plt.text(xt, yt, 'Tyrrhenian Sea', fontsize=14, bbox=dict(boxstyle="square", ec='black', fc='white'), fontweight='normal', ha='left', va='center', color='k', zorder=101, rotation=0) ax.add_artist(att) ## map scale map.drawmapscale(12.71, 40.3, lon0=0, lat0=0, length=100, barstyle='fancy', units='km', fontsize=9, yoffset=None, labelstyle='simple', fontcolor='k', fillcolor1='w', fillcolor2='k', ax=None, format='%d', zorder=None, linecolor=None, linewidth=None) ## annotate projection (xt, yt) = map(12.2, 39.8) att = plt.text(xt, yt, 'Mercator Projection', fontsize=10, bbox=dict(boxstyle="square", ec='black', fc='white'), fontweight='normal', ha='left', va='center', color='k', zorder=101, rotation=0) ax.add_artist(att) ## 8-subgraphs - red circles and labels fo convergences / divergences fout.close() return
from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt # setup south polar lambert azimuthal basemap. # The longitude lon_0 is at 6-o'clock, and the # latitude circle boundinglat is tangent to the edge # of the map at lon_0. m = Basemap(projection="splaea", boundinglat=-10, lon_0=90, resolution="l") m.drawcoastlines() m.fillcontinents(color="coral", lake_color="aqua") # draw parallels and meridians. m.drawparallels(np.arange(-80.0, 81.0, 20.0)) m.drawmeridians(np.arange(-180.0, 181.0, 20.0)) m.drawmapboundary(fill_color="aqua") # draw tissot's indicatrix to show distortion. ax = plt.gca() for y in np.linspace(19 * m.ymin / 20, m.ymin / 20, 10): for x in np.linspace(19 * m.xmin / 20, m.xmin / 20, 10): lon, lat = m(x, y, inverse=True) poly = m.tissot(lon, lat, 2.5, 100, facecolor="green", zorder=10, alpha=0.5) plt.title("South Polar Lambert Azimuthal Projection") plt.show()
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt map = Basemap(projection='merc', lat_0=0, lon_0=0, llcrnrlon=-180.,llcrnrlat=-80.,urcrnrlon=180.,urcrnrlat=80.,) map.drawmapboundary(fill_color='aqua') map.fillcontinents(color='coral',lake_color='aqua') map.drawcoastlines() for lon in range(-160, 180, 30): for lat in range(-60, 90, 30): map.tissot(lon, lat, 4, 50) plt.show()
#-------------------------------------------------- # from mpl_toolkits.basemap import Basemap # import matplotlib.pyplot as plt ar = np.arange enlarge = [1,2,4,8,16,32] w_list = [15000000./(i) for i in enlarge] h_list = [9000000./(i) for i in enlarge] xlim_min = [-142, 80, 120, 135, 139] xlim_max = [ 192, 160, 150, 142, 141] ylim_min = [ -45, 0, 20, 33, 35] ylim_max = [ 75, 50, 50, 37, 36.2] ss = [ 0.7, 0.3, 0.1, 0.03, 0.005] for i, s in zip(ar(len(xlim_min)),ss): m = Basemap(projection='merc',llcrnrlat=ylim_min[i] ,urcrnrlat=ylim_max[i] ,\ llcrnrlon=xlim_min[i],urcrnrlon=xlim_max[i] ,lat_ts=20, resolution='c') plt.figure(figsize=(13,13)) m.plot(lon,lat,'ro') m.bluemarble() for x, y in zip(lon,lat): m.tissot(x, y, s,100,facecolor='red',zorder=100,alpha=0.4) plt.show() plt.savefig('plot_map_%s.png'%(str(i)))
def beholder_plot_map(file, channels=[], mounts=[], interests=[], size=600, time=None, status=None, extra=None): # SAO location obs = ephem.Observer() obs.lat = deg2rad(43.65722222) obs.lon = deg2rad(41.43235417) obs.elevation = 2065 obs.pressure = 0.0 if time: obs.date = time # Current zenith position z = obs.radec_of(0, 90) st = rad2deg(z[0]) # stellar time in degrees fig = Figure(facecolor='white', dpi=72, figsize=(size/72, size/72), tight_layout=True) ax = fig.add_subplot(111) # set up orthographic map projection map = Basemap(projection='ortho', lat_0 = rad2deg(obs.lat), lon_0 = -st, resolution = None, celestial = True, ax = ax) # draw the edge of the map projection region (the projection limb) map.drawmapboundary() # draw and label ra/dec grid lines every 30 degrees. degtoralabel = lambda deg : "$%d^h$" % int(deg/15) degtodeclabel = lambda deg : "%+d$^\circ$" % deg map.drawparallels(np.arange(-90, 90, 30), color='lightgray')#, fmt=degtodeclabel) map.drawmeridians(np.arange(0, 360, 45), color='lightgray') for h in [0,3,6,9,12,15,18,21]: try: x,y = map(h*15,0) if abs(x) < 1e10 and abs(y) < 1e10: ax.text(x,y, degtoralabel(h*15), color='black') except: pass # Place stars star_size = [10*(10**(-0.4*v)) for v in tycho2['v']] px, py = map(tycho2['ra'], tycho2['dec']) map.scatter(px, py, s=star_size, c='gray') # Sun s = ephem.Sun() s.compute(obs) px, py = map(rad2deg(s.ra), rad2deg(s.dec)) if abs(px) < 1e10 and abs(py) < 1e10: map.scatter(px, py, s=2000, c='lightgray', marker='o') ax.text(px, py, "Sun", color='black', va='center', ha='center') # Moon m = ephem.Moon() m.compute(obs) px, py = map(rad2deg(m.ra), rad2deg(m.dec)) if abs(px) < 1e10 and abs(py) < 1e10: map.scatter(px, py, s=1200, c='lightgray', marker='o') ax.text(px, py, "Moon", color='black', va='center', ha='center') # Directions of interest for interest in interests: px, py = map(float(interest['ra']), float(interest['dec'])) if abs(px) < 1e10 and abs(py) < 1e10: map.scatter(px, py, marker=interest.get('marker', 'o'), s=float(interest.get('size', 2000)), alpha=float(interest.get('alpha', 0.1)), color=interest.get('color', 'gray')) ax.text(px, py, interest.get('name', ''), color=interest.get('color', 'gray'), va=interest.get('va', 'center'), ha=interest.get('ha', 'center')) # Draw mounts mp = None for mount in mounts: px, py = map(float(mount['ra']), float(mount['dec'])) if abs(px) < 1e10 and abs(py) < 1e10: mp = map.scatter(px, py, marker='o', s=300, alpha=0.5, color='blue') ax.text(px, py, "%d" % (int(mount['id'])), color='black', va='center', ha='center') # Channels cp = None for channel in channels: px, py = map(float(channel['ra']), float(channel['dec'])) if abs(px) < 1e10 and abs(py) < 1e10: if channel.has_key('ra1'): px1, py1 = map(float(channel['ra1']), float(channel['dec1'])) px2, py2 = map(float(channel['ra2']), float(channel['dec2'])) px3, py3 = map(float(channel['ra3']), float(channel['dec3'])) px4, py4 = map(float(channel['ra4']), float(channel['dec4'])) map.plot([px1, px2, px3, px4, px1], [py1, py2, py3, py4, py1], ':', color='red') cp = map.scatter(px, py, marker='s', s=200, alpha=0.5, color='red') ax.text(px, py, "%d" % (int(channel['id'])), color='black', va='center', ha='center') # Title etc ax.set_title("%s UT, Sidereal %s" % (obs.date, (ephem.hours(deg2rad(st))))) if status: text = 'Night\n' if status['is_night'] == '1' else 'Daytime\n' text += 'Zsun: %.2f\n' % (float(status['scheduler_zsun'])) text += 'Zmoon: %.2f' % (float(status['scheduler_zmoon'])) fig.text(0, 0, text, va='bottom') text = 'Weather Good\n' if status['is_weather_good'] == '1' else 'Weather Bad\n' if status.has_key('weather_cloud_cond'): text += '%s: %.1f\n' % ({0:"Clouds Unknown", 1:"Clear", 2:"Cloudy", 3:"Very Cloudy"}.get(int(status['weather_cloud_cond']), 0), float(status['weather_sky_ambient_temp'])) text += 'Temperature: %.1f\n' % float(status['weather_ambient_temp']) text += '%s: %.1f m/s\n' % ({0:"Wind Unknown", 1:"Calm", 2:"Windy", 3:"Very Windy"}.get(int(status['weather_wind_cond']), 0), float(status['weather_wind'])) text += 'Humidity: %.0f%%\n' % float(status['weather_humidity']) text += '%s\n' % ({0:"Rain Unknown", 1:"Dry", 2:"Wet", 3:"Rain"}.get(int(status['weather_rain_cond']), 0)) fig.text(1, 0.95, text, ha='right', va='top') text = 'State: %s\n' % status['state'] if status.has_key('dome_state'): text += 'Dome: %s\n' % ({0:"Closed", 1:"Opening", 2:"Closing", 3:"Open"}.get(int(status['dome_state']), 'Unknown')) if status.has_key('can_nchillers'): chillers = False for id in xrange(int(status['can_nchillers'])): if status['can_chiller'+str(id+1)+'_state'] == '0': chillers = True text += 'Chillers: ' + ('On' if chillers else 'Off') + '\n' ncameras_on = 0 nchannels_open = 0 for id in xrange(int(status['nchannels'])): if not status.has_key('channel'+str(id+1)+'_hw_camera'): continue if status['channel'+str(id+1)+'_hw_camera'] == '1': ncameras_on += 1 if status['channel'+str(id+1)+'_hw_cover'] == '1': nchannels_open += 1 text += 'Cameras: ' if ncameras_on == 0: text += 'Off\n' elif ncameras_on == int(status['nchannels']): text += 'On\n' else: text += '%d/%d On\n' % (ncameras_on, int(status['nchannels'])) text += 'Covers: ' if nchannels_open == 0: text += 'Closed\n' elif nchannels_open == int(status['nchannels']): text += 'Open\n' else: text += '%d/%d Open\n' % (nchannels_open, int(status['nchannels'])) fig.text(0, 0.95, text, va='top') for i in xrange(int(status['nchannels'])): if not status.has_key('channel'+str(i+1)+'_state'): continue x, y = i%3, np.floor(i/3) state = {0:"Normal", 1:"Darks", 2:"Autofocus", 3:"Monitoring", 4:"Follow-up", 5:"Flats", 6:"Locate", 7:"Reset", 8:"Calibrate", 9:"Imaging", 100:"Error"}.get(int(status['channel%d_state' % (i+1)]), 100) text = state fig.text(0.84 + 0.08*x, 0.06-0.03*y, text, ha='right', backgroundcolor='white') # if cp or mp: # fig.legend([cp, mp], ["Channels", "Mounts"], loc=4).draw_frame(False) if extra: for e in extra: if e['type'] == 'circle' and e.has_key('ra') and e.has_key('dec'): map.tissot(float(e['ra']), float(e['dec']), float(e.get('sr', 1.0)), 50, fc='none', color=e.get('color', 'red'), lw=float(e.get('lw', 1.0))) if e.has_key('name'): px, py = map(float(e['ra']), float(e['dec'])) if abs(px) < 1e10 and abs(py) < 1e10: ax.text(px, py, e.get('name', ''), color=e.get('color', 'gray'), va=e.get('va', 'center'), ha=e.get('ha', 'center')) # Return the image canvas = FigureCanvas(fig) canvas.print_png(file, bbox_inches='tight')
class GlobeMap: def __init__(self,ax, lat=50, lon=-100): # set up orthographic map projection with # perspective of satellite looking down at 50N, 100W. # use low resolution coastlines. # don't plot features that are smaller than 1000 square km. self.ax = ax self.dispSize = 2. # twice bigger than actual size self.map = Basemap(projection='ortho', lat_0 = lat, lon_0 = lon, resolution = 'l', area_thresh = 1000., ax=ax) def drawGlobe(self,grid=10, gridopt=True): # draw coastlines, country boundaries, fill continents. self.map.drawcoastlines(ax=self.ax) self.map.drawcountries(ax=self.ax) #self.map.fillcontinents(color = 'green') #self.map.drawmapboundary() #self.map.drawlsmask(land_color='#FFFFCC', ocean_color='#6699FF', lakes=True, ax=self.ax) self.map.drawlsmask(land_color='yellowgreen', ocean_color='#CCFFFF', lakes=True, ax=self.ax) # draw the edge of the self.map projection region (the projection limb) # draw lat/lon grid lines every 2 degrees. if gridopt: self.map.drawmeridians(np.arange(0, 360, grid),ax=self.ax) self.map.drawparallels(np.arange(-90, 90, grid),ax=self.ax) plt.draw() def drawSatellite(self): self.map.bluemarble() plt.draw() def drawHurricanes(self,hurricanes): # lat/lon coordinates lats = list(hurricanes[:,0]) lons = list(hurricanes[:,1]) # compute the native self.map projection coordinates for cities. x,y = self.map(lons,lats) # by __call__ function definition # take the positions on the backside of globe display out subidx = 0 for i in xrange(len(x)): if x[i-subidx] >1e20 or y[i-subidx] > 1e20: x.pop(i-subidx) y.pop(i-subidx) subidx = subidx + 1 # plot filled circles at the locations of the cities. self.map.plot(x,y,'ro', markersize=5*self.dispSize) plt.draw() def fillGrids(self,gridsCoord): for grid in gridsCoord: #self.map.drawgreatcircle(grid[1],grid[0],grid[3],grid[2]) x, y = self.map([grid[1],grid[3]], [grid[0],grid[2]]) if 1e30 in x or 1e30 in y: continue self.map.tissot((grid[1]+grid[3])/2., (grid[0]+grid[2])/2., (grid[3]-grid[1])*self.dispSize/2., 100) plt.draw()
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt map = Basemap( projection='merc', lat_0=0, lon_0=0, llcrnrlon=-180., llcrnrlat=-80., urcrnrlon=180., urcrnrlat=80., ) map.drawmapboundary(fill_color='aqua') map.fillcontinents(color='coral', lake_color='aqua') map.drawcoastlines() for lon in range(-160, 180, 30): for lat in range(-60, 90, 30): map.tissot(lon, lat, 4, 50) plt.show()
#lats=mn_biomass["latitude"].tolist() # creating list from column biomass_list = mn_biomass["integrated_biomass"].tolist( ) # creating list from column # setting the factor to to have the size fractioning visualization of biomass over the map factor = 200000 # changeable depending on size biomass = np.divide( biomass_list, factor) # quotient determine the size of the visual represntation # creating the map using tissot (representation of a circle on the map) iterator = range(0, len(biomass_list)) for i in iterator: # tissot can not be used on lists, need to loop through map.tissot(lons[i], lats[i], biomass[i], 20, edgecolor='k', facecolor='b', alpha=1) # creating legends for the size fractioning of the biomass circles on the map fac_list = [0.3, 0.2, 0.1, 0.04] # quotient for size of visual representation lat_list = [-12, -12.7, -13.2, -13.6] # latitudinal position of the legends lon = -74 # logitudinal position of the legends label_list = ["60000 µgCm⁻²", "40000 µgCm⁻²", "20000 µgCm⁻²", "8000 µgCm⁻²"] # text in the legends for i in range(0, len(label_list)): # iterating ove the label list map.tissot(-74.9, lat_list[i], fac_list[i], 20,
ax = fig.add_subplot(2, 2, 1) m = Basemap(llcrnrlon=-176, llcrnrlat=8, urcrnrlon=-156, urcrnrlat=28, resolution='h') m.drawmapboundary(fill_color='#7777ff') m.fillcontinents(color='#ddaa66', lake_color='#7777ff', zorder=0) m.drawcoastlines() # Location of ULVZ x0, y0 = -167.5, 17.5 R = 7.5 m.tissot(x0, y0, R, 100, facecolor='g', alpha=0.2) cm = plt.cm.get_cmap('jet') # Plot background from the cluster analysis of Cottaar &Lekic 2016 if plot_background: LMC = LMClust_g6_ryb.LMClust() LMC.read('/raid2/sc845/Tomographic_models/LMClust/', 'clustgr.txt') lon, lat, layer = LMC.get_slice(depth_background) x, y = m(lon.ravel(), lat.ravel()) x = x.reshape(np.shape(layer)) y = y.reshape(np.shape(layer)) minval = np.min(np.min(layer)) maxval = np.max(np.max(layer)) + .1 m.pcolor(x, y, layer, cmap=LMC.rgb_map_light, linewidth=0, rasterized=True)
def tissot(self, lon_0, lat_0, radius_deg, npts, ax=None, **kwargs): """ Draw a polygon centered at ``lon_0,lat_0``. The polygon approximates a circle on the surface of the earth with radius ``radius_deg`` degrees latitude along longitude ``lon_0``, made up of ``npts`` vertices. The polygon represents a Tissot's indicatrix (http://en.wikipedia.org/wiki/Tissot's_Indicatrix), which when drawn on a map shows the distortion inherent in the map projection. Tissots can be used to display azimuthally symmetric directional uncertainties ("error circles"). Extra keyword ``ax`` can be used to override the default axis instance. Other \**kwargs passed on to matplotlib.patches.Polygon. :return: a list of matplotlib.patches.Polygon objects, with two polygons when the tissot crosses the limb, and just one polygon otherwise. """ # only use modified version if we are in a critical region if (((self.east_hem(lon_0) and self.east_hem(lon_0 + radius_deg + 7)) or (not self.east_hem(lon_0) and not self.east_hem(lon_0 - radius_deg - 7))) and abs(lat_0) + radius_deg < 90): return Basemap.tissot(self, lon_0, lat_0, radius_deg, npts, ax=None, **kwargs) # TODO: Just return the polygon (not a list) when there is only one # polygon? Or stick with the list for consistency? # This is based on Basemap.tissot, but addresses a limitation of that # method by handling tissots that cross the limb of the map by finding # separate polygons in the eastern and western hemispheres comprising # the tissot. ax = kwargs.pop('ax', None) or self._check_ax() g = pyproj.Geod(a=self.rmajor, b=self.rminor) try: az12, az21, dist = g.inv(lon_0, lat_0, lon_0, lat_0 + radius_deg) except ValueError: print('WARNING:' 'Error plotting coords', '[' + str(lon_0), str(lat_0) + ']', 'with radius', radius_deg) return start_hem = self.east_hem(lon_0) segs1 = [self(lon_0, lat_0 + radius_deg)] over, segs2 = [], [] delaz = 360. / npts az = az12 last_lon = lon_0 # handling of the poles if (abs(lat_0) + radius_deg >= 90): # Use half of the points for the part inside the map, the # other half of the points is at the map border lats = zeros(int(npts / 2)) lons = zeros(int(npts / 2)) for n in range(int(npts / 2)): az = az + delaz * 2 lon, lat, az21 = g.fwd(lon_0, lat_0, az, dist) lons[n] = lon lats[n] = lat a = list(argsort(lons)) lons = lons[a] lats = lats[a] x1, y1 = self(lons, lats) # Half of the remaining points are used on eastern and # western hemisphere. N = int(npts / 4) segs = [] dL = (90 - abs(lats[0])) / (N - 1) r = range(N) # For the south-pole the order of points is changed to plot # the correct polygon if lat_0 < 0: r = list(reversed(r)) segs.extend(zip(x1, y1)) #First Half of the map border x, y = self(-180 * sign(lat_0) * ones(N), sign(lat_0) * (90 - array(r) * dL)) segs.extend(zip(x, y)) if lat_0 > 0: segs.extend(zip(x1, y1)) #Second half of the map border r = list(reversed(r)) x, y = self(180 * sign(lat_0) * ones(N), sign(lat_0) * (90 - array(r) * dL)) segs.extend(zip(x, y)) #z = array(segs) #self.plot(z[:,0], z[:,1]) poly = Polygon(segs, **kwargs) ax.add_patch(poly) return [poly] # Note adjacent and opposite edge longitudes, in case the tissot # runs over the edge. if start_hem: # eastern case adj_lon = self.east_lon opp_lon = self.west_lon else: adj_lon = self.west_lon opp_lon = self.east_lon for n in range(npts): az = az + delaz # skip segments along equator (Geod can't handle equatorial arcs) if np.allclose(0., lat_0) and (np.allclose(90., az) or np.allclose(270., az)): continue else: lon, lat, az21 = g.fwd(lon_0, lat_0, az, dist) # If in the starting hemisphere, add to 1st polygon seg list. if self.east_hem(lon) == start_hem: x, y = self(lon, lat) # Add segment if it is in the map projection region. if x < 1.e20 and y < 1.e20: segs1.append((x, y)) last_lon = lon # Otherwise, we cross hemispheres. else: # Trace the edge of each hemisphere. x, y = self(adj_lon, lat) if x < 1.e20 and y < 1.e20: segs1.append((x, y)) # We presume if adj projection is okay, opposite is. segs2.append(self(opp_lon, lat)) # Also store the overlap in the opposite hemisphere. x, y = self(lon, lat) if x < 1.e20 and y < 1.e20: over.append((x, y)) last_lon = lon poly1 = Polygon(segs1, **kwargs) ax.add_patch(poly1) if segs2: over.reverse() segs2.extend(over) poly2 = Polygon(segs2, **kwargs) ax.add_patch(poly2) return [poly1, poly2] else: return [poly1]
def plotme(clat,clon,slat,slon,cat,cat_subset,st_minradius,st_maxradius,sta_dir): # plot basemap #map = Basemap(projection='ortho',lat_0=clat,lon_0=clon,resolution='l') # Orthographic Projection map = Basemap(projection='aeqd',lat_0=clat,lon_0=clon,resolution='c') # Azimuthal Equidistant Projection map.drawcoastlines(linewidth=0.25) map.drawcoastlines(linewidth=0.25) map.drawcountries(linewidth=0.25) map.fillcontinents(color='coral',lake_color='aqua') # draw the edge of the map projection region (the projection limb) map.drawmapboundary(fill_color='aqua') # draw lat/lon grid lines every 30 degrees. #map.drawmeridians(np.arange(0,360,30)) #map.drawparallels(np.arange(-90,90,30)) # Plot center of Alaska and station markersize = 7 x,y = map(clon,clat) # convert lon-lat to map cooridates map.plot(x,y,'b*', markersize=markersize) # plot center x,y = map(slon,slat) map.plot(x,y,'rv', markersize=markersize) # plot station plt.title(sta_dir + ' - event selection plot') # Plot circle for event selection # tissot should ideally make circle BUT there is a bug when longitude change from -179 to +179 # plot circle around the center of Alaska npts = 250 xy=[] poly = map.tissot(clon, clat, st_minradius,npts,edgecolor='none',facecolor='none') xy = poly.xy circle_lon = xy.T.tolist()[0] circle_lat = xy.T.tolist()[1] poly = map.tissot(clon, clat, st_maxradius,npts,edgecolor='none',facecolor='none') xy = poly.xy circle_lon = circle_lon + xy.T.tolist()[0] circle_lat = circle_lat + xy.T.tolist()[1] map.plot(circle_lon,circle_lat,'bo', markersize=2) # plot circle around the station poly = map.tissot(slon, slat, st_minradius,npts,edgecolor='none',facecolor='none') xy = poly.xy circle_lon = xy.T.tolist()[0] circle_lat = xy.T.tolist()[1] poly = map.tissot(slon, slat, st_maxradius,npts,edgecolor='none',facecolor='none') xy = poly.xy circle_lon = circle_lon + xy.T.tolist()[0] circle_lat = circle_lat + xy.T.tolist()[1] map.plot(circle_lon,circle_lat,'ro', markersize=2) # Plot All events (cat) and selected events (cat_subset) x1,x2,y1,y2=[],[],[],[] for ii in range(0,len(cat)): x1.append(cat[ii].origins[0].longitude) y1.append(cat[ii].origins[0].latitude) for ii in range(0,len(cat_subset)): x2.append(cat_subset[ii].origins[0].longitude) y2.append(cat_subset[ii].origins[0].latitude) x,y = map(x1,y1) map.plot(x,y,'bo', markersize=markersize) x,y = map(x2,y2) map.plot(x,y,'ro', markersize=markersize) # Plot and save figure # plt.show() fname = './sks_events/' + sta_dir + '_event_selection.eps' plt.savefig(fname) plt.clf()
#project into equal area coordinate system m.drawcoastlines() m.drawcountries() m.fillcontinents(color='brown', lake_color='blue') m.drawparallels(np.arange(33, 38, 1)) m.drawmeridians(np.arange(-100, -92, 2)) m.drawmapboundary(fill_color='blue') ax = plt.gca() for y in np.linspace(m.ymax / 2, 19 * m.ymax / 2, 10): for x in np.linspace(m.xmax / 1, 19 * m.xmax / 1, 12): lon, lat = m(x, y, inverse=True) poly = m.tissot(lon, lat, 2, 100, facecolor='green', zorder=5, alpha=0.5) plt.show() def eq_rate(at, k_win): aS = np.arange(0, at.shape[0] - k_win, 1) aBin, aRate = np.zeros(aS.shape[0]), np.zeros(aS.shape[0]) iS = 0 for s in aS: i1, i2 = s, s + k_win aBin[iS] = (at[i1] + at[i2]) / 2 aRate[iS] = k_win / (at[i2] - at[i1])
from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt # setup stereographic basemap. # lat_ts is latitude of true scale. # lon_0,lat_0 is central point. m = Basemap(width=12000000,height=8000000, resolution='l',projection='stere',\ lat_ts=50,lat_0=50,lon_0=-107.) m.drawcoastlines() m.fillcontinents(color='coral',lake_color='aqua') # draw parallels and meridians. m.drawparallels(np.arange(-80.,81.,20.)) m.drawmeridians(np.arange(-180.,181.,20.)) m.drawmapboundary(fill_color='aqua') # draw tissot's indicatrix to show distortion. ax = plt.gca() for y in np.linspace(m.ymax/20,19*m.ymax/20,9): for x in np.linspace(m.xmax/20,19*m.xmax/20,12): lon, lat = m(x,y,inverse=True) poly = m.tissot(lon,lat,1.5,100,\ facecolor='green',zorder=10,alpha=0.5) plt.title("Stereographic Projection") plt.savefig('stere.png')
def plotskymap(fig, theta, phi, logp, gpstime, arrival_times=None, inj_lon_lat=None): """Draw a skymap as produced by the lal_skymap element. arrival_times should be a dictionary with keys being IFO names (e.g. 'H1', 'L1', 'V1', ...) and values being double precision GPS arrival at each IFO. If inj_lon_at is set to a celestial Dec/RA tuple in radians, then the injection point of origin will be marked with a cross. Currently, lal_skymap generates a grid of 450x900 points, and this code relies on that. It could be generalized to handle any rectangular grid, but the pcolormesh method that is used here is really only finally tuned for quadrilateral meshes. """ # Some imports that are only useful for this function from math import atan2, acos, asin, degrees, sqrt, pi from mpl_toolkits.basemap import Basemap, shiftgrid import numpy as np import lal import lalsimulation # Some useful functions def location_for_site(prefix): """Get the Cartesian (WGS84) coordinates of a site, given its prefix (H1 for Hanford, L1 for Livingston...).""" return lalsimulation.DetectorPrefixToLALDetector(prefix).location def cart2spherical(cart): """Convert a Cartesian vector to spherical polar azimuth (phi) and elevation (theta) in radians.""" return atan2(cart[1], cart[0]), acos(cart[2] / sqrt(np.dot(cart, cart))) def spherical2latlon(spherical): """Converts spherical polar coordinates in radians to latitude, longitude in degrees.""" return degrees(spherical[0]), 90 - degrees(spherical[1]) # Get figure axes. ax = fig.gca() # Initialize map; draw gridlines and map boundary. m = Basemap(projection='moll', lon_0=0, lat_0=0, ax=ax) m.drawparallels(np.arange(-45, 46, 45), linewidth=0.5, labels=[1, 0, 0, 0], labelstyle="+/-") m.drawmeridians(np.arange(-180, 180, 90), linewidth=0.5) m.drawmapboundary() # lal_skymap outputs geographic coordinates; convert to celestial here. sidereal_time = np.mod( lal.GreenwichMeanSiderealTime(lal.LIGOTimeGPS(gpstime)) / lal.PI_180, 360) lons_grid = sidereal_time + phi.reshape(450, 900) / lal.PI_180 lats_grid = 90 - theta.reshape(450, 900) / lal.PI_180 logp_grid = logp.reshape(450, 900) # Rotate the coordinate grid; Basemap is too stupid to correctly handle a # scalar field that must wrap around the edge of the map. # FIXME: Find a mapping library that isn't a toy. gridshift = round(sidereal_time / 360) * 360 + 180 lats_grid, dummy = shiftgrid(gridshift, lats_grid, lons_grid[0, :], start=False) logp_grid, dummy = shiftgrid(gridshift, logp_grid, lons_grid[0, :], start=False) lons_grid, dummy = shiftgrid(gridshift, lons_grid, lons_grid[0, :], start=False) # Transform from longitude/latitude to selected projection. x, y = m(lons_grid, lats_grid) # Draw log probability distribution pc = m.pcolormesh(x, y, logp_grid, vmin=logp[np.isfinite(logp)].min()) cb = fig.colorbar(pc, shrink=0.5) cb.set_label('log relative probability') cb.cmap.set_under('1.0', alpha=1.0) cb.cmap.set_bad('1.0', alpha=1.0) # Draw mode of probability distribution maxidx = logp_grid.flatten().argmax() m.plot(x.flatten()[maxidx], y.flatten()[maxidx], '*', markerfacecolor='white', markersize=10) # Draw time delay loci, if arrival times were provided. if arrival_times is not None: for sites in itertools.combinations(arrival_times.keys(), 2): site0_location = location_for_site(sites[0]) site1_location = location_for_site(sites[1]) site_separation = site0_location - site1_location site_distance_seconds = sqrt( np.dot(site_separation, site_separation)) / lal.C_SI lon, lat = spherical2latlon(cart2spherical(site_separation)) site0_toa = arrival_times[sites[0]] site1_toa = arrival_times[sites[1]] radius = acos( (site1_toa - site0_toa) / site_distance_seconds) * 180 / pi # Sigh. Basemap is too stupid to be able to draw circles that wrap around # the dateline. We'll just grab the points it generated, and plot it as # a dense scatter point series. poly = m.tissot(lon + sidereal_time, lat, radius, 1000, facecolor='none') poly.remove() x, y = zip(*poly.xy) m.plot(x, y, ',k') # Draw injection point, if provided if inj_lon_lat is not None: inj_x, inj_y = m(degrees(inj_lon_lat[0]), degrees(inj_lon_lat[1])) m.plot(inj_x, inj_y, '+k', markersize=20, markeredgewidth=1) # Add labels ax.set_title('Candidate log probability distribution') ax.set_xlabel( 'RA/dec, J2000. White star marks the mode of the PDF.\nBlack lines represent time delay solution loci for each pair of detectors.', fontsize=10)