Beispiel #1
0
def plot_career(careerPath):
    title = getTitle(careerPath)
    plt.figure(figsize=(120,60))

    m = Basemap(resolution='c', # c, l, i, h, f or None
                projection='cyl',
                fix_aspect=True)
    plt.title(title, fontsize=120)

    # m.drawmapboundary(fill_color='#46bcec')
    m.drawcoastlines()#color='#f2f2f2',lake_color='#46bcec')
    m.drawcountries(antialiased=False)
    long = 0
    lat = 51
    output = io.StringIO()
    
    for _, entry in careerPath.iterrows():
        if np.isnan(entry.CapitalLongitude) or np.isnan(entry.CapitalLatitude):
            continue
        if np.isnan(entry.yearPostingStart):
            print_statement = entry.country+"\n"
            
        elif np.isnan(entry.yearPostingEnd):
            print_statement = entry.country + "({}-)".format(int(entry.yearPostingStart))+"\n"
        else:
            print_statement = entry.country + "({}-{})".format(int(entry.yearPostingStart), int(entry.yearPostingEnd))+"\n"
#         print(print_statement)
        output.write(entry.job+"\n")
        output.write(print_statement)
        output.write("\n")
        m.drawgreatcircle(long,lat, entry.CapitalLongitude,entry.CapitalLatitude, del_s =1, lw=20)
        long, lat = entry.CapitalLongitude,entry.CapitalLatitude
    plt.text(x=-170, y=-80, s= output.getvalue(), fontsize=120)
    print(output.getvalue())
    plt.savefig("paths/"+title+".pdf")
Beispiel #2
0
def generate_map(output, lats=[], lons=[], wesn=None):
    """
    creates a traffic map for a specific experiment
    :param output:
    :param lats:
    :param lons:
    :param wesn:
    :return:
    """
    "see http://matplotlib.org/basemap/users/examples.html"
    m = Basemap(llcrnrlon=-180., llcrnrlat=-60., urcrnrlon=190., urcrnrlat=80., \
                rsphere=(6378137.00, 6356752.3142), \
                resolution='l', projection='merc', \
                lat_0=40., lon_0=-20., lat_ts=20.)

    for i in range(0, len(lats), 1):
        centerlat = 55.95
        centerlon = -3.2
        m.drawgreatcircle(lons[i],
                          lats[i],
                          centerlon,
                          centerlat,
                          linewidth=2,
                          color='b')

    m.drawcoastlines()
    m.fillcontinents()
    m.drawparallels(np.arange(-60, 90, 20))
    m.drawmeridians(np.arange(-200, 200, 30))
    plt.savefig(output, dpi=300, bbox_inches='tight')
    plt.close()
Beispiel #3
0
def plot_lat_long(coords):
  
  starting_lat = coords[0][1].lat
  starting_lon = coords[0][1].long
  print "starting lat: %s\nstarting lon: %s\n" % (starting_lat, starting_lon)
  for coord in coords[1:]:
    lat = coord[1].lat
    lon = coord[1].long
    print "lat: %s\nlon: %s\n" % (lat, lon)
    m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,\
              llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='c')
    m.drawcoastlines()
    m.fillcontinents(color='coral',lake_color='aqua')

# draw parallels and meridians.
    m.drawparallels(np.arange(-90.,91.,30.))
    m.drawmeridians(np.arange(-180.,181.,60.))
    xpt, ypt =  m(lon, lat)
    m.plot(xpt, ypt, 'bo')
    lonlat = 51.53; lonlon = 0.08
    m.drawgreatcircle(starting_lon,starting_lat,lon,lat,linewidth=2,color='b')
    m.drawmapboundary(fill_color='aqua')
    plt.title("Blorp")
    plt.show()
    starting_lat = lat
    starting_lon = lon
    def plotOnMap(A,A1):
        x = np.zeros(len(A))
        y = np.zeros(len(A))
        name = []
        for i in range(0, len(A)):
            x[i] = HelpMethod.radTodeg(A[i].lat)
            y[i] = HelpMethod.radTodeg(A[i].lon)
            name.append(A[i].status1)
        fig = plt.figure()
        llcrnrlat=y[0] - 10
        llcrnrlon = x[0] - 10
        urcrnrlat = y[len(x) - 1] + 20
        urcrnrlon = x[len(y) - 1] + 20
        m = Basemap(llcrnrlat=llcrnrlat, llcrnrlon=llcrnrlon, urcrnrlat=urcrnrlat,
                    urcrnrlon=urcrnrlon)
        for i in range(1, len(x)):
            m.drawgreatcircle(x[i - 1], y[i - 1], x[i], y[i], color="red")
            i = +2
        m.drawcoastlines()
        m.fillcontinents()
        m.drawparallels(np.arange(0, 90, 10), labels=[1, 1, 0, 1])
        # draw meridians
        m.drawmeridians(np.arange(-180, 180, 10), labels=[1, 1, 0, 1])
        for i in range(0, len(x)):
            plt.text(x[i], y[i], name[i])


        plt.savefig(A1)
        plt.close(fig)
Beispiel #5
0
def main():

    connection = sl.connect(FLIGHTS_DB)

    query = """
    select cast(sa.longitude as float) as source_lon,
    cast(sa.latitude as float) as source_lat,
    cast(da.longitude as float) as dest_lon,
    cast(da.latitude as float) as dest_lat
    from routes
    inner join airports sa on sa.id = routes.source_id
    inner join airports da on da.id = routes.dest_id 
"""
    routes = pd.read_sql_query(query, connection)
    connection.close()

    myMap = Basemap(projection='merc',
                    llcrnrlat=-80,
                    urcrnrlat=80,
                    llcrnrlon=-180,
                    urcrnrlon=180,
                    lat_ts=20,
                    resolution='c')

    myMap.drawcoastlines()

    for name, row in routes[:3000].iterrows():
        if abs(row["source_lon"] - row["dest_lon"]) < 90:
            myMap.drawgreatcircle(row["source_lon"],
                                  row["source_lat"],
                                  row["dest_lon"],
                                  row["dest_lat"],
                                  linewidth=1,
                                  color='b')
Beispiel #6
0
def draw():

    xs = []
    ys = []

    m = Basemap(projection='mill',
                llcrnrlat=25,
                llcrnrlon=-130,
                urcrnrlat=50,
                urcrnrlon=-60,
                resolution='1')

    m.drawcoastlines()
    m.drawcountries(linewidth=2)
    m.drawstates(color='b')

    NYClat, NYClon = 40.7127, -74.0059
    xpt, ypt = m(NYClon, NYClat)
    xs.append(xpt)
    ys.append(ypt)
    m.plot(xpt, ypt, 'c*', markersize=15)

    LAlat, LAlon = 34.05, -118.25
    xpt, ypt = m(LAlon, LAlat)
    xs.append(xpt)
    ys.append(ypt)
    m.plot(xpt, ypt, 'g^', markersize=15)

    m.plot(xs, ys, color='r', linewidth=3, label='flight')
    m.drawgreatcircle(NYClon, NYClat, LAlon, LAlat, color='c', label='Arc')

    plt.legend(loc=4)

    plt.show()
Beispiel #7
0
 def addMap(self):
     plt.figure(num="QuarksrouteMap")
     m = Basemap(llcrnrlon=self.corners[0][0],
                 llcrnrlat=self.corners[0][1],
                 urcrnrlon=self.corners[1][0],
                 urcrnrlat=self.corners[1][1])
     m.drawmapboundary(fill_color='#A6CAE0', linewidth=0)
     m.fillcontinents(color='grey', alpha=0.6, lake_color='blue')
     m.drawcountries(color="white")
     m.drawcoastlines(linewidth=0.1, color="white")
     head = ()
     index = 0
     for hop in self.data["hops"]:
         if hop["geo"]:
             if head is not ():
                 m.drawgreatcircle(head[0],
                                   head[1],
                                   hop["geo"]["location"]["longitude"],
                                   hop["geo"]["location"]["latitude"],
                                   linewidth=2,
                                   color='blue')
             head = (hop["geo"]["location"]["longitude"],
                     hop["geo"]["location"]["latitude"])
             m.plot(head[0],
                    head[1],
                    linestyle='none',
                    marker="o",
                    markersize=8,
                    alpha=0.6,
                    c="cyan",
                    markeredgecolor="black",
                    markeredgewidth=1)
             plt.annotate(index, xy=(head[0], head[1] + 2))
             index = index + 1
Beispiel #8
0
def drawUSMap(chromosome, states, fname=None):
    "Draws a map of the United States of America. That is true."
    m = Basemap(llcrnrlon=-126,
                llcrnrlat=24,
                urcrnrlon=-67,
                urcrnrlat=50,
                resolution='c',
                projection='merc',
                lon_0=-95,
                lat_0=37)
    caplon = [x[3] for x in states]
    caplat = [x[2] for x in states]
    labels = [unicode(x[1], 'utf-8') for x in states]
    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()
    m.fillcontinents(color='coral', lake_color='aqua')
    m.drawmapboundary(fill_color='aqua')
    for i in range(len(caplon) - 1):
        nylon, nylat, lonlon, lonlat = caplon[chromosome[i]], caplat[
            chromosome[i]], caplon[chromosome[i + 1]], caplat[chromosome[i +
                                                                         1]]
        m.drawgreatcircle(nylon, nylat, lonlon, lonlat, linewidth=2, color='b')
    # Draw points on cities
    x, y = m(caplon, caplat)
    m.plot(x, y, 'bo', markersize=4)
    # Write city names
    for label, xpt, ypt in zip(labels, x, y):
        plt.text(xpt, ypt, label, fontsize=10)
    if fname == None:
        fname = 'US' + str(int(time.time()))
    plt.savefig('images/' + fname + '.svg', bbox_inches='tight')
Beispiel #9
0
 def draw(self, pop):
     fig=plt.figure()
     ax=fig.add_axes([0.1,0.1,0.8,0.8])
     m = Basemap(llcrnrlon=-125.,llcrnrlat=25.,urcrnrlon=-65.,urcrnrlat=52.,
                 rsphere=(6378137.00,6356752.3142),
                 resolution='l',projection='merc',
                 lat_0=40.,lon_0=-20.,lat_ts=20.)
     l = pop[0]          
     for i in range(len(l.sol)):
         lat1 = l.sol[i].lat
         lon1 = l.sol[i].lon
         m.drawgreatcircle(lon1,lat1,lon1,lat1, linewidth=4, color = 'r')
         if i == len(l.sol) - 1:
             lat2 = l.sol[0].lat
             lon2 = l.sol[0].lon
         else:
             lat2 = l.sol[i+1].lat
             lon2 = l.sol[i+1].lon
         m.drawgreatcircle(lon1,lat1,lon2,lat2, color = 'b')
     m.drawcoastlines()
     m.drawstates()
     m.drawcountries()
     m.fillcontinents()
     ax.set_title('GREEDY')
     plt.show()            
Beispiel #10
0
def map_trace(tr,ax='None',showpath=True,showplot=True,Lat_0=0.0,Lon_0=60.0):
   from mpl_toolkits.basemap import Basemap

   if ax == 'None':
       m = Basemap(projection='ortho',lat_0=Lat_0,lon_0=Lon_0,resolution='l')
       m.drawmapboundary()
       m.drawcoastlines()
       m.fillcontinents(color='gray',lake_color='white')
   else:
      m = ax

   x1,y1 = m(tr.stats.sac['evlo'],tr.stats.sac['evla'])
   x2,y2 = m(tr.stats.sac['stlo'],tr.stats.sac['stla'])
   m.scatter(x1,y1,s=200.0,marker='*',facecolors='y',edgecolors='k',zorder=99)
   m.scatter(x2,y2,s=20.0,marker='^',color='b',zorder=99)

   if showpath == True:
      m.drawgreatcircle(tr.stats.sac['evlo'],tr.stats.sac['evla'],
                        tr.stats.sac['stlo'],tr.stats.sac['stla'],
                        linewidth=1,color='k',alpha=0.5)

   if showplot == True:
      plt.show()
   else:
      return m
