示例#1
0
    def plot_global_map(self):
        """
        Plot global map of event and stations
        """
        # ax = plt.subplot(211)
        plt.title(self.cmtsource.eventname)
        m = Basemap(projection='cyl', lon_0=0.0, lat_0=0.0,
                    resolution='c')
        m.drawcoastlines()
        m.fillcontinents()
        m.drawparallels(np.arange(-90., 120., 30.))
        m.drawmeridians(np.arange(0., 420., 60.))
        m.drawmapboundary()

        x, y = m(self.sta_lon, self.sta_lat)
        m.scatter(x, y, 30, color="r", marker="^", edgecolor="k",
                  linewidth='0.3', zorder=3)

        cmt_lat = self.cmtsource.latitude
        cmt_lon = self.cmtsource.longitude
        focmecs = self.moment_tensor
        ax = plt.gca()
        bb = Beach(focmecs, xy=(cmt_lon, cmt_lat), width=20, linewidth=1,
                   alpha=1.0)
        bb.set_zorder(10)
        ax.add_collection(bb)
示例#2
0
def source_reciever_plot(st, **kwargs):
    """
   Plot source and reciever on map
   """
    save = kwargs.get('save', False)
    topo = kwargs.get('topo', False)
    mt = kwargs.get('moment_tensor', False)
    w = kwargs.get('width', (900000, 900000))
    title = kwargs.get('title', True)
    proj = kwargs.get('proj', 'aeqd')

    m = mapplot(proj,
                lat_0=st[0].stats.sac['evla'],
                lon_0=st[0].stats.sac['evlo'])
    m.drawparallels(np.arange(-80., 81., 20.), labels=[True])
    m.drawmeridians(np.arange(-180., 181., 20.))
    source_coord = add_source(st, m)
    coord_list = stat_coord(st)
    add_station(coord_list, m)
    for ii in range(0, len(coord_list[0]), 2):
        m.drawgreatcircle(source_coord[1],
                          source_coord[0],
                          coord_list[1][ii],
                          coord_list[0][ii],
                          c='k',
                          lw=0.3,
                          alpha=0.3)
    title = os.getcwd().split('/')
    ax = plt.gca()
    x, y = m(st[0].stats.sac['evlo'], st[0].stats.sac['evla'])

    if mt == False:
        try:
            b = beachball(st[0], xy=(x, y), plot='map')
            b.set_zorder(2)
            ax.add_collection(b)
        except KeyError:
            print('No focal mechanism found')
    else:
        b = Beach(mt, width=w, xy=(x, y))
        b.set_zorder(2)
        ax.add_collection(b)

    if title == True:
        ax.set_title('{} \n Depth (km): {} '.format(
            title[5], round(st[0].stats.sac['evdp'], 3)))
    if topo != False:
        myplot.basemap.drawtopography(m, alpha=0.5, cmap=matplotlib.cm.gray)

    if save != False:
        plt.savefig(save + '/map.pdf', format='pdf')
    if save == False:
        plt.show()
示例#3
0
def source_reciever_plot(st, **kwargs):
   """
   Plot source and reciever on map
   """
   save = kwargs.get('save',False)
   topo = kwargs.get('topo',False)
   mt = kwargs.get('moment_tensor',False)
   w = kwargs.get('width',(900000,900000))
   title = kwargs.get('title',True)
   proj = kwargs.get('proj','eck4')

   m = mapplot(proj,lat_0=st[0].stats.sac['evla'],lon_0=st[0].stats.sac['evlo'])
   m.drawparallels(np.arange(-80.,81.,20.),labels=[True])
   m.drawmeridians(np.arange(-180.,181.,20.))
   source_coord = add_source(st,m)
   coord_list = stat_coord(st)
   add_station(coord_list,m)
   for ii in range(0,len(coord_list[0]),2):
       m.drawgreatcircle(source_coord[1],source_coord[0],
       coord_list[1][ii],coord_list[0][ii],c='k',lw=0.3,alpha=0.3)
   title = os.getcwd().split('/')
   ax = plt.gca()
   x,y = m(st[0].stats.sac['evlo'],st[0].stats.sac['evla'])

   if mt == False:
       try:
           b = beachball(st[0],xy=(x,y),plot='map')
           b.set_zorder(2)
           ax.add_collection(b)
       except KeyError:
           print('No focal mechanism found')
   else:
       b = Beach(mt,width=w,xy=(x,y))
       b.set_zorder(2)
       ax.add_collection(b)


   if title == True:
       ax.set_title('{} \n Depth (km): {} '.format(
               title[5],round(st[0].stats.sac['evdp'],3)))
   if topo != False:
       myplot.basemap.drawtopography(m,alpha=0.5,cmap=matplotlib.cm.gray)

   if save != False:
       plt.savefig(save+'/map.pdf',format='pdf')
   if save == False:
       plt.show()
示例#4
0
def plot_events(events, map_object):
    """
    """
    for event in events:
        org = event.preferred_origin() or event.origins[0]
        fm = event.preferred_focal_mechanism() or event.focal_mechanisms[0]
        mt = fm.moment_tensor.tensor

        # Add beachball plot.
        x, y = map_object(org.longitude, org.latitude)

        focmec = [mt.m_rr, mt.m_tt, mt.m_pp, mt.m_rt, mt.m_rp, mt.m_tp]
        # Attempt to calculate the best beachball size.
        width = max((map_object.xmax - map_object.xmin,
            map_object.ymax - map_object.ymin)) * 0.020
        b = Beach(focmec, xy=(x, y), width=width, linewidth=1, facecolor="red")
        b.set_zorder(200000000)
        plt.gca().add_collection(b)
示例#5
0
def plot_events(events, map_object):
    """
    """
    for event in events:
        org = event.preferred_origin() or event.origins[0]
        fm = event.preferred_focal_mechanism() or event.focal_mechanisms[0]
        mt = fm.moment_tensor.tensor

        # Add beachball plot.
        x, y = map_object(org.longitude, org.latitude)

        focmec = [mt.m_rr, mt.m_tt, mt.m_pp, mt.m_rt, mt.m_rp, mt.m_tp]
        # Attempt to calculate the best beachball size.
        width = max((map_object.xmax - map_object.xmin,
                     map_object.ymax - map_object.ymin)) * 0.020
        b = Beach(focmec, xy=(x, y), width=width, linewidth=1, facecolor="red")
        b.set_zorder(200000000)
        plt.gca().add_collection(b)