def show_flight(flight_info):
    m = Basemap(llcrnrlon=-180, llcrnrlat=-90, urcrnrlon=180, urcrnrlat=90, \
                projection='mill', resolution='c')
    m.shadedrelief()

    plt.show()

    m.drawcoastlines()
    # m.drawcounties(linewidth=2)
    m.drawstates(color='b')

    xs = []
    ys = []

    # Plot arrival points
    NYClat, NYClon = float(flight_info[1][0]), float(flight_info[1][1])
    xpt, ypt = m(NYClon, NYClat)
    xs.append(xpt)
    ys.append(ypt)
    m.plot(xpt, ypt, 'go', markersize=20)

    # Plot departure points
    LAlat, LAlon = float(flight_info[0][0]), float(flight_info[0][1])
    xpt, ypt = m(LAlon, LAlat)
    xs.append(xpt)
    ys.append(ypt)
    m.drawgreatcircle(NYClon, NYClat, LAlon, LAlat, linewidth=2, color='b')
    m.drawcoastlines()
    m.plot(xpt, ypt, 'r^', markersize=20)

    m.plot(xs, ys, color='y', linewidth=3, label='Flight 112')

    # Customization of plotted map and displaying it
    plt.title('Flight Map')
Beispiel #12
0
 def draw(self, pop):
     fig = plt.figure()
     ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
     m = Basemap(llcrnrlon=-125.,
                 llcrnrlat=25.,
                 urcrnrlon=-65.,
                 urcrnrlat=52.,
                 rsphere=(6378137.00, 6356752.3142),
                 resolution='l',
                 projection='merc',
                 lat_0=40.,
                 lon_0=-20.,
                 lat_ts=20.)
     l = pop[0]
     for i in range(len(l.sol)):
         lat1 = l.sol[i].lat
         lon1 = l.sol[i].lon
         m.drawgreatcircle(lon1, lat1, lon1, lat1, linewidth=4, color='r')
         if i == len(l.sol) - 1:
             lat2 = l.sol[0].lat
             lon2 = l.sol[0].lon
         else:
             lat2 = l.sol[i + 1].lat
             lon2 = l.sol[i + 1].lon
         m.drawgreatcircle(lon1, lat1, lon2, lat2, color='b')
     m.drawcoastlines()
     m.drawstates()
     m.drawcountries()
     m.fillcontinents()
     ax.set_title('GREEDY')
     plt.show()
Beispiel #13
0
  def plot_eq(self,ax='None',showpath=True,showplot=True,lon_0=0.0,lat_0=0.0):
     from mpl_toolkits.basemap import Basemap
     
     if ax == 'None':
         #m = Basemap(projection='hammer',lon_0=self.ry)
         m = Basemap(projection='ortho',lat_0=lat_0,lon_0=lon_0,resolution='l')
         m.drawmapboundary()
         m.drawcoastlines()
         m.fillcontinents(color='gray',lake_color='white')
     else:
         m = ax

     x1,y1 = m(self.sy,90.0-self.sx)
     x2,y2 = m(self.ry,90.0-self.rx)
     m.scatter(x1,y1,s=200.0,marker='*',facecolors='y',edgecolors='k',zorder=99)
     m.scatter(x2,y2,s=20.0,marker='^',color='b',zorder=99)
     
     if showpath == True:
        lon_s = self.sy
        lat_s = 90.0-self.sx
        lon_r = self.ry
        lat_r = 90.0-self.rx
        print "lon_s,lat_s,lon_r,lat_r", lon_s, lat_s, lon_r, lat_r
        m.drawgreatcircle(lon_s,lat_s,lon_r,lat_r,linewidth=1,color='k',alpha=0.5)

     if showplot == True:
        plt.show()
     else:
        return m
Beispiel #14
0
def draw(x1, x2, x3, x4):

    map = Basemap(projection='robin',
                  lat_0=0,
                  lon_0=0,
                  resolution='l',
                  area_thresh=1000.0)
    map.drawcoastlines()
    map.drawcountries()
    map.fillcontinents(color='coral', lake_color='aqua')
    map.drawmapboundary(fill_color='aqua')

    map.drawmeridians(np.arange(0, 360, 30))
    map.drawparallels(np.arange(-90, 90, 30))

    #initiate ocean and icecap colours
    #map.bluemarble()

    #draw a blob on the map
    x, y = map(x2, x1)
    map.plot(x, y, 'bo', markersize=10)

    x, y = map(x4, x3)
    map.plot(x, y, 'bd', markersize=10)

    map.drawgreatcircle(x2, x1, x4, x3, linewidth=2, color='b')

    plt.show()
Beispiel #15
0
def map_trace(tr,ax='None',showpath=True,showplot=True,Lat_0=0.0,Lon_0=60.0):
   from mpl_toolkits.basemap import Basemap

   if ax == 'None':
       m = Basemap(projection='ortho',lat_0=Lat_0,lon_0=Lon_0,resolution='l')
       m.drawmapboundary()
       m.drawcoastlines()
       m.fillcontinents(color='gray',lake_color='white')
   else:
      m = ax

   x1,y1 = m(tr.stats.sac['evlo'],tr.stats.sac['evla'])
   x2,y2 = m(tr.stats.sac['stlo'],tr.stats.sac['stla'])
   m.scatter(x1,y1,s=200.0,marker='*',facecolors='y',edgecolors='k',zorder=99)
   m.scatter(x2,y2,s=20.0,marker='^',color='b',zorder=99)

   if showpath == True:
      m.drawgreatcircle(tr.stats.sac['evlo'],tr.stats.sac['evla'],
                        tr.stats.sac['stlo'],tr.stats.sac['stla'],
                        linewidth=1,color='k',alpha=0.5)

   if showplot == True:
      plt.show()
   else:
      return m
def image_result(flightnum):
    #设置画布大小
    plt.figure(figsize=(8, 8))
    #画一幅中国地图
    map1 = Basemap(llcrnrlon=77, llcrnrlat=14, urcrnrlon=140, urcrnrlat=51)
    # map1 = Basemap(resolution = 'h' , llcrnrlon=73, llcrnrlat=18, urcrnrlon=135, urcrnrlat=53)
    #画出国家边界
    map1.drawcountries()
    #画出海岸线
    # map1.drawcoastlines()
    #画一幅NASA的bluemarble地图
    map1.bluemarble()
    #获取航班信息
    flight = flightaware(flightnum)
    #获得航班总共的信息条数
    z = len(flight)
    #导入函数
    # facheck= flightawareparser.fascrapper()
    facheck = fascrapper()
    #获得航班号对应的航班起始站点的信息
    details = facheck.flightdata(flightnum)
    #取整条航线上的四个点
    x1, y1 = map1(flight[1][1], flight[1][2])
    x2, y2 = map1(flight[int(z / 3)][1], flight[int(z / 3)][2])
    x3, y3 = map1(flight[int(2 * z / 3)][1], flight[int(2 * z / 3)][2])
    x4, y4 = map1(flight[z - 1][1], flight[z - 1][2])
    x = [x1, x2, x3, x4]
    y = [y1, y2, y3, y4]
    #画点
    map1.scatter(x, y, 270, marker='o', color='steelblue')
    #画线
    map1.drawgreatcircle(x1, y1, x2, y2, linewidth=2, color='lightblue')
    map1.drawgreatcircle(x2, y2, x3, y3, linewidth=2, color='lightblue')
    map1.drawgreatcircle(x3, y3, x4, y4, linewidth=2, color='lightblue')
    #备注文字
    plt.text(x1, y1, flight[1][0], rotation=0, fontsize=10, color='lawngreen')
    plt.text(x1, y1, details[2], rotation=30, fontsize=12, color='snow')
    plt.text(x2,
             y2,
             flight[int(z / 3)][0],
             rotation=0,
             fontsize=10,
             color='lawngreen')
    plt.text(x3,
             y3,
             flight[int(2 * z / 3)][0],
             rotation=0,
             fontsize=10,
             color='lawngreen')
    plt.text(x4,
             y4,
             flight[z - 1][0],
             rotation=0,
             fontsize=10,
             color='lawngreen')
    plt.text(x4, y4, details[3], rotation=30, fontsize=12, color='snow')
    #plt.text(x2, y2, '北京', rotation=30, fontsize=15, color='coral')
    plt.savefig('flight.png')
class GCMapper:
    def __init__(self):
        # create new figure, axes instances.
        self.fig = plt.figure()
        self.ax = self.fig.add_axes([0.1, 0.1, 0.8, 0.8], axisbg='#a5bfdd')

        # setup mercator map projection.
        self.map = Basemap(llcrnrlon=-130.,
                           llcrnrlat=1.,
                           urcrnrlon=40.,
                           urcrnrlat=70.,
                           rsphere=(6378137.00, 6356752.3142),
                           resolution='c',
                           projection='merc',
                           lat_0=40.,
                           lon_0=-20.,
                           lat_ts=20.)

    def plot(self, element):
        if isinstance(element, Segment):
            self.plot_segment(element)
        if isinstance(element, Route):
            self.plot_route(element)
        if isinstance(element, Point):
            self.plot_point(element)
        raise Exception('Incompatible type %s of element to plot' %
                        type(element))

    def plot_route(self, route, color='b', linestyle='-'):
        #just to be suer
        route.init_segments()
        for segment in route.segments:
            self.plot_segment(segment, color=color, linestyle=linestyle)

    def plot_point(self, point, formatting='go'):
        x, y = self.map(point.lon, point.lat)
        self.map.plot(x, y, formatting, ms=8)

    def plot_segment(self, segment, color='b', linestyle='-'):
        point1 = segment.start
        point2 = segment.end
        self.map.drawgreatcircle(point1.lon,
                                 point1.lat,
                                 point2.lon,
                                 point2.lat,
                                 linestyle=linestyle,
                                 linewidth=1.5,
                                 color=color)

    def render(self):
        self.map.drawcoastlines(color='#8f8457')
        self.map.fillcontinents(color='#f5f0db')
        self.map.drawcountries(color='#a9a06d')
        self.map.drawparallels(np.arange(10, 90, 20), labels=[1, 1, 0, 1])
        self.map.drawmeridians(np.arange(-180, 180, 30), labels=[1, 1, 0, 1])
        self.ax.set_title('Flights')
        plt.show()
Beispiel #18
0
    def plot_test(self, resolution=5):
        '''
        Show a plot of the earth and polygon with points tested for beeing inside.

        resolution : a positive number. The grid resolution in degrees for the test. 

        '''

        import matplotlib.pyplot as plt
        try:
            from mpl_toolkits.basemap import Basemap
        except Exception as e:
            print(e)
            raise ImportError(
                "This function requiers Basemap, please install and try again")

        lons, lats = np.meshgrid(np.arange(-180, 180.01, resolution),
                                 np.arange(-90, 90.01, resolution))
        points = np.asarray([lats.flatten(), lons.flatten()]).T

        points_in = self.contains_points(points, radians=False)

        fig, ax = plt.subplots(figsize=(10, 10))

        m = Basemap()

        plot_vertices = self.vertices_geo
        if self.radians:
            plot_vertices = np.rad2deg(self.vertices_geo)

        for i in range(len(plot_vertices) - 1):
            m.drawgreatcircle(plot_vertices[i][1],
                              plot_vertices[i][0],
                              plot_vertices[i + 1][1],
                              plot_vertices[i + 1][0],
                              c='b',
                              lw=3)
        m.drawgreatcircle(plot_vertices[i + 1][1],
                          plot_vertices[i + 1][0],
                          plot_vertices[0][1],
                          plot_vertices[0][0],
                          c='b',
                          lw=3)

        m.drawcoastlines()
        m.drawmeridians(np.arange(-180, 180, 10))
        m.drawparallels(np.arange(-90, 90, 10))

        for i, point in enumerate(points):
            if points_in[i]:
                c = 'b'
            else:
                c = 'r'
            m.scatter(point[1], point[0], latlon=True, s=20, c=c, lw=0)
        plt.show()
Beispiel #19
0
def plot(st, **kwargs):
    gc = kwargs.get('great_circle', False)
    width = 28000000
    latav = []
    lonav = []
    for tr in st:
        latav.append(tr.stats.stla)
        lonav.append(tr.stats.stlo)
    latav = np.mean(latav)
    lonav = np.mean(lonav)

    fig1 = plt.figure(figsize=(10, 10))
    lat_s = st[0].stats.evla
    lon_s = st[0].stats.evlo

    m = Basemap(projection='aeqd', lat_0=lat_s, lon_0=lon_s)
    xpt, ypt = m(lon_s, lat_s)
    m.scatter(xpt, ypt, s=99, c='red', marker='o', lw=1)
    m.drawcoastlines(linewidth=0.5)
    for tr in st:
        lat_0 = tr.stats.stla
        lon_0 = tr.stats.stlo
        xpt, ypt = m(lon_0, lat_0)
        if gc == True:
            m.drawgreatcircle(lon_s,
                              lat_s,
                              lon_0,
                              lat_0,
                              color='k',
                              alpha=0.1,
                              lw=0.4)
        m.scatter(xpt, ypt, s=5, c='green', marker='o', lw=0)
    '''
    fig2 = plt.figure(figsize=(10,10))
    m = Basemap(projection='ortho',lat_0=latav,lon_0=lonav)
    xpt, ypt = m(st[0].stats.sac['evlo'], st[0].stats.sac['evla'])
    m.scatter(xpt,ypt,s=99,c='red',marker='o',lw=1)
    # fill background.
    #m.drawmapboundary(fill_color='aqua')
    # draw coasts and fill continents.
    m.drawcoastlines(linewidth=0.5)
    #m.fillcontinents(color='coral',lake_color='aqua')
    # 20 degree graticule.
    m.drawparallels(np.arange(-80,81,20))
    m.drawmeridians(np.arange(-180,180,20))
    # draw a black dot at the center.
    for tr in st:
        lat_0 = tr.stats.sac['stla']
        lon_0 = tr.stats.sac['stlo']
        xpt, ypt = m(lon_0, lat_0)
        m.scatter(xpt,ypt,s=5,c='green',marker='o',lw=0)
    '''

    plt.show()
Beispiel #20
0
def general(input_file="input.csv"):
    # create arrays to hold
    lats = []
    longs = []
    weights = []
    names = []

    with open(input_file) as input_csv:
        csv_reader = csv.reader(input_csv)
        #next(csv_reader, None)
        for row in csv_reader:
            #print (float(row[0]))
            
            x, y, w, n = float(row[0]),  float(row[1]), row[2], row[3]
            lats.append(x)
            longs.append(y)
            weights.append(w)
            names.append(n)


    # create background map
    minLat=min(lats)
    maxLat=max(lats)
    minLong = min(longs)
    maxLong = max(longs)    
    if minLat -10 >-90:
        minLat = minLat-10
    if maxLat +10 <90:
        maxLat = maxLat +10
    if minLong -10 >-180:
        minLong = minLong-10
    if maxLong +10<180:
        maxLong = maxLong+10
    m= Basemap(llcrnrlon=minLong, llcrnrlat=minLat, urcrnrlon=maxLong,
                               urcrnrlat=maxLat, projection='merc', lat_1=33, lat_2=45,
                               lon_0=-95, resolution='c', area_thresh=10000)
    m.drawcoastlines()
    m.drawmapboundary(fill_color='aqua')
    m.drawcountries()
    m.fillcontinents(color='green', lake_color='aqua')
    m.drawstates()
    ypt, xpt = m(longs, lats)
    m.plot(ypt, xpt, 'bo', markersize=10)
    for y, x, name in zip(ypt,xpt,names):
        plt.text(y-1000,x+1000,name)

    for i in range(0,len(ypt)-1):
        m.drawgreatcircle(longs[i], lats[i], longs[i+1], lats[i+1], linewidth=1, color='r')
    
    for i in range(0,len(weights)-1):
        plt.text(((ypt[i]+ypt[i+1])/2),((xpt[i]+xpt[i+1])/2),weights[i+1])
    
    plt.show()
Beispiel #21
0
def plotSatelliteTrajectory(longitude,latitude,trajectoryname,fig_type='eps'):
    # TODO: This plotting function needs to be looked over...
    
    from mpl_toolkits.basemap import Basemap #@UnresolvedImport
    import pylab
    import numpy
    
    m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\
                llcrnrlon=-180,urcrnrlon=180,resolution='c')

    m.drawmapboundary()
    m.drawcoastlines()
    
    lon_nanix = numpy.where(~numpy.isnan(longitude))[0]    
    lon_ix_split = numpy.where(numpy.diff(lon_nanix) != 1)[0]
    
    if lon_ix_split.shape[0]==0 and  lon_nanix.shape[0]!=0:
        lon = longitude[lon_nanix]
        lat = latitude[lon_nanix]
        m.drawgreatcircle(lon[0],lat[0],lon[1],lat[1],color='red')
        m1 = m.drawgreatcircle(lon[0],lat[0],lon[1],lat[1],color='red')
        m = makesTheActuallyTrajectoryPlot(m,lon,lat)
    elif lon_ix_split.shape[0]==1:
        lon = longitude[lon_nanix[0:lon_ix_split[0]+1]]
        lat = latitude[lon_nanix[0:lon_ix_split[0]+1]]
        m.drawgreatcircle(lon[0],lat[0],lon[1],lat[1],color='red')
        m1 = m.drawgreatcircle(lon[0],lat[0],lon[1],lat[1],color='red')
        m = makesTheActuallyTrajectoryPlot(m,lon,lat)
        
        lon = longitude[lon_nanix[lon_ix_split[-1]+1:]]
        lat = latitude[lon_nanix[lon_ix_split[-1]+1:]]
        m = makesTheActuallyTrajectoryPlot(m,lon,lat)
    elif lon_ix_split.shape[0]>1:
        lon = longitude[lon_nanix[0:lon_ix_split[0]+1]]
        lat = latitude[lon_nanix[0:lon_ix_split[0]+1]]
        m.drawgreatcircle(lon[0],lat[0],lon[1],lat[1],color='red')
        m1 = m.drawgreatcircle(lon[0],lat[0],lon[1],lat[1],color='red')
        m = makesTheActuallyTrajectoryPlot(m,lon,lat)
        
        for c in range(len(lon_ix_split)-1):
            lon = longitude[lon_nanix[lon_ix_split[c]+1:lon_ix_split[c+1]+1]]
            lat = latitude[lon_nanix[lon_ix_split[c]+1:lon_ix_split[c+1]+1]]
            m = makesTheActuallyTrajectoryPlot(m,lon,lat)
        
        lon = longitude[lon_nanix[lon_ix_split[-1]+1:]]
        lat = latitude[lon_nanix[lon_ix_split[-1]+1:]]
        m = makesTheActuallyTrajectoryPlot(m,lon,lat)    

    pylab.legend((m1),['CloudSat/Calipso'],loc=0)
    
    if isinstance(fig_type, str) == True:
        figname = '%s.%s' %(trajectoryname, fig_type)
        pylab.savefig(figname)
    else:
        for figtype in fig_type:
            figname = '%s.%s' %(trajectoryname, figtype)
            pylab.savefig(figname)
class GCMapper:
    def __init__(self):
        # create new figure, axes instances.
        self.fig = plt.figure()
        self.ax  = self.fig.add_axes([0.1,0.1,0.8,0.8], axisbg = '#a5bfdd')
        
        # setup mercator map projection.
        self.map = Basemap(llcrnrlon = -130., llcrnrlat = 1.,
                    urcrnrlon = 40.,   urcrnrlat = 70.,
                    rsphere = (6378137.00,6356752.3142),
                    resolution = 'c',
                    projection = 'merc',
                    lat_0 = 40.,lon_0 = -20.,lat_ts = 20.)
        
    def plot(self, element):
        if isinstance(element, Segment):
            self.plot_segment(element)
        if isinstance(element, Route):
            self.plot_route(element)
        if isinstance(element, Point):
            self.plot_point(element)
        raise Exception('Incompatible type %s of element to plot' % type(element))
        
    def plot_route(self, route, color = 'b', linestyle = '-'):
        #just to be suer
        route.init_segments()
        for segment in route.segments:
            self.plot_segment(segment, color = color, linestyle = linestyle)
    
    def plot_point(self, point, formatting = 'go'):
        x, y = self.map(point.lon, point.lat)
        self.map.plot(x, y, formatting, ms = 8)
        
    def plot_segment(self, segment, color = 'b', linestyle = '-'):
        point1 = segment.start
        point2 = segment.end
        self.map.drawgreatcircle(
            point1.lon, point1.lat,
            point2.lon, point2.lat,
            linestyle = linestyle,
            linewidth = 1.5,
            color = color)

    def render(self):
        self.map.drawcoastlines(color='#8f8457')
        self.map.fillcontinents(color='#f5f0db')
        self.map.drawcountries(color='#a9a06d')
        self.map.drawparallels(np.arange(10,90,20), labels = [1,1,0,1])
        self.map.drawmeridians(np.arange(-180,180,30), labels = [1,1,0,1])
        self.ax.set_title('Flights')
        plt.show()
Beispiel #23
0
def drawMap(chromosome, continent, countries, fname=None):
    "Draws a map of a given chromosome on a given continent."
    continentBoundary = {
        'AO': [121, -43.0, 230, 20, 130, -10],
        'AS': [31, -13.0, 141, 53, 60, 20],
        'AF': [-24, -35.0, 59, 38, 10, 0],
        'EU': [-22, 33.0, 40, 65, 17, 52],
        'SA': [-82, -52.0, -40, 15, -17, -62],
        'NA': [-100, 4.0, -52, 50, -62, 20]
    }
    lllon, lllat, urlon, urlat, lon0, lat0 = continentBoundary[continent]
    plt.clf()
    map = Basemap(projection='merc',
                  lat_0=lat0,
                  lon_0=lon0,
                  resolution='c',
                  llcrnrlon=lllon,
                  llcrnrlat=lllat,
                  urcrnrlon=urlon,
                  urcrnrlat=urlat)
    map.drawcountries()
    caplon = [x[3] for x in countries]
    caplat = [x[2] for x in countries]
    caplonDX = [x[7] + x[3] for x in countries]
    caplatDX = [x[6] + x[2] for x in countries]
    labels = [unicode(x[1], 'utf-8') for x in countries]
    # TODO make maps prettier: better colors etc.
    map.fillcontinents(color='coral')
    # Connect cities in a proper order
    # TODO fix 180/-180 longitude problem
    for i in range(len(caplon) - 1):
        nylon, nylat, lonlon, lonlat = caplon[chromosome[i]], caplat[
            chromosome[i]], caplon[chromosome[i + 1]], caplat[chromosome[i +
                                                                         1]]
        map.drawgreatcircle(nylon,
                            nylat,
                            lonlon,
                            lonlat,
                            linewidth=1,
                            color='b')
    # Draw points on cities
    x, y = map(caplon, caplat)
    map.plot(x, y, 'bo', markersize=2)
    # Write city names
    x, y = map(caplonDX, caplatDX)
    for label, xpt, ypt in zip(labels, x, y):
        plt.text(xpt, ypt, label, fontsize=8)
    if fname == None:
        fname = str(int(time.time()))
    plt.savefig('images/' + fname + '.svg', bbox_inches='tight')
   def find_pierce_coor(self,plot='False'):
      import geopy
      from geopy.distance import VincentyDistance

      '''
      given an instance of the receiver function class this function
      returns latitude and longitude of all receiver side pierce points
      of Pds in a given depth range (the default range is 50 - 800 km)
      NOTE:
      be careful that ses3d typically uses colatitude, while
      this function returns latitude '''

      depth_range = np.arange(50,800,5)        #set range of pierce points

      #geodetic info
      bearing     = self.az
      lon_s = self.ses3d_seismogram.sy
      lat_s = 90.0-self.ses3d_seismogram.sx
      lon_r = self.ses3d_seismogram.ry
      lat_r = 90.0-self.ses3d_seismogram.rx
      origin      = geopy.Point(lat_s, lon_s)

      #find how far away the pierce point is
      model  = TauPyModel(model='pyrolite_5km')

      for i in range(0,len(depth_range)):
         phase = 'P'+str(depth_range[i])+'s'
         pierce = model.get_pierce_points(self.eq_depth,self.delta_deg,phase_list=[phase])
         points = pierce[0].pierce
         for j in range(0,len(points)):
            if points[j]['depth'] == depth_range[i] and points[j]['dist']*(180.0/np.pi) > 25.0:
               prc_dist = points[j]['dist']*(180.0/np.pi)
               d_km = prc_dist * ((2*np.pi*6371.0/360.0))
               destination = VincentyDistance(kilometers=d_km).destination(origin,bearing)
               lat = destination[0]
               lon = destination[1]
               value = 0
               row = {'depth':depth_range[i],'dist':prc_dist,'lat':lat,'lon':lon,'value':value}
               self.pierce_dict.append(row)

      if plot=='True':
         m = Basemap(projection='hammer',lon_0=0)
         m.drawmapboundary()
         m.drawcoastlines()
         m.drawgreatcircle(lon_s,lat_s,lon_r,lat_r,linewidth=1,color='b',alpha=0.5)

         for i in range(len(self.pierce_dict)):
            x,y = m(self.pierce_dict[i]['lon'],self.pierce_dict[i]['lat'])
            m.scatter(x,y,5,marker='o',color='r')
         plt.show()