def plot_mt(mapobj,
            axisobj,
            figobj,
            earthquakes,
            mt,
            event_id,
            location=None,
            M_above=3.0,
            show_above_M=True,
            llat='-90',
            ulat='90',
            llon='-170',
            ulon='190',
            figsize=(12, 8),
            radius=25,
            dist_bt=600,
            mt_width=2,
            angle_step=20,
            show_eq=True,
            par_range=(-90., 120., 30.),
            mer_range=(0, 360, 60),
            pretty=False,
            legend_loc=4,
            title='',
            resolution='l'):
    '''
    Function to plot moment tensors on the map
    Input:
        mapobj - already existing Basemap object onwhich to plot the quakes
        earthquakes - list of earthquake information
        mt - list of focal/moment_tensor information
        event_id - event ID corresponding to the earthquakes 
        location - predefined region, choose from 'US' or 'CA', 
            default is 'None' which will plot the whole world
        M_above - Only show the events with magnitude larger than this number
            default is 5.0, use with show_above_M 
        show_above_M - Flag to turn on the M_above option, default is True, 
        llat - bottom left corner latitude, default is -90
        ulat - upper right corner latitude, default is 90
        llon - bottom left corner longitude, default is -170 
        ulon - upper right corner longitude, default is 190
        figsize - figure size, default is (12,8)
        radius - used in checking collisions (MT), put the MT on a circle with this 
            radius, default is 25
        dist_bt - used in checking collisions (MT), if two events within dist_bt km, 
            then we say it is a collision, default is 600
        angle_step - used in checking collisions (MT), this is to decide the angle 
            step on the circle, default is 20 degree 
        mt_width - size of the MT on the map. Different scale of the map may need 
            different size, play with it.
        show_eq -  flag to show the seismicity as well, default is True
        par_range - range of latitudes you want to label on the map, start lat, end lat
            and step size, default is (-90., 120., 30.),
        mer_range - range of longitudes you want to label on the map, start lon, end lon
            and step size, default is (0, 360, 60),
        pretty - draw a pretty map, default is False to make faster plot
        legend_loc - location of the legend, default is 4
        title - title of the plot
        resolution - resolution of the map,  Possible values are
            * ``"c"`` (crude)
            * ``"l"`` (low)
            * ``"i"`` (intermediate)
            * ``"h"`` (high)
            * ``"f"`` (full)
            Defaults to ``"l"``
    '''

    quakedots = None

    if location == 'US':
        llon = -125
        llat = 20
        ulon = -70
        ulat = 60
        M_above = 4.0
        radius = 5
        dist_bt = 200
        par_range = (20, 60, 15)
        mer_range = (-120, -60, 15)
        mt_width = 0.8
        drawCountries = True

    elif location == 'CAL':
        llat = '30'
        ulat = '45'
        llon = '-130'
        ulon = '-110'
        M_above = 3.0
        radius = 1.5
        dist_bt = 50
        mt_width = 0.3
        drawStates = True
    else:
        location = None

    times = [event[6] for event in earthquakes]

    if show_above_M:
        mags = [row[3] for row in mt]
        index = np.array(mags) >= M_above
        mt_select = np.array(mt)[index]
        evid = np.array(event_id)[index]
        #times_select = np.array(times)[index]
    else:
        evid = [row for row in event_id]
        times_select = times
        mt_select = mt

    lats = [row[0] for row in mt_select]
    lons = [row[1] for row in mt_select]
    depths = [row[2] for row in mt_select]
    mags = [row[3] for row in mt_select]
    focmecs = [row[4:] for row in mt_select]

    lats_m, lons_m, indicator = check_collision(lats, lons, radius, dist_bt,
                                                angle_step)

    #sys.exit(1)

    count = 0

    colors = []

    min_color = 1  #min(times_select) 1
    max_color = 10  #max(times_select) 10
    colormap = plt.get_cmap()

    for i in range(min_color, max_color):
        colors.append(i)

    scal_map = ScalarMappable(norm=cc.Normalize(min_color, max_color),
                              cmap=colormap)
    scal_map.set_array(np.linspace(0, 1, 1))

    colors_plot = [scal_map.to_rgba(c) for c in colors]

    ys = np.array(lats_m)
    xs = np.array(lons_m)
    url = [
        'http://earthquake.usgs.gov/earthquakes/eventpage/' + tmp + '#summary'
        for tmp in evid
    ]

    stnm = np.array(evid)

    #fig, ax1 = plt.subplots(1,1, figsize = figsize)
    #map_ax = fig.add_axes([0.03, 0.13, 0.94, 0.82])

    # if show_eq:
    #     cm_ax = fig.add_axes([0.98, 0.39, 0.04, 0.3])
    #     plt.sca(ax1)
    #     cb = mpl.colorbar.ColorbarBase(ax=cm_ax, cmap=colormap, orientation='vertical')
    #     cb.set_ticks([0, 0.25, 0.5, 0.75, 1.0])
    #     color_range = max_color - min_color
    #     cb.set_ticklabels([_i.strftime('%Y-%b-%d, %H:%M:%S %p')
    #     for _i in [min_color, min_color + color_range * 0.25,
    #        min_color + color_range * 0.50,
    #        min_color + color_range * 0.75, max_color]])

    #m = Basemap(projection='cyl', lon_0=142.36929, lat_0=38.3215, llcrnrlon=llon,llcrnrlat=llat,urcrnrlon=ulon,urcrnrlat=ulat,resolution=resolution)

    #mapobj.drawmapboundary()
    #mapobj.drawcountries()
    #mapobj.drawparallels(np.arange(par_range[0], par_range[1], par_range[2]), labels=[1,0,0,0], linewidth=0)
    #mapobj.drawmeridians(np.arange(mer_range[0],mer_range[1], mer_range[2]), labels=[0,0,0,1], linewidth=0)

    # Plot the earthquake epicenters as points

    x, y = mapobj(lons, lats)
    min_size = 1
    max_size = 8
    min_mag = min(mags)
    max_mag = max(mags)

    if show_eq:
        if len(lats) > 1:
            frac = [(_i - min_mag) / (max_mag - min_mag) for _i in mags]
            magnitude_size = [(_i * (max_size - min_size))**2 for _i in frac]
            magnitude_size = [(_i * min_size / 2)**2 for _i in mags]
        else:
            magnitude_size = 15.0**2
            colors_plot = "red"

        quakedots = mapobj.scatter(x,
                                   y,
                                   marker='o',
                                   s=magnitude_size,
                                   c=colors_plot,
                                   zorder=10)

    print 'Max magnitude ' + str(np.max(mags)), 'Min magnitude ' + str(
        np.min(mags))

    #plot the moment tensor beachballs if available
    x, y = mapobj(lons_m, lats_m)

    mtlineobjs = []
    mtobjs = []

    for i in range(len(focmecs)):

        index = np.where(focmecs[i] == 0)[0]

        #note here, if the mrr is zero, then you will have an error
        #so, change this to a very small number
        if focmecs[i][0] == 0:
            focmecs[i][0] = 0.001

        width = mags[i] * mt_width

        if depths[i] <= 50:
            color = '#FFA500'
            #label_
        elif depths[i] > 50 and depths[i] <= 100:
            color = '#FFFF00'
        elif depths[i] > 100 and depths[i] <= 150:
            color = '#00FF00'
        elif depths[i] > 150 and depths[i] <= 200:
            color = 'b'
        else:
            color = 'r'

        if indicator[i] == 1:
            lineobj = mapobj.plot([lons[i], lons_m[i]], [lats[i], lats_m[i]],
                                  'k')
            #mtlineobjs.append(lineobj)
            #m.plot([10,20],[0,0])
        else:

            lineobj = None

        try:

            b = Beach(focmecs[i],
                      xy=(x[i], y[i]),
                      width=width,
                      linewidth=1,
                      facecolor=color,
                      alpha=1)
            count += 1
            #line = axisobj.plot(x[i],y[i], 'o', picker=5, markersize=30, alpha =0)
            #mtlineobjs.append(line)

        except:
            pass

        #ensure that the MTs are always plotted on top of the earthquakes associated with them
        b.set_zorder(100)
        axisobj.add_collection(b)
        mtobjs.append(b)
        mtlineobjs.append(lineobj)

    d = 2
    circ1 = Line2D([0], [0],
                   linestyle="none",
                   marker="o",
                   alpha=0.6,
                   markersize=10,
                   markerfacecolor="#FFA500")
    circ2 = Line2D([0], [0],
                   linestyle="none",
                   marker="o",
                   alpha=0.6,
                   markersize=10,
                   markerfacecolor="#FFFF00")
    circ3 = Line2D([0], [0],
                   linestyle="none",
                   marker="o",
                   alpha=0.6,
                   markersize=10,
                   markerfacecolor="#00FF00")
    circ4 = Line2D([0], [0],
                   linestyle="none",
                   marker="o",
                   alpha=0.6,
                   markersize=10,
                   markerfacecolor="b")
    circ5 = Line2D([0], [0],
                   linestyle="none",
                   marker="o",
                   alpha=0.6,
                   markersize=10,
                   markerfacecolor="r")

    M4 = Line2D([0], [0],
                linestyle="none",
                marker="o",
                alpha=0.4,
                markersize=4 * d,
                markerfacecolor="k")
    M5 = Line2D([0], [0],
                linestyle="none",
                marker="o",
                alpha=0.4,
                markersize=5 * d,
                markerfacecolor="k")
    M6 = Line2D([0], [0],
                linestyle="none",
                marker="o",
                alpha=0.4,
                markersize=6 * d,
                markerfacecolor="k")
    M7 = Line2D([0], [0],
                linestyle="none",
                marker="o",
                alpha=0.4,
                markersize=7 * d,
                markerfacecolor="k")

    if location == 'World':

        title = str(
            count
        ) + ' events with focal mechanism - color codes depth, size the magnitude'

    elif location == 'US':

        title = 'US events with focal mechanism - color codes depth, size the magnitude'

    elif location == 'CAL':
        title = 'California events with focal mechanism - color codes depth, size the magnitude'
    elif location is None:
        pass

    #handles, labels = axisobj.get_legend_handles_labels()

    #axisobj.legend(handles,labels,(circ1, circ2, circ3, circ4, circ5), ("depth $\leq$ 50 km", "50 km $<$ depth $\leq$ 100 km",
    #                                   "100 km $<$ depth $\leq$ 150 km", "150 km $<$ depth $\leq$ 200 km","200 km $<$ depth"), numpoints=1, loc=legend_loc)

    #plt.title(title)
    #plt.gca().add_artist(legend1)

    #if location == 'World':
    #    axisobj.legend(han,dles,labels(M4,M5,M6,M7), ("M 4.0", "M 5.0", "M 6.0", "M 7.0"), numpoints=1, loc=legend_loc)

    if not quakedots:
        quakedots = False

    return mtlineobjs, mtobjs, quakedots, xs, ys, url