Beispiel #25
0
def plot_interactions(locations: List[str],
                      latent_graph: ndarray,
                      map: Basemap,
                      ax: Axis,
                      skip_first: bool = False):
    """
    Given station ids and latent graph plot edges in different colors
    """

    # Transform lan/lot into region-specific values
    pixel_coords = [map(*coords) for coords in locations]

    # Draw contours and borders
    map.shadedrelief()
    map.drawcountries()
    # m.bluemarble()
    # m.etopo()


    # Plot Locations of weather stations
    for i, (x, y) in enumerate(pixel_coords):
        ax.plot(x, y, 'ok', markersize=10, color='yellow')
        ax.text(x + 10, y + 10, "Station " + str(i), fontsize=20, color='yellow');

    # Infer number of edge types and atoms from latent graph
    n_atoms = latent_graph.shape[-1]
    n_edge_types = latent_graph.shape[0]

    color_map = get_cmap('Set1')

    for i in range(n_atoms):
        for j in range(n_atoms):
            for edge_type in range(n_edge_types):
                if latent_graph[edge_type, i, j] > 0.5:

                    if skip_first and edge_type == 0:
                        continue

                    # Draw line between points
                    x = locations[i]
                    y = locations[j]
                    map.drawgreatcircle(x[0], x[1], y[0], y[1],
                                        color=color_map(edge_type - 1),
                                        label=str(edge_type))
    handles, labels = ax.get_legend_handles_labels()
    unique = [(h, l) for i, (h, l) in enumerate(zip(handles, labels)) if l not in labels[:i]]
    ax.legend(*zip(*unique))
    return ax
def plot_legs(df, dst_dir, title="?", boundary="all"):
    '''
    plot all legs in df on a map, df should have columns: 'latitude_x',
    'longitude_x', 'latitude_y' and 'longitude_y'
    '''
    fig = plt.figure(1, figsize=(16, 12))
    # setup mercator map projection.
    if boundary == "domestic":
        m = Basemap(llcrnrlon=-126,
                    llcrnrlat=23.5,
                    urcrnrlon=-65,
                    urcrnrlat=50,
                    projection='merc')
    else:
        m = Basemap(llcrnrlon=-150,
                    llcrnrlat=-35,
                    urcrnrlon=136,
                    urcrnrlat=62,
                    projection='merc')

    m.drawmapboundary(fill_color='#EBF4FA')
    m.drawcoastlines()
    m.fillcontinents()
    m.drawcountries()
    # m.drawcounties(linewidth= 0.15, color= '#000066')
    m.drawstates(linewidth=1.2, linestyle='solid', color='w')
    m.drawparallels(np.arange(15, 60, 15), labels=[1, 1, 1, 1])
    m.drawmeridians(np.arange(-120, -50, 40), labels=[1, 1, 1, 1])
    plt.title(title, fontsize=20)

    for index, row in df.iterrows():
        Dep_lat = row['latitude_x']
        Dep_lon = row['longitude_x']
        Arr_lat = row['latitude_y']
        Arr_lon = row['longitude_y']
        # draw great circle route between NY and London
        m.drawgreatcircle(Dep_lon,
                          Dep_lat,
                          Arr_lon,
                          Arr_lat,
                          del_s=10,
                          alpha=0.7,
                          linestyle='solid')
    fig.savefig(dst_dir + "legs_" + "%s" % boundary + ".png", dpi=150)
    fig.clear()
    return
Beispiel #27
0
def contact_map(wspr_data):
  """Show all the contacts on a map"""
  filename = os.path.join(Config.target, 'contactmap.png')
  logging.info('Drawing connection map to %s', filename)

  __calls = []
  points = []
  for data in wspr_data:
    if data.rx_call in __calls:
      continue
    __calls.append(data.rx_call)
    points.append((data.rx_lon, data.rx_lat))

  points = np.array(points)
  right, upl = points.max(axis=0) + [15., 10.]
  left, downl = points.min(axis=0) + [-15., -10]

  if right > 180 or left < -180:
    right, left, upl, downl = (180., -180., 90., -90.)

  fig = plt.figure(figsize=(12, 8))
  fig.text(.01, .02, ('http://github/com/0x9900/wspr - Contacts map - '
                      'Time span: %sH - Band: %s') % (Config.timespan, Config.band))
  fig.suptitle('[{}] WSPR Stats'.format(Config.callsign), fontsize=14, fontweight='bold')

  logging.info("Origin lat: %f / lon: %f", wspr_data[0].tx_lat, wspr_data[0].tx_lon)
  bmap = Basemap(projection='mill', lon_0=wspr_data[0].tx_lon, lat_0=wspr_data[0].tx_lat,
                 urcrnrlat=upl, urcrnrlon=right, llcrnrlat=downl, llcrnrlon=left,
                 resolution='c')

  bmap.drawlsmask(land_color="#5c4033", ocean_color="#9999ff", resolution='l')
  bmap.drawparallels(np.arange(-90., 90., 45.))
  bmap.drawmeridians(np.arange(-180., 180., 45.))
  bmap.drawcountries()
  bmap.drawstates(linestyle='dashed', color='#777777')
  #bmap.drawrivers(linestyle='dotted', color='#7777ff')

  for lon, lat in points:
    bmap.drawgreatcircle(wspr_data[0].tx_lon, wspr_data[0].tx_lat, lon, lat,
                         linewidth=.5, color='navy', del_s=1)
    x, y = bmap(lon, lat)
    bmap.plot(x, y, '*', markersize=4, alpha=.5, color='yellow')

  plt.savefig(filename)
  plt.close()
Beispiel #28
0
def trace_route(ip_address: str) -> None:
    if platform.system() in ('Linux', 'Darwin'):
        command = ['traceroute', '-m', '25', '-n', ip_address]
    elif platform.system() == 'Windows':
        tracert_path = Path('C:') / 'Windows' / 'System32' / 'TRACERT.exe'
        # alt: tracert_path = Path(subprocess.run(['where.exe', 'tracert'], capture_output=True, encoding='utf-8').stdout.rstrip())
        command = [str(tracert_path), '-h', '25', '-d', '-4', ip_address]
    else:
        print(
            "Sorry, this Python program does not have support for your current operating system!"
        )
        sys.exit(-1)

    # Start traceroute command
    proc = subprocess.Popen(command,
                            stdout=subprocess.PIPE,
                            shell=True,
                            universal_newlines=True)

    # Plot a pretty enough map
    fig = plt.figure(figsize=(10, 6), edgecolor='w')
    m = Basemap(projection='mill', lon_0=0, resolution='l')
    m.shadedrelief(scale=0.05)

    # Where we are coming from
    last_lon = None
    last_lat = None

    # Parse individual traceroute command lines
    for line in proc.stdout:
        print(line, end='')

        if platform.system() == 'Windows' and len(line.split()) != 8:
            continue

        hop_ip = line.split()[1 if platform.system() in ('Linux', 'Darwin')
                              else 7]  # First step already handled other cases

        if hop_ip in ('*', 'to'):
            continue

        (lat, lon) = get_location(hop_ip)

        if (lat is None):
            continue

        if last_lat is not None and (last_lat - lat + last_lon - lon) != 0.0:
            # print(lastLat, lastLon, lat, lon)
            x, y = m(lon, lat)
            m.scatter(x, y, 10, marker='o', color='r')
            line, = m.drawgreatcircle(last_lon, last_lat, lon, lat, color='b')

        last_lat = lat
        last_lon = lon

    plt.tight_layout()
    plt.show()
Beispiel #29
0
    def _dump_graph(self, title=None, lon_0=0, lat_0=90,
                    projection='vandg', func=lambda x: len(x._edges)):
        from mpl_toolkits.basemap import Basemap
        from matplotlib import pyplot as plt
        fig = plt.figure()
        m = Basemap()

        counts = {}
        for node in self._nodes:
            count = func(node)
            counts.setdefault(count, [])
            counts[count].append(list(node._point))

        minx = np.inf
        miny = np.inf
        maxx = -np.inf
        maxy = -np.inf
        for k, v in counts.items():
            v = np.array(v)
            ra, dec = vector.vector_to_radec(v[:, 0], v[:, 1], v[:, 2])
            x, y = m(ra, dec)
            m.plot(x, y, 'o', label=str(k))
            for x0 in x:
                minx = min(x0, minx)
                maxx = max(x0, maxx)
            for y0 in y:
                miny = min(y0, miny)
                maxy = max(y0, maxy)

        for edge in list(self._edges):
            A, B = [x._point for x in edge._nodes]
            r0, d0 = vector.vector_to_radec(A[0], A[1], A[2])
            r1, d1 = vector.vector_to_radec(B[0], B[1], B[2])
            m.drawgreatcircle(r0, d0, r1, d1, color='blue')

        plt.xlim(minx, maxx)
        plt.ylim(miny, maxy)
        if title:
            plt.title("%s, %d v, %d e" % (
                title, len(self._nodes), len(self._edges)))
        plt.legend()
        plt.show()
Beispiel #30
0
    def plot_city_in_map(self,name, routes=None):
        geolocator = Nominatim()
        fig = plt.figure(num=None, figsize=(150, 150))
        m = Basemap(projection='merc', llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180, urcrnrlon=180, resolution='c')
        m.drawcoastlines()
        m.fillcontinents(color='tan', lake_color='lightblue')
        # draw parallels and meridians.
        m.drawmapboundary(fill_color='lightblue')
        m.drawcountries(color='black')

        nylat = 40.78;
        nylon = -73.98
        # lonlat, lonlon are lat/lon of London.
        lonlat = 51.53;
        lonlon = 0.08
        # draw great circle route between NY and London
        # m.drawgreatcircle(nylon, nylat, lonlon, lonlat, linewidth=2, color='b')
        last_long = 0
        last_lat = 0
        count = 0
        color = None
        for city in routes:
            loc = geolocator.geocode(city)
            # x, y = map(loc.longitude, loc.latitude)
            if count !=0 :
                print('lala: %s' % count)
                print(loc)
                if (count % 2) is 0:
                    color = 'b'
                else:
                    color = 'g'
                m.drawgreatcircle(last_long, last_lat, loc.longitude, loc.latitude, linewidth=2, color=color)
            x, y = m(loc.longitude, loc.latitude)
            m.plot(x, y, 'b', markersize=50)


            plt.text(x, y, city, fontsize=8 , fontweight='bold', ha='left', va='top', color='k')
            last_long = loc.longitude
            last_lat = loc.latitude
            count += 1
        plt.title(name)
        plt.show()
Beispiel #31
0
def display(lat1,lon1,lat2,lon2):
# create new figure, axes instances.
    fig=plt.figure()
    ax=fig.add_axes([0.1,0.1,0.8,0.8])
    # setup mercator map projection.
    m = Basemap(projection='mill',lon_0=0) # Whole map
#    
#     
#    m = Basemap(llcrnrlon=-30.,llcrnrlat=20.,urcrnrlon=60.,urcrnrlat=80.,\
#            rsphere=(6378137.00,6356752.3142),\
#            resolution='l',projection='merc',\
#            lat_0=40.,lon_0=-20.,lat_ts=20.) #just Europe
#    
    # nylat, nylon are lat/lon of New York
    deblat = lat1; deblon = lon1
    # lonlat, lonlon are lat/lon of London.
    finlat = lat2; finlon = lon2
    # draw great circle route between NY and London
    m.drawgreatcircle(deblon,deblat,finlon,finlat,linewidth=2,color='r')
    m.drawcoastlines()
    m.fillcontinents()
    # draw parallels
    m.drawparallels(np.arange(10,90,20),labels=[1,1,0,1])
    # draw meridians
    m.drawmeridians(np.arange(-180,180,30),labels=[1,1,0,1])
    
    xpt1,ypt1 = m(lon1,lat1)
    xpt2,ypt2 = m(lon2,lat2)

    lonpt1, latpt1 = m(xpt1,ypt1,inverse=True) # plot a blue dot there
    lonpt2, latpt2 = m(xpt2,ypt2,inverse=True) # plot a blue dot there

    m.plot(xpt1,ypt1,'bo')  # plot a blue dot there
    m.plot(xpt2,ypt2,'bo')  # plot a blue dot there

    # put some text next to the dot, offset a little bit
    # (the offset is in map projection coordinates)
    plt.text(xpt1+100000,ypt1+100000,'Universite' % (lonpt1,latpt1)) 
    plt.text(xpt1+100000,ypt1+100000,'Universite' % (lonpt2,latpt2)) 

    ax.set_title('Parcours du Chercheur')
    plt.show()