def plot_hist_mt(psmeca_dict,
                 figsize=(16, 24),
                 mt_size=10,
                 pretty=False,
                 resolution='l'):
    if psmeca_dict['psmeca'] != []:
        psmeca = psmeca_dict['psmeca']
        #get the latitudes, longitudes, and the 6 independent component
        lats = psmeca[:, 1]
        lons = psmeca[:, 0]
        focmecs = psmeca[:, 3:9]
        depths = psmeca[:, 2]
        (llat, ulat, llon, ulon) = psmeca_dict['range']
        evla = psmeca_dict['evloc'][0]
        evlo = psmeca_dict['evloc'][1]

        plt.figure(figsize=figsize)
        m = Basemap(projection='cyl',
                    lon_0=142.36929,
                    lat_0=38.3215,
                    llcrnrlon=llon,
                    llcrnrlat=llat,
                    urcrnrlon=ulon,
                    urcrnrlat=ulat,
                    resolution=resolution)

        m.drawcoastlines()
        m.drawmapboundary()

        if pretty:
            m.etopo()
        else:
            m.fillcontinents()

        llat = float(llat)
        ulat = float(ulat)
        llon = float(llon)
        ulon = float(ulon)

        m.drawparallels(np.arange(llat, ulat, (ulat - llat) / 4.0),
                        labels=[1, 0, 0, 0])
        m.drawmeridians(np.arange(llon, ulon, (ulon - llon) / 4.0),
                        labels=[0, 0, 0, 1])

        ax = plt.gca()

        x, y = m(lons, lats)

        for i in range(len(focmecs)):
            '''
            if x[i] < 0:
                x[i] = 360 + x[i]
            '''

            if depths[i] <= 50:
                color = '#FFA500'
                #label_
            elif depths[i] > 50 and depths[i] <= 100:
                color = 'g'
            elif depths[i] > 100 and depths[i] <= 200:
                color = 'b'
            else:
                color = 'r'

            index = np.where(focmecs[i] == 0)[0]

            #note here, if the mrr is zero, then you will have an error
            #so, change this to a very small number
            if focmecs[i][0] == 0:
                focmecs[i][0] = 0.001

            try:
                b = Beach(focmecs[i],
                          xy=(x[i], y[i]),
                          width=mt_size,
                          linewidth=1,
                          facecolor=color)
            except:
                pass

            b.set_zorder(10)
            ax.add_collection(b)

        x_0, y_0 = m(evlo, evla)
        m.plot(x_0, y_0, 'r*', markersize=25)

        circ1 = Line2D([0], [0],
                       linestyle="none",
                       marker="o",
                       alpha=0.6,
                       markersize=10,
                       markerfacecolor="#FFA500")
        circ2 = Line2D([0], [0],
                       linestyle="none",
                       marker="o",
                       alpha=0.6,
                       markersize=10,
                       markerfacecolor="g")
        circ3 = Line2D([0], [0],
                       linestyle="none",
                       marker="o",
                       alpha=0.6,
                       markersize=10,
                       markerfacecolor="b")
        circ4 = Line2D([0], [0],
                       linestyle="none",
                       marker="o",
                       alpha=0.6,
                       markersize=10,
                       markerfacecolor="r")
        plt.legend((circ1, circ2, circ3, circ4),
                   ("depth $\leq$ 50 km", "50 km $<$ depth $\leq$ 100 km",
                    "100 km $<$ depth $\leq$ 200 km", "200 km $<$ depth"),
                   numpoints=1,
                   loc=3)
        plt.show()
    else:
        print 'No historical MT found!'
示例#8
0
# Make gradient plot.
#ps = m.pcolor(x, y, srtm3)
# Make contour plot.
cs = m.contour(x, y, srtm3, 40, colors=".4", lw=0.5, alpha=0.3)
m.drawcountries(color="red", linewidth=1)

# Draw a lon/lat grid (20 lines for an interval of one degree).
m.drawparallels(np.linspace(47, 48, 21), labels=[1,1,0,0], fmt="%.2f",
                dashes=[2,2])
m.drawmeridians(np.linspace(12, 13, 21), labels=[0,0,1,1], fmt="%.2f",
                dashes=[2,2])

# Calculate map projection for the coordinates.
x, y = m(stations_long, stations_lat)
m.scatter(x, y, 200, color="r", marker="v", edgecolor="k", zorder=3)
for i in range(len(stations_id)):
    plt.text(x[i], y[i], " " + stations_id[i], color='k', va="top", 
             family="monospace", weight="bold")

# Calculate map projectoins for the beachballs.
x, y = m(events_long, events_lat)
# Plot the beachballs.
ax = plt.gca()
for i in range(len(events_focmec)):
    b = Beach(events_focmec[i], xy=(x[i], y[i]), width=1000, linewidth=1)
    b.set_zorder(10)
    ax.add_collection(b)

# Save the figure.
plt.savefig("basemap_beachball_example.pdf")
def plot_mt(earthquakes, mt, event_id, location = None, M_above = 5.0, show_above_M = True, 
            llat = '-90', ulat = '90', llon = '-170', ulon = '190', figsize = (12,8),
            radius = 25, dist_bt = 600, mt_width = 2, angle_step = 20, show_eq = True, 
            par_range = (-90., 120., 30.), mer_range = (0, 360, 60),
            pretty = False,  legend_loc = 4, title = '', resolution = 'l'):
    '''
    Function to plot moment tensors on the map
    Input:
        earthquakes - list of earthquake information
        mt - list of focal/moment_tensor information
        event_id - event ID corresponding to the earthquakes 
        location - predefined region, choose from 'US' or 'CA', 
            default is 'None' which will plot the whole world
        M_above - Only show the events with magnitude larger than this number
            default is 5.0, use with show_above_M 
        show_above_M - Flag to turn on the M_above option, default is True, 
        llat - bottom left corner latitude, default is -90
        ulat - upper right corner latitude, default is 90
        llon - bottom left corner longitude, default is -170 
        ulon - upper right corner longitude, default is 190
        figsize - figure size, default is (12,8)
        radius - used in checking collisions (MT), put the MT on a circle with this 
            radius, default is 25
        dist_bt - used in checking collisions (MT), if two events within dist_bt km, 
            then we say it is a collision, default is 600
        angle_step - used in checking collisions (MT), this is to decide the angle 
            step on the circle, default is 20 degree 
        mt_width - size of the MT on the map. Different scale of the map may need 
            different size, play with it.
        show_eq -  flag to show the seismicity as well, default is True
        par_range - range of latitudes you want to label on the map, start lat, end lat
            and step size, default is (-90., 120., 30.),
        mer_range - range of longitudes you want to label on the map, start lon, end lon
            and step size, default is (0, 360, 60),
        pretty - draw a pretty map, default is False to make faster plot
        legend_loc - location of the legend, default is 4
        title - title of the plot
        resolution - resolution of the map,  Possible values are
            * ``"c"`` (crude)
            * ``"l"`` (low)
            * ``"i"`` (intermediate)
            * ``"h"`` (high)
            * ``"f"`` (full)
            Defaults to ``"l"``
    '''
    
    if location == 'US':
        llon=-125
        llat=20
        ulon=-70
        ulat=60
        M_above = 4.0
        radius = 5
        dist_bt = 200 
        par_range = (20, 60, 15)
        mer_range = (-120, -60, 15)
        mt_width = 0.8        
        drawCountries = True
        
    elif location == 'CAL':
        llat = '30'
        ulat = '45'
        llon = '-130'
        ulon = '-110'
        M_above = 3.0
        radius = 1.5
        dist_bt = 50
        mt_width = 0.3
        drawStates = True
    else:
        location = None

    print earthquakes,mt,event_id
        
        
    times = [event[6] for event in earthquakes]  
    
    if show_above_M:
        mags = [row[3] for row in mt]
        index = np.array(mags) >= M_above
        mt_select = np.array(mt)[index]
        evid = np.array(event_id)[index]
        times_select = np.array(times)[index]
    else:
        evid = [row[0] for row in event_id]
        times_select = times
        mt_select = mt
    
    lats = [row[0] for row in mt_select]
    lons = [row[1] for row in mt_select]
    depths = [row[2] for row in mt_select]
    mags =  [row[3] for row in mt_select]
    focmecs = [row[4:] for row in mt_select]
    
    lats_m, lons_m, indicator = check_collision(lats, lons, radius, dist_bt, angle_step)  
    
    count = 0
    
    colors=[]
    
    min_color = min(times_select)
    max_color = max(times_select)
    colormap = plt.get_cmap()
    
    for i in times_select:
        colors.append(i)
    
    scal_map = ScalarMappable(norm=cc.Normalize(min_color, max_color),cmap=colormap)
    scal_map.set_array(np.linspace(0, 1, 1))
    
    colors_plot = [scal_map.to_rgba(c) for c in colors]
     
    ys = np.array(lats_m)
    xs = np.array(lons_m)
    url = ['http://earthquake.usgs.gov/earthquakes/eventpage/' + tmp + '#summary' for tmp in evid]
    
    stnm = np.array(evid)    
    
    fig, ax1 = plt.subplots(1,1, figsize = figsize)
    #map_ax = fig.add_axes([0.03, 0.13, 0.94, 0.82])
    
    if show_eq:
        cm_ax = fig.add_axes([0.98, 0.39, 0.04, 0.3])   
        plt.sca(ax1)
        cb = mpl.colorbar.ColorbarBase(ax=cm_ax, cmap=colormap, orientation='vertical')
        cb.set_ticks([0, 0.25, 0.5, 0.75, 1.0])
        color_range = max_color - min_color
        cb.set_ticklabels([_i.strftime('%Y-%b-%d, %H:%M:%S %p')
        for _i in [min_color, min_color + color_range * 0.25,
           min_color + color_range * 0.50,
           min_color + color_range * 0.75, max_color]])
           
    
    m = Basemap(projection='cyl', lon_0=142.36929, lat_0=38.3215, 
                llcrnrlon=llon,llcrnrlat=llat,urcrnrlon=ulon,urcrnrlat=ulat,resolution=resolution)
    
    m.drawcoastlines()
    m.drawmapboundary()
    m.drawcountries()
    m.drawparallels(np.arange(par_range[0], par_range[1], par_range[2]), labels=[1,0,0,0], linewidth=0)
    m.drawmeridians(np.arange(mer_range[0],mer_range[1], mer_range[2]), labels=[0,0,0,1], linewidth=0)
    
    
    if pretty:    
        m.etopo()
    else:
        m.fillcontinents()
        
    x, y = m(lons_m, lats_m)
    
    for i in range(len(focmecs)):
            
        index = np.where(focmecs[i] == 0)[0]
        
        #note here, if the mrr is zero, then you will have an error
        #so, change this to a very small number 
        if focmecs[i][0] == 0:
            focmecs[i][0] = 0.001
            
        
        width = mags[i] * mt_width
        
        if depths[i] <= 50:
            color = '#FFA500'
            #label_
        elif depths[i] > 50 and depths [i] <= 100:
            color = '#FFFF00'
        elif depths[i] > 100 and depths [i] <= 150:
            color = '#00FF00'
        elif depths[i] > 150 and depths [i] <= 200:
            color = 'b'
        else:
            color = 'r'
                  
        if indicator[i] == 1:
            m.plot([lons[i],lons_m[i]],[lats[i], lats_m[i]], 'k')   
            #m.plot([10,20],[0,0])  
        try:
            
            b = Beach(focmecs[i], xy=(x[i], y[i]),width=width, linewidth=1, facecolor= color, alpha=1)
            count += 1
            line, = ax1.plot(x[i],y[i], 'o', picker=5, markersize=30, alpha =0) 
    
        except:
            pass
        b.set_zorder(3)
        ax1.add_collection(b)
        
        
    d=5
    circ1 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="#FFA500")
    circ2 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="#FFFF00")
    circ3 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="#00FF00")
    circ4 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="b")
    circ5 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="r")
    
    M4 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize= 4*d, markerfacecolor="k")
    M5 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize= 5*d, markerfacecolor="k")
    M6 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize= 6*d, markerfacecolor="k")
    M7 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize= 7*d, markerfacecolor="k")
    
    if location == 'World':
    
        title = str(count) + ' events with focal mechanism - color codes depth, size the magnitude'
        
    elif location == 'US':
    
        title = 'US events with focal mechanism - color codes depth, size the magnitude'
        
    elif location == 'CAL':
        title = 'California events with focal mechanism - color codes depth, size the magnitude'
    elif location is None:
        pass
        
    legend1 = plt.legend((circ1, circ2, circ3, circ4, circ5), ("depth $\leq$ 50 km", "50 km $<$ depth $\leq$ 100 km", 
                                       "100 km $<$ depth $\leq$ 150 km", "150 km $<$ depth $\leq$ 200 km","200 km $<$ depth"), numpoints=1, loc=legend_loc)
    
    plt.title(title)
    plt.gca().add_artist(legend1)
    
    if location == 'World':
        plt.legend((M4,M5,M6,M7), ("M 4.0", "M 5.0", "M 6.0", "M 7.0"), numpoints=1, loc=legend_loc)
        
    x, y = m(lons, lats)
    min_size = 6
    max_size = 30
    min_mag = min(mags)
    max_mag = max(mags)
    
    if show_eq:
        if len(lats) > 1:
            frac = [(_i - min_mag) / (max_mag - min_mag) for _i in mags]
            magnitude_size = [(_i * (max_size - min_size)) ** 2 for _i in frac]
            magnitude_size = [(_i * min_size/2)**2 for _i in mags]
        else:
            magnitude_size = 15.0 ** 2
            colors_plot = "red"
        m.scatter(x, y, marker='o', s=magnitude_size, c=colors_plot,
                zorder=10)
    
    plt.show()
    
    print 'Max magnitude ' + str(np.max(mags)), 'Min magnitude ' + str(np.min(mags))