Beispiel #32
0
def draw(version, cities_coor):
    m = Basemap(llcrnrlon=-180.,
                llcrnrlat=-80.,
                urcrnrlon=180.,
                urcrnrlat=80.,
                rsphere=(6378137.00, 6356752.3142),
                resolution='l',
                projection='mill',
                lat_0=0.,
                lon_0=-0.,
                lat_ts=30.)
    m.drawcoastlines()
    m.fillcontinents()
    for x in range(len(version.genom) - 1):
        m.drawgreatcircle(cities_coor[version.genom[x]][1],
                          cities_coor[version.genom[x]][0],
                          cities_coor[version.genom[x + 1]][1],
                          cities_coor[version.genom[x + 1]][0],
                          linewidth=2,
                          color="b")
    return m
Beispiel #33
0
    def GDELT_interactions_maplot(self,counts_int):

        max_val = np.log10(counts_int.max())

        def get_alpha(interaction_counts):
            '''
            Convert a count to an alpha val.
            Log-scaled
            '''
            scale = np.log10(interaction_counts)
            return (scale/max_val) * 0.25

        # Draw the basemap like before
        plt.figure(figsize=(12,12))
        event_map = Basemap(projection='merc',
                            resolution='l', area_thresh=1000.0,  # Low resolution
                            lat_0=15, lon_0=30,  # Map center
                            llcrnrlon=10, llcrnrlat=1,  # Lower left corner
                            urcrnrlon=50, urcrnrlat=30)  # Upper right corner
        # Draw important features
        event_map.drawcoastlines()
        event_map.drawcountries()
        event_map.fillcontinents(color='0.8')
        event_map.drawmapboundary()

        # Draw the lines on the map:
        for arc, count in interaction_counts.iteritems():
            point1, point2 = arc
            y1, x1 = point1
            y2, x2 = point2

            # Only plot lines where both points are on our map:
            if ((x1 > 10 and x1 < 100 and y1 > 20 and y1 < 70) and
                (x2 > 10 and x2 < 100 and y2 > 20 and y2 < 70)):

                line_alpha = get_alpha(count)

                # Draw the great circle line
                event_map.drawgreatcircle(x1, y1, x2, y2, linewidth=2,color='r', alpha=line_alpha)
        plt.show()
def translation_pathway(N, vt=2., Ric=1221):

    fig, ax = plt.subplots(1)
    fig2, ax2 = plt.subplots(1)
    # use low resolution coastlines.
    map = Basemap(projection='moll',lat_0=0,lon_0=0,resolution='l')
    # draw coastlines, country boundaries, fill continents.
    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))

    for i in range(N):
        
        Point = seismo.random_points(seismo="surface")
        pos_1, pos_2 = seismo.bottom_point_zeta(Point, Ric=1221)

        x_, y_, z_ = seismo.from_seismo_to_cartesian(Ric-Point['depth'],
                                                  Point['longitude'], Point['latitude'])
        Age = geodyn.translation(x_/Ric, y_/Ric, z_/Ric, vt, 1.)
        age_x, age_y = map(Point['longitude'], Point['latitude'])
        map.scatter(age_x, age_y, s=Age*100, zorder=10)

        #print Age, Ric-Point['depth'], Point['longitude'], Point['longitude']
        Nd = 20
        x, y, z, d, dx = seismo.raypath_straight(pos_1, pos_2, Nd, coordinate_type="spherical")
        r, theta, phi = seismo.from_cartesian_to_seismo(x, y, z)
        
        A = geodyn.translation(x/Ric, y/Ric, z/Ric, vt, 1.)
        Age_average = np.sum(A)/Nd
        
        map.scatter(age_x, age_y, s=Age*100, zorder=20)
        ax.scatter(Point['longitude'], Age_average)
        map.drawgreatcircle(pos_1['longitude'], pos_1['latitude'], pos_2['longitude'], pos_2['latitude'])
        for i, xtheta in enumerate(theta[0:-1]):
            map.drawgreatcircle(phi[i], theta[i], phi[i+1], theta[i+1])
def example_2():
    
    # retrieve data
    dir  = "/homespace/gaubert/viirs/real-data"
    #geo_file     = h5py.File("%s/%s" %(dir,"GMODO_npp_d20120224_t1821456_e1823098_b01694_c20120306214722023793_cspp_dev.h5"))
    #geo_file     = h5py.File("%s/%s" %(dir,"GMODO_npp_d20120224_t1823110_e1824352_b01694_c20120306215057805679_cspp_dev.h5"))
    #geo_file     = h5py.File("%s/%s" %(dir,"GMODO_npp_d20120224_t1826018_e1827260_b01694_c20120306215454419051_cspp_dev.h5"))
    #geo_file     = h5py.File("%s/%s" %(dir,"GMODO_npp_d20120224_t1827272_e1828514_b01694_c20120306215852012949_cspp_dev.h5"))
    geo_file      = h5py.File("/homespace/gaubert/GMTCO_npp_d20120224_t1100479_e1102121_b01689_c20120224172231282331_noaa_ops.h5")
    
    
    #lats = geo_file['All_Data']['VIIRS-MOD-GEO_All']['Latitude'][:]
    #lons = geo_file['All_Data']['VIIRS-MOD-GEO_All']['Longitude'][:]
    lats = geo_file['All_Data']['VIIRS-MOD-GEO-TC_All']['Latitude'][:]
    lons = geo_file['All_Data']['VIIRS-MOD-GEO-TC_All']['Longitude'][:]
    
    line_len = len(lats[0])
    col_len  = len(lats)
    
    print("line len %d, col len %d" % (line_len, col_len))
    print("Upper left corner point: (%f,%f)\n" % (lats[0][0], lons[0][0] ))
    print("Lower right corner point: (%f,%f)\n" % (lats[col_len-1][line_len-1], lons[col_len-1][line_len-1]))
    
    
    # draw map with markers for float locations
    #m = Basemap(projection='hammer',lon_0=180)
    lon_ref = lons[(col_len-1)/2][(line_len-1)/2]
    #lat_ref = 10
    lat_ref = lats[(col_len-1)/2][(line_len-1)/2]
    #m = Basemap(projection='ortho',lat_0=lat_ref,lon_0=lon_ref,resolution='l')
    m = Basemap(projection='nsper',lat_0=lat_ref,lon_0=lon_ref,satellite_height=2000*1000,resolution='l')
    
    #x, y = m(lons[0:10],lats[0:10])
    x,y  = m(lons,lats)
    
    
    m.drawcoastlines()
    
    m.drawmapboundary(fill_color='#99ffff')
    #m.fillcontinents(color='#cc9966',lake_color='#99ffff')
    #m.scatter(x,y,s = 1 ,color='k')
    
    m.drawgreatcircle(lons[0][0],lats[0][0],lons[0][-1],lats[0][-1],linewidth=1,color='b')
    m.drawgreatcircle(lons[0][0],lats[0][0],lons[col_len-1][0],lats[col_len-1][0],linewidth=1,color='b')
    m.drawgreatcircle(lons[col_len-1][0],lats[col_len-1][0],lons[col_len-1][line_len-1],lats[col_len-1][line_len-1],linewidth=1,color='b')
    m.drawgreatcircle(lons[0][line_len-1],lats[0][line_len-1],lons[col_len-1][line_len-1],lats[col_len-1][line_len-1],linewidth=1,color='b')
    
    plt.title('Location of VIIRS granule ')
    plt.savefig('/tmp/plot-gran3.png')
Beispiel #36
0
def calling():
    m = Basemap(projection='mill',
                llcrnrlat = 25,
                llcrnrlon = -130,
                urcrnrlat = 50,
                urcrnrlon = -60,
                resolution='l')

    m.drawcoastlines()
    m.drawcountries(linewidth=2)
    m.drawstates(color='b')
    #m.drawcounties(color='darkred')
    #m.fillcontinents()
    #m.etopo()
    #m.bluemarble()

    xs = []
    ys = []

    NYClat, NYClon = 40.7127, -74.0059
    xpt, ypt = m(NYClon, NYClat)
    xs.append(xpt)
    ys.append(ypt)
    m.plot(xpt, ypt, 'c*', markersize=15)

    LAlat, LAlon = 34.05, -118.25
    xpt, ypt = m(LAlon, LAlat)
    xs.append(xpt)
    ys.append(ypt)
    m.plot(xpt, ypt, 'g^', markersize=15)

    m.plot(xs, ys, color='r', linewidth=3, label='Flight 98')
    m.drawgreatcircle(NYClon, NYClat, LAlon, LAlat, color='c', linewidth=3, label='Arc')


    plt.legend(loc=4)
    plt.title('Basemap Tutorial')
    plt.show()
Beispiel #37
0
def drawWorldMap(chromosome, countries, fname=None):
    "Draws a map of the whole world"
    m = Basemap(projection='robin', lon_0=0, resolution='c')
    m.drawcoastlines()
    m.fillcontinents(color='coral', lake_color='aqua')
    # draw parallels and meridians.
    m.drawparallels(np.arange(-90., 140., 30.))
    m.drawmeridians(np.arange(0., 360., 60.))
    m.drawmapboundary(fill_color='aqua')
    # Draw points on cities
    caplon = [x[3] for x in countries]
    caplat = [x[2] for x in countries]
    labels = [unicode(x[1], 'utf-8') for x in countries]
    x, y = m(caplon, caplat)
    m.plot(x, y, 'bo', markersize=5)
    for i in range(len(caplon) - 1):
        nylon, nylat, lonlon, lonlat = caplon[chromosome[i]], caplat[
            chromosome[i]], caplon[chromosome[i + 1]], caplat[chromosome[i +
                                                                         1]]
        m.drawgreatcircle(nylon, nylat, lonlon, lonlat, linewidth=1, color='b')
    if fname == None:
        fname = 'world' + str(int(time.time()))
    plt.savefig('images/' + fname + '.png')
Beispiel #38
0
def make_map():
    m = Basemap(projection='lcc',
                resolution='l',
                width=2500000,
                height=3200000,
                lon_0=-78.70,
                lat_0=-11.,
                urcrnrlat=2.)
    m.shadedrelief()
    m.drawcountries(linewidth=0.6,
                    linestyle='solid',
                    color='k',
                    antialiased=1,
                    ax=None,
                    zorder=None)
    m.drawrivers(linewidth=0.1,
                 linestyle='solid',
                 color='b',
                 antialiased=1,
                 ax=None,
                 zorder=None)
    m.drawgreatcircle(lon1=0,
                      lat1=0,
                      lon2=-100,
                      lat2=0,
                      del_s=100.0,
                      linewidth=1,
                      color='w')
    m.drawparallels(np.arange(int(-50.), int(50.), 10),
                    labels=[1, 0, 0, 0],
                    linewidth=0.0,
                    size=8)
    m.drawmeridians(np.arange(int(-100.), int(-50.), 10),
                    labels=[0, 0, 0, 1],
                    linewidth=0.0,
                    size=8)
    return m
def draw_map(coordinates:list):
    
    """
        This function draws a map for a list of 
        Coordinates that would be passed as a parameter
        The function loops through the list of 
        coordinates and then plots the map for every departure airport from the 
        arrival airport.
        :params List[Dict[str,str]]
    """
   
    fig=plt.figure()
    ax=fig.add_axes([0.1,0.1,0.8,0.8])
    m = Basemap(\
                rsphere=(6378137.00,6356752.3142),\
                resolution='l',projection='cyl',\
                )
    arrlon = float(coordinates[0]['arrLon'])
    arrlat = float(coordinates[0]['arrLat'])
    
    for i in range(len(coordinates)):
        deplon = float(coordinates[i]['depLon'])
        deplat = float(coordinates[i]['depLat'])
        # # draw great circle route between Arrival and Department Airport
        m.drawgreatcircle(deplon,deplat,arrlon,arrlat,linewidth=1,color='r')
        m.plot(deplon,deplat, marker='o',color='b')
        
        
    m.drawcoastlines()
    m.fillcontinents()
    m.drawmapboundary(fill_color='aqua')
    #draw parallels
    m.drawparallels(np.arange(10,90,20),labels=[1,1,0,1])
    #draw meridians
    m.drawmeridians(np.arange(-180,180,30),labels=[1,1,0,1])
    ax.set_title('Flight Movement Map From EDDF Airport By Chinedum Roland Eke')
    plt.show()
def draw(x1,x2,x3,x4):

	map = Basemap(projection='robin', lat_0=0, lon_0=0, resolution='l', area_thresh=1000.0)
	map.drawcoastlines()
	map.drawcountries()
	map.fillcontinents(color='coral', lake_color='aqua')
	map.drawmapboundary(fill_color='aqua')

	map.drawmeridians(np.arange(0,360,30))
	map.drawparallels(np.arange(-90,90,30))

	#initiate ocean and icecap colours
	#map.bluemarble()

	#draw a blob on the map
	x,y = map(x2,x1)
	map.plot(x,y, 'bo', markersize=10)

	x,y = map(x4,x3)
	map.plot(x,y, 'bd', markersize=10)
	
	map.drawgreatcircle(x2,x1,x4,x3,linewidth=2,color='b')

	plt.show()
def save_map(routes, file_name):
    """
    Render flight routes to an image file.

    :param list routes: flight path lines
    :param str file_name: image output file name
    """
    fig = plt.figure(figsize=(7.195, 3.841), dpi=100)
    m = Basemap(projection='cyl', lon_0=0, resolution='c')
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)

    for (colour, alpha, linewidth, lat1, long1, lat2, long2) in sorted(routes):
        """
        Cannot handle situations in which the great circle intersects the 
        edge of the map projection domain, and then re-enters the domain.

        Fix from: http://stackoverflow.com/questions/13888566/
        """
        line, = m.drawgreatcircle(long1,
                                  lat1,
                                  long2,
                                  lat2,
                                  linewidth=linewidth,
                                  color=colour,
                                  alpha=alpha,
                                  solid_capstyle='round')

        p = line.get_path()

        # Find the index which crosses the dateline (the delta is large)
        cut_point = np.where(np.abs(np.diff(p.vertices[:, 0])) > 200)[0]

        if cut_point:
            cut_point = cut_point[0]

            # Create new vertices with a nan in between and set
            # those as the path's vertices
            new_verts = np.concatenate([
                p.vertices[:cut_point, :], [[np.nan, np.nan]],
                p.vertices[cut_point + 1:, :]
            ])
            p.codes = None
            p.vertices = new_verts

    m.warpimage(image="earth_lights_lrg.jpg")
    plt.savefig(file_name, dpi=1000)
def draw_records(rdd, n: int, colors="bgrcmy", alpha=1, seed=0):
    """
    n = -1 for all records
    """
    m = Basemap(llcrnrlon=-30.,
                llcrnrlat=30.,
                urcrnrlon=40.,
                urcrnrlat=75.,
                rsphere=(6378137.00, 6356752.3142),
                resolution='l',
                projection='merc',
                lat_ts=20.)

    colors = itertools.cycle(colors)

    if type(rdd) == RDD:
        collection = rdd.takeSample(False, n,
                                    seed) if n >= 0 else rdd.collect()
    else:
        collection = rdd[:n] if n >= 0 else rdd

    for i, (c, record) in enumerate(zip(colors, collection)):
        print("{} over {}".format(i, len(collection)))
        lat, long, time, alt, speed = record.Lat, record.Long, record.Time, record.Alt, record.Speed
        # print((record["From"]["Lat"], record["From"]["Long"], record["From"]["Alt"]))
        m.drawgreatcircle(record["From"]["Long"],
                          record["From"]["Lat"],
                          long[0],
                          lat[0],
                          color="k",
                          alpha=alpha)

        for x1, x2 in zip(
                zip(lat[:-1], long[:-1], time[:-1], alt[:-1], speed[:-1]),
                zip(lat[1:], long[1:], time[1:], alt[1:], speed[1:])):
            lat1, long1, t1, alt1, s1 = x1
            lat2, long2, t2, alt2, s2 = x2
            # print((lat1, long1, alt1, s1), (lat2, long2, alt2, s2), (t2-t1)/1000)
            m.drawgreatcircle(long1, lat1, long2, lat2, color=c, alpha=alpha)

        # print((record["To"]["Lat"], record["To"]["Long"], record["To"]["Alt"]))
        m.drawgreatcircle(long[-1],
                          lat[-1],
                          record["To"]["Long"],
                          record["To"]["Lat"],
                          color="k",
                          alpha=alpha)

    m.drawcoastlines()
    m.fillcontinents()
    # draw parallels
    m.drawparallels(np.arange(10, 90, 5), labels=[1, 1, 0, 1])
    # draw meridians
    m.drawmeridians(np.arange(-180, 180, 10), labels=[1, 1, 0, 1])
    plt.show()
Beispiel #43
0
def map_stream(st,showpath=True,showplot=True,Lat_0=0.0,Lon_0=60.0):
   from mpl_toolkits.basemap import Basemap

   fig = plt.figure()
   plt.ion()
   m = Basemap(projection='ortho',lat_0=Lat_0,lon_0=Lon_0,resolution='l')
   m.drawmapboundary()
   m.drawcoastlines()
   m.fillcontinents(color='gray',lake_color='white')
   gc_lines = []

   for tr in st:
      x1,y1 = m(tr.stats.sac['evlo'],tr.stats.sac['evla'])
      x2,y2 = m(tr.stats.sac['stlo'],tr.stats.sac['stla'])
      m.scatter(x1,y1,s=200.0,marker='*',facecolors='y',edgecolors='k',zorder=99)
      station_pt = m.scatter(x2,y2,s=20.0,marker='^',color='b',zorder=99,picker=1)
      station_pt.set_label(tr.stats.station)

      if showpath == True:
         gc_line = m.drawgreatcircle(tr.stats.sac['evlo'],tr.stats.sac['evla'],
                                     tr.stats.sac['stlo'],tr.stats.sac['stla'],
                                     linewidth=1,color='k',alpha=0.5)
         gc_line[0].set_label(tr.stats.station)
         gc_lines.append(gc_line)

   def onpick(event):
      art = event.artist
      picked =  art.get_label()
      print "removing station(s) ", picked
      st_to_remove = st.select(station=picked)
      for killed_tr in st_to_remove:
         st.remove(killed_tr)
      art.remove()

      for gc in gc_lines:
         gc_line_label = gc[0].get_label()
         if gc_line_label == picked:
            gc[0].remove()

      fig.canvas.draw()
   
   fig.canvas.mpl_connect('pick_event', onpick)

   if showplot == True:
      plt.show()
   else:
      return m
def save_map(routes, file_name):
    """
    Render flight routes to an image file.

    :param list routes: flight path lines
    :param str file_name: image output file name
    """
    fig = plt.figure(figsize=(7.195, 3.841), dpi=100)
    m = Basemap(projection='cyl', lon_0=0, resolution='c')
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)

    for (colour, alpha, linewidth, lat1, long1, lat2, long2) in sorted(routes):
        """
        Cannot handle situations in which the great circle intersects the 
        edge of the map projection domain, and then re-enters the domain.

        Fix from: http://stackoverflow.com/questions/13888566/
        """
        line, = m.drawgreatcircle(long1, lat1, long2, lat2,
                                  linewidth=linewidth,
                                  color=colour,
                                  alpha=alpha,
                                  solid_capstyle='round')

        p = line.get_path()

        # Find the index which crosses the dateline (the delta is large)
        cut_point = np.where(np.abs(np.diff(p.vertices[:, 0])) > 200)[0]

        if cut_point:
            cut_point = cut_point[0]

            # Create new vertices with a nan in between and set 
            # those as the path's vertices
            new_verts = np.concatenate([p.vertices[:cut_point, :], 
                                        [[np.nan, np.nan]], 
                                        p.vertices[cut_point+1:, :]])
            p.codes = None
            p.vertices = new_verts

    m.warpimage(image="earth_lights_lrg.jpg")
    plt.savefig(file_name, dpi=1000)
Beispiel #45
0
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
# setup mercator map projection.
m = Basemap(
    llcrnrlon=-100.0,
    llcrnrlat=20.0,
    urcrnrlon=20.0,
    urcrnrlat=60.0,
    rsphere=(6378137.00, 6356752.3142),
    resolution="l",
    projection="merc",
    lat_0=40.0,
    lon_0=-20.0,
    lat_ts=20.0,
)
# nylat, nylon are lat/lon of New York
nylat = 40.78
nylon = -73.98
# lonlat, lonlon are lat/lon of London.
lonlat = 51.53
lonlon = 0.08
# draw great circle route between NY and London
m.drawgreatcircle(nylon, nylat, lonlon, lonlat, linewidth=2, color="b")
m.drawcoastlines()
m.fillcontinents()
# draw parallels
m.drawparallels(np.arange(10, 90, 20), labels=[1, 1, 0, 1])
# draw meridians
m.drawmeridians(np.arange(-180, 180, 30), labels=[1, 1, 0, 1])
ax.set_title("Great Circle from New York to London")
plt.savefig("plotgreatcircle.png")
     plt.text(xpt,ypt,label)

"""
Next, let's display each edge in our array:
"""

twoFlights = flights.dot(flights)
threeFlights = flights.dot(flights).dot(flights)

print twoFlights
print
print threeFlights

for c1 in cityNum.keys():
     for c2 in cityNum.keys():
          #if c1 != c2 and flights[cityNum[c1],cityNum[c2]] > 0:
          if c1 != c2 and twoFlights[cityNum[c1],cityNum[c2]] > 0:
          #if c1 != c2 and threeFlights[cityNum[c1],cityNum[c2]] > 0:
               #Get city coordinates:
               c1lat,c1lon = cityCoords[c1]
               c2lat,c2lon = cityCoords[c2]
               print c1, c1lon, c1lat, c2, c2lat,c2lon
               #Draw edge between them:
               m.drawgreatcircle(c1lon,c1lat,c2lon,c2lat,linewidth=2,color='b')

"""
Display the final product:
"""
plt.show()

Beispiel #47
0
class WorldMap(object):
    def __init__(self, world_size=30):
        plt.clf()
        self.world_size = world_size
        self.world_map = Basemap(projection="vandg", lat_0=0, lon_0=0)
        self.world_map.drawparallels(np.arange(-90.0, 91.0, 180.0 / (world_size - 1.0)), latmax=90)
        self.world_map.drawmeridians(np.arange(0, 360, (360.0 / world_size)), latmax=90)

    def tron_to_lonlat(self, tx, ty):
        lat = 180.0 / (self.world_size - 1.0) * ty - 90.0
        lon = (360.0 / self.world_size) * tx
        return (lon, lat)

    def tron_to_xy(self, tx, ty):
        (lon, lat) = self.tron_to_lonlat(tx, ty)
        return self.world_map(lon, lat)

    def _plot_trace(self, trace, color):
        if len(trace) > 0:
            x, y = self.tron_to_xy(trace[0][0], trace[0][1])
            self.world_map.plot(x, y, color + "o", markersize=8.0)
            if len(trace) > 1:
                lon0, lat0 = self.tron_to_lonlat(trace[0][0], trace[0][1])
                for pos in trace[1:]:
                    lon, lat = self.tron_to_lonlat(pos[0], pos[1])
                    if (lon0 == 180.0) and (lon >= 180.0):
                        self.world_map.drawgreatcircle(lon0 + 0.001, lat0, lon + 0.001, lat, linewidth=5, color=color)
                    elif (lon0 >= 180.0) and (lon == 180.0):
                        self.world_map.drawgreatcircle(lon0 + 0.001, lat0, lon + 0.001, lat, linewidth=5, color=color)
                    else:
                        self.world_map.drawgreatcircle(lon0, lat0, lon, lat, linewidth=5, color=color)
                    lon0, lat0 = lon, lat
                if trace[-1][0] >= 15:
                    x, y = self.tron_to_xy(trace[-1][0] + 0.001, trace[-1][1])
                else:
                    x, y = self.tron_to_xy(trace[-1][0], trace[-1][1])
                self.world_map.plot(x, y, color + "D", markersize=8.0)

    def plot_trace(self, trace1=None, trace2=None, player1=BLUE, player2=RED):

        if player1 == BLUE:
            p1color = "b"
        elif player1 == RED:
            p1color = "r"
        else:
            p1color = "m"

        if player2 == BLUE:
            p2color = "b"
        elif player2 == RED:
            p2color = "r"
        else:
            p2color = "m"

        self._plot_trace(trace1, p1color)
        self._plot_trace(trace2, p2color)

    def plot_points(self, points, color="k"):
        for point in points:
            x, y = self.tron_to_xy(point[0] + 0.001, point[1])
            self.world_map.plot(x, y, color + "s", markersize=6.0)

    def show(self, title=None):
        if title:
            plt.title(title)
        plt.show()

    def save(self, title=None, filename="world.png"):
        if title:
            plt.title(title)
        fig = plt.gcf()
        fig.set_size_inches(16, 12)
        plt.savefig(filename, dpi=100)