示例#10
0
def plot_hist_mt(psmeca_dict, figsize = (16,24), mt_size = 10, pretty = False, resolution='l'):
    if psmeca_dict['psmeca'] != []:
        psmeca = psmeca_dict['psmeca']
        #get the latitudes, longitudes, and the 6 independent component
        lats = psmeca[:,1]
        lons = psmeca[:,0]
        focmecs = psmeca[:,3:9]
        depths =  psmeca[:,2]    
        (llat, ulat, llon, ulon) = psmeca_dict['range'] 
        evla = psmeca_dict['evloc'][0]
        evlo = psmeca_dict['evloc'][1]

        plt.figure(figsize=figsize)
        m = Basemap(projection='cyl', lon_0=142.36929, lat_0=38.3215, 
                    llcrnrlon=llon,llcrnrlat=llat,urcrnrlon=ulon,urcrnrlat=ulat,resolution=resolution)
    
        m.drawcoastlines()
        m.drawmapboundary()
    
        if pretty:    
            m.etopo()
        else:
            m.fillcontinents()
    
        llat = float(llat)
        ulat = float(ulat)
        llon = float(llon)
        ulon = float(ulon)
    
        m.drawparallels(np.arange(llat, ulat, (ulat - llat) / 4.0), labels=[1,0,0,0])
        m.drawmeridians(np.arange(llon, ulon, (ulon - llon) / 4.0), labels=[0,0,0,1])   
    
        ax = plt.gca()
    
        x, y = m(lons, lats)
    
        for i in range(len(focmecs)):
            '''
            if x[i] < 0:
                x[i] = 360 + x[i]
            '''
        
            if depths[i] <= 50:
                color = '#FFA500'
                #label_
            elif depths[i] > 50 and depths [i] <= 100:
                color = 'g'
            elif depths[i] > 100 and depths [i] <= 200:
                color = 'b'
            else:
                color = 'r'
        
            index = np.where(focmecs[i] == 0)[0]
        
            #note here, if the mrr is zero, then you will have an error
            #so, change this to a very small number 
            if focmecs[i][0] == 0:
                focmecs[i][0] = 0.001
        
            try:
                b = Beach(focmecs[i], xy=(x[i], y[i]),width=mt_size, linewidth=1, facecolor=color)
            except:
                pass
            
            b.set_zorder(10)
            ax.add_collection(b)
        
        x_0, y_0 = m(evlo, evla)
        m.plot(x_0, y_0, 'r*', markersize=25) 
    
        circ1 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="#FFA500")
        circ2 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="g")
        circ3 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="b")
        circ4 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="r")
        plt.legend((circ1, circ2, circ3, circ4), ("depth $\leq$ 50 km", "50 km $<$ depth $\leq$ 100 km", 
                        "100 km $<$ depth $\leq$ 200 km", "200 km $<$ depth"), numpoints=1, loc=3)
        plt.show()
    else:
        print 'No historical MT found!'