def map_G(G):
        
    import matplotlib.pyplot as plt
    from mpl_toolkits.basemap import Basemap
    import matplotlib.cm as cmx
    
    import matplotlib as mpl
    mpl.rcParams['font.size'] = 10.
    mpl.rcParams['axes.labelsize'] = 8.
    mpl.rcParams['xtick.labelsize'] = 6.
    mpl.rcParams['ytick.labelsize'] = 6.
    
    from shapelib import ShapeFile
    import dbflib
    from matplotlib.collections import LineCollection
    from matplotlib import cm
    import matplotlib.colors as colors
     
    ###########################################################################################
    fig = plt.figure(3)
    #Custom adjust of the subplots
    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(projection='cyl',\
                llcrnrlon=-9, \
                llcrnrlat=3.8, \
                urcrnrlon=-1.5, \
                urcrnrlat = 11, \
                resolution = 'h', \
#                 projection = 'tmerc', \
                lat_0 = 7.38, \
                lon_0 = -5.30)
      
    # read subpref coordinates
    subpref_coord = read_in_subpref_lonlat()
    
    shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    
    for npoly in range(shp.info()[0]):
        shpsegs = []
        shpinfo = []
           
        shp_object = shp.read_object(npoly)
        verts = shp_object.vertices()
        rings = len(verts)
        for ring in range(rings):
            lons, lats = zip(*verts[ring])
    #        if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91:
    #            raise ValueError,msg
            x, y = m(lons, lats)
            shpsegs.append(zip(x,y))
            if ring == 0:
                shapedict = dbf.read_record(npoly)
            #print shapedict
            name = shapedict["ID_DEPART"]
            subpref_id = shapedict["ID_SP"]
            # add information about ring number to dictionary.
            shapedict['RINGNUM'] = ring+1
            shapedict['SHAPENUM'] = npoly+1
            shpinfo.append(shapedict)
        #print subpref_id
        #print name
        lines = LineCollection(shpsegs,antialiaseds=(1,))
#         lines.set_facecolors(col[subpref_id])
        lines.set_edgecolors('gray')
        lines.set_linewidth(0.1)
        ax.add_collection(lines)   
        
    if G.has_node(-1): 
        G.remove_node(-1)
    if G.has_node(0): 
        G.remove_node(0)
        
###########################################################################################################
### this is the main part: scale weights of # commuters, use colormap by work location and then plot
### all or just the routes with more that 10 commutes 
###########################################################################################################
    
#     max7s = 0
#     min7s = 10000000
#     for u,v,d in G.edges(data=True):
#         if d['weight'] > max7s:
#             max7s = d['weight']
#         if d['weight'] < min7s:
#             min7s = d['weight']
#             
#     max7s = float(max7s)
#     print "max", (max7s)
#     print "min", (min7s)
#     
#     scaled_weight = defaultdict(int)
#     
#     for i in range(len(G.edges())):
#         scaled_weight[i] = defaultdict(int)
#     for u,v,d in G.edges(data=True):
#         scaled_weight[u][v] = (d['weight'] - min7s) / (max7s - min7s)
    
    values = range(256)    
    jet = cm = plt.get_cmap('jet') 
    cNorm  = colors.Normalize(vmin=0, vmax=values[-1])
    scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
    
    for u, v, d in G.edges(data=True):
#         lo = []
#         la = []  
#         lo.append(subpref_coord[u][0])
#         lo.append(subpref_coord[v][0])
#         la.append(subpref_coord[u][1])
#         la.append(subpref_coord[v][1])
#         x, y = m(lo, la)
#         linewidth7s = scaled_weight[u][v] * 2.5 + 0.25
#         m.plot(x,y, linewidth= linewidth7s)
#         if linewidth7s > 1:
#             print (linewidth7s)
        if d['weight'] >= 0: 
            colorVal = scalarMap.to_rgba(values[v])
#             linewidth7s = scaled_weight[u][v] * 2.5 + 0.35 
#             print u, v,  d['weight'], scaled_weight[u][v]
###########################################################################################################
### no scaling vs scaling the width of the line
###########################################################################################################
#            linewidth7s = d['weight'] / 10   
            m.drawgreatcircle(subpref_coord[u][0], subpref_coord[u][1], \
                              subpref_coord[v][0], subpref_coord[v][1], linewidth= d['weight']*100, color=colorVal)

#     m.drawcoastlines()
    #m.fillcontinents()
        
    plt.savefig('/home/sscepano/Project7s/D4D/CI/commuting_centers/Igor/high_betweenes_routes4.png',dpi=700)
    #plt.show()
    
    ###################################################################################################3
    
    return
Beispiel #49
0
    d_long = end_long - start_long
    a = math.sin(d_latt/2)**2 + math.cos(start_latt) * math.cos(end_latt) * math.sin(d_long/2)**2  
    c = 2 * math.asin(math.sqrt(a))  
    return 6371 * c *1000

longslist=[0,90,180]
latslist=[65,65,65]
dpslist=[5,10,5]
dmslist=[5,5,10]
print m(0,60)
print m(0,70)
print m(-5,65)
print m(5,65)
print m.gcpoints(0,60,0,70,10)

m.drawgreatcircle(0,60,0,70,100)
m.drawgreatcircle(-5,65,5,65,100)

m.drawgreatcircle(0,60,-5,65,100)
m.drawgreatcircle(0,60,5,65,100)