示例#11
0
文件: map.py 项目: iceseismic/sito
def createMap(
    ll=None,
    ur=None,
    figsize=None,
    margin=None,
    ax=None,
    dict_basemap=None,
    countries=True,
    lw=1,
    coastlines=True,
    mapboundary=True,
    grid=False,
    grid_labels=True,
    watercolor="#ADD8E6",
    fillcontinents="coral",
    use_lsmask=False,
    stations=None,
    cities=None,
    trench=None,
    earthquake=None,
    slip=None,
    elevation=None,
    elevation_args=(7000, 500, True),
    elevation_offset=None,
    shaded=True,
    shaded_args=(315, 45, 0.2),
    colormap=None,
    title=None,
    show=True,
    save=None,
    station_markersize=4,
    elev_oceans=True,
    grid_lw=None,
    spines_lw=None,
    dpi=None,
    station_labelsize="small",
    loffset=None,
):
    if figsize:
        fig = plt.figure(figsize=figsize)
        if margin:
            ax = fig.add_axes(margin)
    else:
        fig = None
    if dict_basemap is None:
        dict_basemap = dict(
            llcrnrlon=-180,
            llcrnrlat=-60,
            urcrnrlon=180,
            urcrnrlat=60,
            lat_0=0,
            lon_0=0,
            projection="hammer",
            resolution="l",
        )
    elif ll is not None:
        print dict_basemap
        up_dict = dict(llcrnrlon=ll[1], llcrnrlat=ll[0], urcrnrlon=ur[1], urcrnrlat=ur[0])
        dict_basemap.update(up_dict)
    m = Basemap(ax=ax, **dict_basemap)
    if fillcontinents and use_lsmask:
        m.drawlsmask(land_color=fillcontinents, ocean_color="white")
    elif fillcontinents:
        m.fillcontinents(color=fillcontinents, lake_color=watercolor, zorder=0)
    if countries:
        m.drawcountries(linewidth=lw)
    if coastlines:
        m.drawcoastlines(linewidth=lw)
    if mapboundary:
        m.drawmapboundary(fill_color=watercolor, zorder=-10)
    print 1
    if grid or grid_labels:
        if not grid_lw:
            grid_lw = lw
        if grid is True:
            grid = 1.0
        # JGR
        if grid and grid_labels:
            m.drawparallels(
                np.arange(-90.0, 90.0, grid),
                labels=[True, True, False, False],
                linewidth=grid_lw,
                xoffset=loffset,
                yoffset=loffset,
                size="small",
            )
            m.drawmeridians(
                np.arange(0.0, 390.0, grid),
                labels=[False, False, True, True],
                linewidth=grid_lw,
                xoffset=loffset,
                yoffset=loffset,
                size="small",
            )
        elif grid:
            m.drawparallels(np.arange(-90.0, 90.0, grid), labels=[False, False, False, False], linewidth=grid_lw)
            m.drawmeridians(np.arange(0.0, 390.0, grid), labels=[False, False, False, False], linewidth=grid_lw)
    if stations:
        stations.plot(m, mfc="b", ms=station_markersize, zorder=10, lsize=station_labelsize)
    if slip:
        if len(slip) == 4:
            x, y, z, levels = slip
            colors_slip = None
        else:
            x, y, z, levels, colors_slip = slip
        x, y = zip(*[m(lon, lat) for lon, lat in zip(x, y)])
        if len(np.shape(z)) == 2:
            grid_x = x
            grid_y = y
        else:
            grid_x = np.arange(
                min(x), max(x) - 0.15 * (max(x) - min(x)), 100
            )  # VERY dirty hack to cut of parts of the slip model
            grid_y = np.arange(min(y), max(y), 100)
            # grid_x, grid_y = np.mgrid[min(x):max(x):100j, min(y):max(y):100j]
            z = scipy.interpolate.griddata((x, y), z, (grid_x[None, :], grid_y[:, None]), method="cubic")

        plt.gca().contour(grid_x, grid_y, z, levels, colors=colors_slip, lw=lw)
    if earthquake == "Tocopilla":
        x, y = m(-70.06, -22.34)
        x2, y2 = m(-69.5, -24.2)  # x2, y2 = m(-70.4, -21.5)
        m.plot((x, x2), (y, y2), "k-", lw=lw)  # line
        m.plot((x), (y), "r*", ms=2 * station_markersize, zorder=10)  # epicenter
        b = Beach([358, 26, 109], xy=(x2, y2), width=50000, linewidth=lw)
        b.set_zorder(10)
        plt.gca().add_collection(b)
        plt.annotate(
            "14 Nov. 2007\n M 7.7",
            (x2, y2),
            xytext=(15, 0),  # 22
            textcoords="offset points",
            va="center",
            size=station_labelsize,
        )
    elif earthquake == "Tocopilla_beachball":
        # x, y = m(-70.06, -22.34)
        x2, y2 = m(-69.5, -24.2)  # x2, y2 = m(-70.4, -21.5)
        b = Beach([358, 26, 109], xy=(x2, y2), width=50000, linewidth=lw)
        b.set_zorder(10)
        plt.gca().add_collection(b)
        plt.annotate("14 Nov. 2007\n M 7.6", (x2, y2), xytext=(22, 0), textcoords="offset points", va="center")

    elif earthquake == "Tocopilla_position":
        x, y = m(-70.06, -22.34)
        m.plot((x), (y), "r*", ms=15, zorder=10)  # epicenter
    elif earthquake:
        xs, ys = zip(*[m(lon, lat) for lon, lat in zip(*earthquake[:2])])
        m.plot(xs, ys, "r*", ms=15, zorder=10)  # epicenters
        if len(earthquake) == 3:
            for i in range(len(xs)):
                x, y, mag = xs[i], ys[i], earthquake[2][i]
                plt.annotate("M%.1f" % mag, xy=(x, y), xytext=(-5, -15), textcoords="offset points", va="center")
        elif len(earthquake) > 3:
            for i in range(len(xs)):
                x, y, mag, date = xs[i], ys[i], earthquake[2][i], earthquake[3][i]
                plt.annotate(
                    "M%.1f\n%s" % (mag, date.date), xy=(x, y), xytext=(10, 0), textcoords="offset points", va="center"
                )
    print 2
    if elevation:
        vmax, resol, bar = elevation_args
        geo = gdal.Open(elevation)
        topoin = geo.ReadAsArray()
        if elevation_offset:
            topoin[topoin > 0] += elevation_offset
        coords = geo.GetGeoTransform()
        nlons = topoin.shape[1]
        nlats = topoin.shape[0]
        delon = coords[1]
        delat = coords[5]
        lons = coords[0] + delon * np.arange(nlons)
        lats = coords[3] + delat * np.arange(nlats)[::-1]  # reverse lats
        # create masked array, reversing data in latitude direction
        # (so that data is oriented in increasing latitude,
        # as transform_scalar requires).
        topoin = np.ma.masked_less(topoin[::-1, :], -11000)
        # topoin = gaussian_filter(topoin, 1)
        # topoin = array[::-1, :]
        # transform DEM data to a 250m native projection grid

        #            if True:
        #                x, y = m(*np.meshgrid(lons, lats))
        #                m.contourf(x, y, topoin, 100, cm=colormap)
        #                if save:
        #                    plt.savefig(save)
        #                return
        if resol:
            if resol < 25:
                nx = resol * len(lons)
                ny = resol * len(lats)
            else:
                nx = int((m.xmax - m.xmin) / resol) + 1
                ny = int((m.ymax - m.ymin) / resol) + 1
        else:
            nx = len(lons)
            ny = len(lats)
        topodat = m.transform_scalar(topoin, lons, lats, nx, ny, masked=True)
        if elevation == "CleanTopo2_nchile.tif":
            # -10,701m(0) to 8,248m(18948)
            topodat = topodat - 10701
        if isinstance(colormap, basestring) and os.path.isfile(colormap) and colormap.endswith(".gpf"):
            colormap = createColormapFromGPF(colormap)
        if shaded:
            azdeg, altdeg, fraction = shaded_args
            ls = colors.LightSource(azdeg=azdeg, altdeg=altdeg)
            # convert data to rgb array including shading from light source.
            if elev_oceans:
                rgb = colormap(0.5 * topodat / vmax + 0.5)
            else:
                rgb = colormap(topodat / vmax)
            rgb1 = ls.shade_rgb(rgb, elevation=topodat, fraction=fraction)
            rgb[:, :, 0:3] = rgb1
            m.imshow(rgb, zorder=1)
        else:
            if elev_oceans:
                m.imshow(topodat, interpolation="bilinear", cmap=colormap, zorder=1, vmin=-vmax, vmax=vmax)
            else:
                m.imshow(topodat, interpolation="bilinear", cmap=colormap, zorder=1, vmin=0, vmax=vmax)

        if bar:
            ax = plt.gca()
            fig = plt.gcf()
            # cb_ax = fig.add_axes([0.8, 0.3, 0.02, 0.4])
            cb_ax = fig.add_axes([0.82, 0.3, 0.02, 0.4])
            cb = colorbar.ColorbarBase(cb_ax, cmap=colormap, norm=colors.Normalize(vmin=-vmax, vmax=vmax))
            # cb.set_label('elevation and bathymetry')
            ticks = (np.arange(20) - 10) * 1000
            ticks = ticks[np.abs(ticks) <= vmax]
            cb.set_ticks(ticks)
            tls = ["%dm" % i if i % 2000 == 0 else "" for i in ticks]
            cb.set_ticklabels(tls)
            plt.axes(ax)  # make the original axes current again
    if cities == "ipoc":
        cities = "Antofagasta Tocopilla Iquique Calama Pisagua Arica".split()
        lons = [-70.4, -70.2, -70.1525, -68.933333, -70.216667, -70.333333]
        lats = [-23.65, -22.096389, -20.213889, -22.466667, -19.6, -18.483333]
        x, y = m(lons[: len(cities)], lats[: len(cities)])
        m.plot(x, y, "o", ms=station_markersize, mfc="w", mec="k", zorder=10)
        for i in range(len(cities)):
            if "Anto" in cities[i]:
                plt.annotate(
                    cities[i], (x[i], y[i]), xytext=(5, 0), textcoords="offset points", va="top", size=station_labelsize
                )
            else:
                plt.annotate(
                    cities[i],
                    (x[i], y[i]),
                    xytext=(-5, 0),
                    textcoords="offset points",
                    ha="right",
                    size=station_labelsize,
                )
    elif cities == "Tocopilla":
        lons = [-70.2]
        lats = [-22.096389]
        x, y = m(lons, lats)
        m.plot(x, y, "o", ms=station_markersize, mfc="w", mec="k", zorder=10)
        plt.annotate("Tocopilla", (x[0], y[0]), xytext=(5, 0), textcoords="offset points", size=station_labelsize)

    if trench == "ipoc":
        coords = np.transpose(np.loadtxt("/home/richter/Data/map/" "nchile_trench.txt"))
        import matplotlib as mpl  # hack JGR

        mpl.rcParams.update({"lines.linewidth": 1})
        plotTrench(m, coords[0, :], coords[1, :], facecolors="k", edgecolors="k")
    if spines_lw:
        for l in plt.gca().spines.values():
            l.set_linewidth(spines_lw)
    if title:
        plt.title(title, y=1.05)
    if save:
        plt.savefig(save, dpi=dpi)
    if show:
        plt.show()
    return m