m.drawgreatcircle(-5,65,0,70,100)
m.drawgreatcircle(0,70,5,65,100)
'''
# draw ellipses
for n in range(0,len(longslist)):
    xy= m(longslist[n],latslist[n])
    w = haversine(longslist[n]-dmslist[n],latslist[n],longslist[n]+dmslist[n],latslist[n])
    h = haversine(longslist[n],latslist[n]-dpslist[n],longslist[n],latslist[n]+dpslist[n])
    e = Ellipse(xy, w,h,longslist[n])
    print xy, w,h,e
Beispiel #50
0
    top_right_lon = get_domain('full_utah')['top_right_lon']    
    top_right_lat = get_domain('full_utah')['top_right_lat']    
    m = Basemap(resolution='i',area_thresh=10.,projection='cyl',\
        llcrnrlon=bot_left_lon,llcrnrlat=bot_left_lat,\
        urcrnrlon=top_right_lon,urcrnrlat=top_right_lat,)
    
    m.drawstates(color='k', linewidth=.8)
    m.drawcoastlines()
    m.drawcounties()
    m.fillcontinents()
    #Plot Subdomains (Salt Lake Valley, Utah Lake, etc...)
    for area in ['salt_lake_valley','utah_valley','cache_valley','uintah_basin','bear_lake']:    
        domain = get_domain(area)
        toprightlat = domain['top_right_lat']
        topleftlat = domain['top_right_lat']
        toprightlon = domain['top_right_lon']
        topleftlon = domain['bot_left_lon']
        botrightlat = domain['bot_left_lat']
        botrightlon = domain['top_right_lon']
        botleftlat = domain['bot_left_lat']
        botleftlon = domain['bot_left_lon']
        
        m.drawgreatcircle(toprightlon,toprightlat,topleftlon,topleftlat, color='#FFFF4C', linewidth='3')
        m.drawgreatcircle(topleftlon,topleftlat,botleftlon,botleftlat, color='#FFFF4c', linewidth='3')
        m.drawgreatcircle(botleftlon,botleftlat,botrightlon,botrightlat, color='#FFFF4c', linewidth='3')
        m.drawgreatcircle(botrightlon,botrightlat,toprightlon,toprightlat, color='#FFFF4c', linewidth='3')

    
    
    
Beispiel #51
0
# <headingcell level=2>

# Grafisch

# <codecell>

fig = plt.figure(figsize=(9,9))
m = Basemap(projection='ortho',lon_0=lon0,lat_0=lat0,resolution='l')
m.shadedrelief()

# draw parallels and meridians.
m.drawparallels(np.arange(-90.,120.,30.))
m.drawmeridians(np.arange(0.,420.,10.))

# draw distance
m.drawgreatcircle(lon1,lat1,lon2,lat2,linewidth=2,color='b')

# draw km
x, y = m(lon0, lat0+0.5)
sx,sy= m(lon1, lat1)
ex,ey= m(lon2, lat2)
plt.text(x, y, '%dkm' % (dist2), color='k', ha='center', va='bottom',fontsize=14)
plt.text(sx,sy, sadr, color='k', ha='left',fontsize=9)
plt.text(ex,ey, eadr, color='k', ha='left',fontsize=9)
fig.savefig('Distance-Berlin-Lisbon.png',dpi=72,transparent=True,bbox_inches='tight')

# <codecell>

print('Done.')

# <codecell>
Beispiel #52
0
def johnsons(input_file="input.csv"):
    lats = []
    longs = []
    weights = []
    names = []
    path = []
    paths = []
    minLat = 90;
    minLong = 180;
    maxLat = -90
    maxLong =-180

    with open(input_file) as input_csv:
        csv_reader = csv.reader(input_csv)
        for row in csv_reader:
            if row[0] != "done":    
                x, y, w, n = float(row[0]),  float(row[1]), row[2], row[3]

                lats.append(x)
                longs.append(y)
                weights.append(w)
                names.append(n)
                if x<minLat:
                    minLat=x
                if y<minLong:
                    minLong = y
                if x>maxLat:
                    maxLat = x
                if y>maxLong:
                    maxLong = y
            else:
                path.append(lats)
                path.append(longs)
                path.append(weights)
                path.append(names)
                paths.append(path)
                lats = []
                longs = []
                weights = []
                names = []
                path = []


    # create background map 
    if minLat -10 >-90:
        minLat = minLat-10
    if maxLat +10 <90:
        maxLat = maxLat +10
    if minLong -10 >-180:
        minLong = minLong-10
    if maxLong +10<180:
        maxLong = maxLong+10
    m= Basemap(llcrnrlon=minLong, llcrnrlat=minLat, urcrnrlon=maxLong,
                               urcrnrlat=maxLat, projection='merc', lat_1=33, lat_2=45,
                               lon_0=-95, resolution='c', area_thresh=10000)
    m.drawcoastlines()
    m.drawmapboundary(fill_color='aqua')
    m.drawcountries()
    m.fillcontinents(color='green', lake_color='aqua')
    m.drawstates()
    
    for p in paths:
        in_lats= p[0];
        in_longs =p[1];
        in_names = p[3];
        in_weight = p[2];
        ypt, xpt = m(in_longs, in_lats)
        m.plot(ypt, xpt, 'bo', markersize=10)
        for y, x, name in zip(ypt,xpt,in_names):
            plt.text(y-1000,x+1000,name)
    
        for i in range(0,len(in_lats)-1):
            m.drawgreatcircle(in_longs[i], in_lats[i], in_longs[i+1], in_lats[i+1], linewidth=1, color='r')
        
        for i in range(0,len(in_weight)-1):
            plt.text(((ypt[i]+ypt[i+1])/2),((xpt[i]+xpt[i+1])/2),in_weight[i+1])
    plt.show()
Beispiel #53
0
            rsphere=(6378137.00,6356752.3142),\
            resolution='c',area_thresh=10000.,projection='merc',\
            lat_0=40.,lon_0=-20.,lat_ts=20.)
# nylat, nylon are lat/lon of New York
nylat = 40.78
nylon = -73.98
# lonlat, lonlon are lat/lon of London.
lonlat = 51.53
lonlon = 0.08

# find 1000 points along the great circle.
#x,y = m.gcpoints(nylon,nylat,lonlon,lonlat,1000)
# draw the great circle.
#m.plot(x,y,linewidth=2)
# drawgreatcircle performs the previous 2 steps in one call.
m.drawgreatcircle(nylon,nylat,lonlon,lonlat,linewidth=2,color='b')

m.drawcoastlines()
m.fillcontinents()
# draw parallels
circles = np.arange(10,90,20)
m.drawparallels(circles,labels=[1,1,0,1])
# draw meridians
meridians = np.arange(-180,180,30)
m.drawmeridians(meridians,labels=[1,1,0,1])
plt.title('Great Circle from New York to London (Mercator)')
sys.stdout.write('plotting Great Circle from New York to London (Mercator)\n')

# create new figure
fig=plt.figure()
# setup a gnomonic projection.
Beispiel #54
0
def prims(input_file= "input.csv"):
    lats = []
    longs = []
    weights = []
    names = []
    neighbors = []


    with open(input_file) as input_csv:
        csv_reader = csv.reader(input_csv)
        for row in csv_reader:
            x,y,w,n,ne = float(row[0]), float(row[1]), row[2], row[3], row[4]        
            lats.append(x)
            longs.append(y)
            weights.append(w)
            names.append(n)
            neighbors.append(ne)
    
  

    # background map
    minLat=min(lats)
    maxLat=max(lats)
    minLong = min(longs)
    maxLong = max(longs)    
    if minLat -10 >-90:
        minLat = minLat-10
    if maxLat +10 <90:
        maxLat = maxLat +10
    if minLong -10 >-180:
        minLong = minLong-10
    if maxLong +10<180:
        maxLong = maxLong+10
    m= Basemap(llcrnrlon=minLong, llcrnrlat=minLat, urcrnrlon=maxLong,
                               urcrnrlat=maxLat, projection='merc', lat_1=33, lat_2=45,
                               lon_0=-95, resolution='c', area_thresh=10000)
    m.drawcoastlines()
    m.drawmapboundary(fill_color='aqua')
    m.fillcontinents(color='green', lake_color='aqua')
    m.drawstates()
    m.drawcountries()

    ypt, xpt = m(longs, lats)
    m.plot(ypt, xpt, 'bo', markersize=10)
    for y, x, name in zip(ypt,xpt,names):
        plt.text(y+1000,x+1000,name)    
        
    for i in range(0,(len(longs))):
        neighbors_list = neighbors[i].split("_");
        inner_lats = []
        inner_longs = []
        inner_weight = []
        for neighbor in neighbors_list:
            if(neighbor==''):
                continue
            value_list = neighbor.split(";")            
            if(len(value_list)>=2):                
                if(value_list[0] != " " and value_list[1] != " "):
                    lat = float(value_list[0])
                    lng = float(value_list[1])
                    w = float(value_list[2])
                    inner_lats.append(lat)
                    inner_longs.append(lng)
                    inner_weight.append(w)
        if(inner_longs!= []):
            in_ypt, in_xpt = m(inner_longs, inner_lats)
            m.plot(in_ypt, in_xpt, 'bo', markersize=10)
            inner_y, inner_x = m(inner_longs,inner_lats)
            for j in range(0,len(inner_longs)):
                m.drawgreatcircle(longs[i],lats[i],inner_longs[j],inner_lats[j], linewidth=1,color="r")
                plt.text((ypt[i]+inner_y[j])/2,(xpt[i]+inner_x[j])/2,inner_weight[j])


    plt.show()
            #lat_1=minlat, lat_2=maxlat,
            lat_0=minlat + height/2,
            lon_0=minlon + width/2,)
            #lon_0=-180)

m.drawcoastlines()
m.drawstates()
m.drawcountries()
m.fillcontinents()

#m.drawparallels(np.arange(pts.latitude.min(),pts.latitude.max(),2.), labels=[1,1,1,1], fmt="%0.1f")
#m.drawmeridians(np.arange(pts.longitude.min(), pts.longitude.max(),5.), labels=[1,1,1,1], fmt="%0.1f")

for f in fly.iterrows():
    f = f[1]
    m.drawgreatcircle(f.startlon, f.startlat, f.endlon, f.endlat, linewidth=3, alpha=0.4, color='b' )
    m.plot(*m(f.startlon, f.startlat), color='g', alpha=0.8, marker='o')
    m.plot(*m(f.endlon, f.endlat), color='r', alpha=0.5, marker='o' )
    #pa = Point(m(f.startlon, f.startlat))
    #pb = Point(m(f.endlon, f.endlat))
    #plt.plot([pa.x, pb.x], [pa.y, pb.y], linewidth=4)
plt.savefig('data/flightdata.png', dpi=300, frameon=False, transparent=True)

# <headingcell level=1>

# Scratch

# <codecell>

flights.distance.sum()
def map_commutes(G):
    
    import numpy as np    
    import matplotlib.pyplot as plt
    from mpl_toolkits.basemap import Basemap
    
    import matplotlib as mpl
    mpl.rcParams['font.size'] = 10.
    mpl.rcParams['axes.labelsize'] = 8.
    mpl.rcParams['xtick.labelsize'] = 6.
    mpl.rcParams['ytick.labelsize'] = 6.
    
    from shapelib import ShapeFile
    import dbflib
    from matplotlib.collections import LineCollection
    from matplotlib import cm
     
    ###########################################################################################
    fig = plt.figure(3)
    #Custom adjust of the subplots
    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(projection='cyl',\
                llcrnrlon=-9, \
                llcrnrlat=3.8, \
                urcrnrlon=-1.5, \
                urcrnrlat = 11, \
                resolution = 'h', \
#                 projection = 'tmerc', \
                lat_0 = 7.38, \
                lon_0 = -5.30)
      
    # read subpref coordinates
    subpref_coord = read_subpref_lonlat()
    
    shp = ShapeFile(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    dbf = dbflib.open(r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    
    for npoly in range(shp.info()[0]):
        shpsegs = []
        shpinfo = []
           
        shp_object = shp.read_object(npoly)
        verts = shp_object.vertices()
        rings = len(verts)
        for ring in range(rings):
            lons, lats = zip(*verts[ring])
    #        if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91:
    #            raise ValueError,msg
            x, y = m(lons, lats)
            shpsegs.append(zip(x,y))
            if ring == 0:
                shapedict = dbf.read_record(npoly)
            #print shapedict
            name = shapedict["ID_DEPART"]
            subpref_id = shapedict["ID_SP"]
            # add information about ring number to dictionary.
            shapedict['RINGNUM'] = ring+1
            shapedict['SHAPENUM'] = npoly+1
            shpinfo.append(shapedict)
        #print subpref_id
        #print name
        lines = LineCollection(shpsegs,antialiaseds=(1,))
#         lines.set_facecolors(col[subpref_id])
        lines.set_edgecolors('k')
        lines.set_linewidth(0.2)
        ax.add_collection(lines)   
        
    if G.has_node(-1): 
        G.remove_node(-1)
    if G.has_node(0): 
        G.remove_node(0)
    
    max7s = 1
    min7s = 10000000
    for u,v,d in G.edges(data=True):
        if d['weight'] > max7s:
            max7s = d['weight']
        if d['weight'] < min7s:
            min7s = d['weight']
            
    max7s = float(max7s)
    print "max", (max7s)
    print "min", (min7s)
    
    scaled_weight = defaultdict(int)
    for i in range(256):
        scaled_weight[i] = defaultdict(int)
    for u,v,d in G.edges(data=True):
        scaled_weight[u][v] = (d['weight'] - min7s) / (max7s - min7s)
    
    for u, v, d in G.edges(data=True):
#         lo = []
#         la = []  
#         lo.append(subpref_coord[u][0])
#         lo.append(subpref_coord[v][0])
#         la.append(subpref_coord[u][1])
#         la.append(subpref_coord[v][1])
#         x, y = m(lo, la)
#         linewidth7s = scaled_weight[u][v] * 2.5 + 0.25
#         m.plot(x,y, linewidth= linewidth7s)
#         if linewidth7s > 1:
#             print (linewidth7s)
        linewidth7s = scaled_weight[u][v] * 2.5 + 0.25    
        m.drawgreatcircle(subpref_coord[u][0], subpref_coord[u][1], \
                          subpref_coord[v][0], subpref_coord[v][1], linewidth= linewidth7s, color='r')

    m.drawcoastlines()
    m.fillcontinents()
        
    plt.savefig('/home/sscepano/Project7s/D4D/CI/urban_rural/home_work/OUTPUT_files/maps/hw_commuting_cur.png',dpi=700)
    #plt.show()
    
    ###################################################################################################3
    
    return
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

map = Basemap(projection='merc', 
              lat_0=0, lon_0=0,
              llcrnrlon=-20.,llcrnrlat=0.,urcrnrlon=180.,urcrnrlat=80.)

map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='coral',lake_color='aqua')
map.drawcoastlines()

map.drawparallels(range(0, 90, 20))
map.drawmeridians(range(0, 180, 20))

#Paris-Tokyo
map.drawgreatcircle(2.3, 48.9, 139.7, 35.6,linewidth=2,color='r')
#Tokyo-Dubai
map.drawgreatcircle(139.7, 35.6, 55.2, 25.,linewidth=2,color='r')
#Dubai-Paris
map.drawgreatcircle(55.2, 25., 2.3, 48.9,linewidth=2,color='r')

plt.show()
Beispiel #58
0
def render(segments):
    
    # create new figure, axes instances.
    fig = plt.figure()
    ax  = fig.add_axes([0.1,0.1,0.8,0.8], axisbg = '#a5bfdd')
    
    llcrnrlon = config.map_dimensions['lon'][0]
    urcrnrlon = config.map_dimensions['lon'][1]
    
    llcrnrlat = config.map_dimensions['lat'][0]
    urcrnrlat = config.map_dimensions['lat'][1]

    # setup mercator map projection.
    m = Basemap(
        llcrnrlon = llcrnrlon, llcrnrlat = llcrnrlat,
        urcrnrlon = urcrnrlon, urcrnrlat = urcrnrlat,
        rsphere = (6378137.00,6356752.3142),
        resolution = 'c', projection = 'merc',
        #lat_0 = 40.,lon_0 = -20.,lat_ts = 20.
    )
    
    for segment in segments['benchmark']:
        m.drawgreatcircle(segment.start.lon, segment.start.lat,
                          segment.end.lon, segment.end.lat,
                          linewidth = 1, color='#00458A')
        x, y = m(segment.start.lon, segment.start.lat)
        m.plot(x, y, 'bo', ms = 4)
        x, y = m(segment.end.lon, segment.end.lat)
        m.plot(x, y, 'bo', ms = 4)

    for segment in segments['formation']:
        p('geo-debug', 'Start to plot a formation trajectory')
        p('geo-debug', 'Trajectory: (%s, %s) -> (%s, %s)' % (
            segment.start.lon, segment.start.lat,
            segment.end.lon, segment.end.lat
        ))
        m.drawgreatcircle(segment.start.lon, segment.start.lat,
                          segment.end.lon, segment.end.lat,
                          linewidth = 1, color='g')
        x, y = m(segment.start.lon, segment.start.lat)
        m.plot(x, y, 'go', ms = 4)
        x, y = m(segment.end.lon, segment.end.lat)
        m.plot(x, y, 'go', ms = 4)
        p('geo-debug', 'Done with plotting a formation trajectory')
    
    for segment in segments['solo']:
        m.drawgreatcircle(segment.start.lon, segment.start.lat,
                          segment.end.lon, segment.end.lat,
                          linewidth = 1, color='r')
        x, y = m(segment.start.lon, segment.start.lat)
        m.plot(x, y, 'ro', ms = 4)
        x, y = m(segment.end.lon, segment.end.lat)
        m.plot(x, y, 'ro', ms = 4)

    m.drawcoastlines(color='#8f8457')
    m.fillcontinents(color='#f5f0db')
    m.drawcountries(color='#a9a06d')
    m.drawparallels(config.map['parallels'], labels = [1,1,0,1])
    m.drawmeridians(config.map['meridians'], labels = [1,1,0,1])
    
    return plt, ax
Beispiel #59
0
#!/bin/env python
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
from g import getCoordinates

# llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon
# are the lat/lon values of the lower left and upper right corners
# of the map.
# resolution = 'c' means use crude resolution coastlines.
fig = plt.figure(figsize=(20,18))
m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\
            llcrnrlon=-180,urcrnrlon=180,resolution='c')
m.drawcoastlines()
m.fillcontinents(color='grey',lake_color='black')
# lonlat, lonlon are lat/lon of London.
lonlat = 51.53; lonlon = 0.08
for c in getCoordinates():
    if len(c['Longitude']) > 2:
        lon = float(c['Longitude'])
        lat = float(c['Latitude'])
        m.drawgreatcircle(lon, lat,lonlon,lonlat,linewidth=2,color='b')
m.drawparallels(np.arange(-90.,91.,30.), color='red')
m.drawmeridians(np.arange(-180.,181.,60.), color='red')
m.drawmapboundary(fill_color='black')
plt.title("How about a nice game of chess?")
plt.show()
# Draw the points on the map:
for arc, count in interaction_counts.iteritems():
    point1, point2 = arc
    y1, x1 = point1
    y2, x2 = point2

##    if x1<-30:
##        x1=x1+360
##    if x2<-30:
##        x2=x2+360
        
    # Only plot lines where both points are on our map:
    if ((y1 > -60 and y1 < 75) and (y2 > -60 and y2 < 75)):
        line_alpha = get_alpha(count)
        #line, =
        event_map.drawgreatcircle(x1, y1, x2, y2, linewidth=3, color='r', alpha=line_alpha)
'''
        p = line.get_path()
        # find the index which crosses the dateline (the delta is large)
        cut_point = np.where(np.abs(np.diff(p.vertices[:, 0])) > 200)[0]
        if cut_point:
            cut_point = cut_point[0]
            # create new vertices with a nan inbetween and set those as the path's vertices
            new_verts = np.concatenate(
                                       [p.vertices[:cut_point, :], 
                                        [[np.nan, np.nan]], 
                                        p.vertices[cut_point+1:, :]]
                                       )
            p.codes = None
            p.vertices = new_verts
'''