示例#12
0
文件: map.py 项目: wangwu1991/sito
def createMap(ll=None,
              ur=None,
              figsize=None,
              margin=None,
              ax=None,
              dict_basemap=None,
              countries=True,
              lw=1,
              coastlines=True,
              mapboundary=True,
              grid=False,
              grid_labels=True,
              watercolor='#ADD8E6',
              fillcontinents='coral',
              use_lsmask=False,
              stations=None,
              cities=None,
              trench=None,
              earthquake=None,
              slip=None,
              elevation=None,
              elevation_args=(7000, 500, True),
              elevation_offset=None,
              shaded=True,
              shaded_args=(315, 45, 0.2),
              colormap=None,
              title=None,
              show=True,
              save=None,
              station_markersize=4,
              elev_oceans=True,
              grid_lw=None,
              spines_lw=None,
              dpi=None,
              station_labelsize='small',
              loffset=None):
    if figsize:
        fig = plt.figure(figsize=figsize)
        if margin:
            ax = fig.add_axes(margin)
    else:
        fig = None
    if dict_basemap is None:
        dict_basemap = dict(llcrnrlon=-180,
                            llcrnrlat=-60,
                            urcrnrlon=180,
                            urcrnrlat=60,
                            lat_0=0,
                            lon_0=0,
                            projection='hammer',
                            resolution='l')
    elif ll is not None:
        print dict_basemap
        up_dict = dict(llcrnrlon=ll[1],
                       llcrnrlat=ll[0],
                       urcrnrlon=ur[1],
                       urcrnrlat=ur[0])
        dict_basemap.update(up_dict)
    m = Basemap(ax=ax, **dict_basemap)
    if fillcontinents and use_lsmask:
        m.drawlsmask(land_color=fillcontinents, ocean_color='white')
    elif fillcontinents:
        m.fillcontinents(color=fillcontinents, lake_color=watercolor, zorder=0)
    if countries:
        m.drawcountries(linewidth=lw)
    if coastlines:
        m.drawcoastlines(linewidth=lw)
    if mapboundary:
        m.drawmapboundary(fill_color=watercolor, zorder=-10)
    print 1
    if grid or grid_labels:
        if not grid_lw:
            grid_lw = lw
        if grid is True:
            grid = 1.
        #JGR
        if grid and grid_labels:
            m.drawparallels(np.arange(-90., 90., grid),
                            labels=[True, True, False, False],
                            linewidth=grid_lw,
                            xoffset=loffset,
                            yoffset=loffset,
                            size='small')
            m.drawmeridians(np.arange(0., 390., grid),
                            labels=[False, False, True, True],
                            linewidth=grid_lw,
                            xoffset=loffset,
                            yoffset=loffset,
                            size='small')
        elif grid:
            m.drawparallels(np.arange(-90., 90., grid),
                            labels=[False, False, False, False],
                            linewidth=grid_lw)
            m.drawmeridians(np.arange(0., 390., grid),
                            labels=[False, False, False, False],
                            linewidth=grid_lw)
    if stations:
        stations.plot(m,
                      mfc='b',
                      ms=station_markersize,
                      zorder=10,
                      lsize=station_labelsize)
    if slip:
        if len(slip) == 4:
            x, y, z, levels = slip
            colors_slip = None
        else:
            x, y, z, levels, colors_slip = slip
        x, y = zip(*[m(lon, lat) for lon, lat in zip(x, y)])
        if len(np.shape(z)) == 2:
            grid_x = x
            grid_y = y
        else:
            grid_x = np.arange(
                min(x),
                max(x) - 0.15 * (max(x) - min(x)),
                100)  #VERY dirty hack to cut of parts of the slip model
            grid_y = np.arange(min(y), max(y), 100)
            #grid_x, grid_y = np.mgrid[min(x):max(x):100j, min(y):max(y):100j]
            z = scipy.interpolate.griddata((x, y),
                                           z,
                                           (grid_x[None, :], grid_y[:, None]),
                                           method='cubic')

        plt.gca().contour(grid_x, grid_y, z, levels, colors=colors_slip, lw=lw)
    if earthquake == 'Tocopilla':
        x, y = m(-70.06, -22.34)
        x2, y2 = m(-69.5, -24.2)  #x2, y2 = m(-70.4, -21.5)
        m.plot((x, x2), (y, y2), 'k-', lw=lw)  #line
        m.plot((x), (y), 'r*', ms=2 * station_markersize,
               zorder=10)  #epicenter
        b = Beach([358, 26, 109], xy=(x2, y2), width=50000, linewidth=lw)
        b.set_zorder(10)
        plt.gca().add_collection(b)
        plt.annotate(
            '14 Nov. 2007\n M 7.7',
            (x2, y2),
            xytext=(15, 0),  # 22
            textcoords='offset points',
            va='center',
            size=station_labelsize)
    elif earthquake == 'Tocopilla_beachball':
        #x, y = m(-70.06, -22.34)
        x2, y2 = m(-69.5, -24.2)  #x2, y2 = m(-70.4, -21.5)
        b = Beach([358, 26, 109], xy=(x2, y2), width=50000, linewidth=lw)
        b.set_zorder(10)
        plt.gca().add_collection(b)
        plt.annotate('14 Nov. 2007\n M 7.6', (x2, y2),
                     xytext=(22, 0),
                     textcoords='offset points',
                     va='center')

    elif earthquake == 'Tocopilla_position':
        x, y = m(-70.06, -22.34)
        m.plot((x), (y), 'r*', ms=15, zorder=10)  #epicenter
    elif earthquake:
        xs, ys = zip(*[m(lon, lat) for lon, lat in zip(*earthquake[:2])])
        m.plot(xs, ys, 'r*', ms=15, zorder=10)  #epicenters
        if len(earthquake) == 3:
            for i in range(len(xs)):
                x, y, mag = xs[i], ys[i], earthquake[2][i]
                plt.annotate('M%.1f' % mag,
                             xy=(x, y),
                             xytext=(-5, -15),
                             textcoords='offset points',
                             va='center')
        elif len(earthquake) > 3:
            for i in range(len(xs)):
                x, y, mag, date = xs[i], ys[i], earthquake[2][i], earthquake[
                    3][i]
                plt.annotate('M%.1f\n%s' % (mag, date.date),
                             xy=(x, y),
                             xytext=(10, 0),
                             textcoords='offset points',
                             va='center')
    print 2
    if elevation:
        vmax, resol, bar = elevation_args
        geo = gdal.Open(elevation)
        topoin = geo.ReadAsArray()
        if elevation_offset:
            topoin[topoin > 0] += elevation_offset
        coords = geo.GetGeoTransform()
        nlons = topoin.shape[1]
        nlats = topoin.shape[0]
        delon = coords[1]
        delat = coords[5]
        lons = coords[0] + delon * np.arange(nlons)
        lats = coords[3] + delat * np.arange(nlats)[::-1]  # reverse lats
        # create masked array, reversing data in latitude direction
        # (so that data is oriented in increasing latitude,
        # as transform_scalar requires).
        topoin = np.ma.masked_less(topoin[::-1, :], -11000)
        #topoin = gaussian_filter(topoin, 1)
        #topoin = array[::-1, :]
        # transform DEM data to a 250m native projection grid

        #            if True:
        #                x, y = m(*np.meshgrid(lons, lats))
        #                m.contourf(x, y, topoin, 100, cm=colormap)
        #                if save:
        #                    plt.savefig(save)
        #                return
        if resol:
            if resol < 25:
                nx = resol * len(lons)
                ny = resol * len(lats)
            else:
                nx = int((m.xmax - m.xmin) / resol) + 1
                ny = int((m.ymax - m.ymin) / resol) + 1
        else:
            nx = len(lons)
            ny = len(lats)
        topodat = m.transform_scalar(topoin, lons, lats, nx, ny, masked=True)
        if elevation == 'CleanTopo2_nchile.tif':
            # -10,701m(0) to 8,248m(18948)
            topodat = topodat - 10701
        if (isinstance(colormap, basestring) and os.path.isfile(colormap)
                and colormap.endswith('.gpf')):
            colormap = createColormapFromGPF(colormap)
        if shaded:
            azdeg, altdeg, fraction = shaded_args
            ls = colors.LightSource(azdeg=azdeg, altdeg=altdeg)
            # convert data to rgb array including shading from light source.
            if elev_oceans:
                rgb = colormap(0.5 * topodat / vmax + 0.5)
            else:
                rgb = colormap(topodat / vmax)
            rgb1 = ls.shade_rgb(rgb, elevation=topodat, fraction=fraction)
            rgb[:, :, 0:3] = rgb1
            m.imshow(rgb, zorder=1)
        else:
            if elev_oceans:
                m.imshow(topodat,
                         interpolation='bilinear',
                         cmap=colormap,
                         zorder=1,
                         vmin=-vmax,
                         vmax=vmax)
            else:
                m.imshow(topodat,
                         interpolation='bilinear',
                         cmap=colormap,
                         zorder=1,
                         vmin=0,
                         vmax=vmax)

        if bar:
            ax = plt.gca()
            fig = plt.gcf()
            #cb_ax = fig.add_axes([0.8, 0.3, 0.02, 0.4])
            cb_ax = fig.add_axes([0.82, 0.3, 0.02, 0.4])
            cb = colorbar.ColorbarBase(cb_ax,
                                       cmap=colormap,
                                       norm=colors.Normalize(vmin=-vmax,
                                                             vmax=vmax))
            #cb.set_label('elevation and bathymetry')
            ticks = (np.arange(20) - 10) * 1000
            ticks = ticks[np.abs(ticks) <= vmax]
            cb.set_ticks(ticks)
            tls = ['%dm' % i if i % 2000 == 0 else '' for i in ticks]
            cb.set_ticklabels(tls)
            plt.axes(ax)  # make the original axes current again
    if cities == 'ipoc':
        cities = 'Antofagasta Tocopilla Iquique Calama Pisagua Arica'.split()
        lons = [-70.4, -70.2, -70.1525, -68.933333, -70.216667, -70.333333]
        lats = [-23.65, -22.096389, -20.213889, -22.466667, -19.6, -18.483333]
        x, y = m(lons[:len(cities)], lats[:len(cities)])
        m.plot(x, y, 'o', ms=station_markersize, mfc='w', mec='k', zorder=10)
        for i in range(len(cities)):
            if 'Anto' in cities[i]:
                plt.annotate(cities[i], (x[i], y[i]),
                             xytext=(5, 0),
                             textcoords='offset points',
                             va='top',
                             size=station_labelsize)
            else:
                plt.annotate(cities[i], (x[i], y[i]),
                             xytext=(-5, 0),
                             textcoords='offset points',
                             ha='right',
                             size=station_labelsize)
    elif cities == 'Tocopilla':
        lons = [-70.2]
        lats = [-22.096389]
        x, y = m(lons, lats)
        m.plot(x, y, 'o', ms=station_markersize, mfc='w', mec='k', zorder=10)
        plt.annotate('Tocopilla', (x[0], y[0]),
                     xytext=(5, 0),
                     textcoords='offset points',
                     size=station_labelsize)

    if trench == 'ipoc':
        coords = np.transpose(
            np.loadtxt('/home/richter/Data/map/'
                       'nchile_trench.txt'))
        import matplotlib as mpl  # hack JGR
        mpl.rcParams.update({'lines.linewidth': 1})
        plotTrench(m,
                   coords[0, :],
                   coords[1, :],
                   facecolors='k',
                   edgecolors='k')
    if spines_lw:
        for l in plt.gca().spines.values():
            l.set_linewidth(spines_lw)
    if title:
        plt.title(title, y=1.05)
    if save:
        plt.savefig(save, dpi=dpi)
    if show:
        plt.show()
    return m
示例#13
0
文件: mapa.py 项目: ndperezg/mapa_foc
from obspy.imaging.beachball import Beach

focmec, lat, lon = [], [], []
datos = open('datos.txt')

counter = 0
for line in datos:
    if counter > 0:
        focmec.append([float(line.split('\t')[7]),float(line.split('\t')[9]),float(line.split('\t')[9])])
        lat.append(float(line.split('\t')[1]))
        lon.append(float(line.split('\t')[2]))
    counter+= 1



map = Basemap(llcrnrlon=-83.5,llcrnrlat=-4.5,urcrnrlon=-76,urcrnrlat=6, projection='cyl', resolution=None)
#map.drawcoastlines()



x, y = map(lon, lat)
#map.scatter(x, y, 200, color="r", marker="v", edgecolor="k", zorder=3)

ax = plt.gca()
for i in range(len(focmec)):
    b = Beach(focmec[i], xy=(x[i], y[i]), width=0.35, linewidth=1)
    b.set_zorder(1)
    ax.add_collection(b)

map.arcgisimage(service='NatGeo_World_Map', xpixels = 1500, verbose= True)
plt.show()