def collection_aspect(self, axis, filename_width, filename_width_height): """ Common part of the test_collection_aspect_[xy] tests. """ mt = [0.91, -0.89, -0.02, 1.78, -1.55, 0.47] # Test passing only a width # Initialize figure fig = plt.figure() ax = fig.add_subplot(111) # add the beachball (a collection of two patches) to the axis # give it an axes to keep make the beachballs circular # even though axes are not scaled ax.add_collection(beach(mt, width=400, xy=(0, 0), linewidth=.6, axes=ax)) # set the x and y limits ax.axis(axis) # create and compare image with ImageComparison(self.path, filename_width) as ic: fig.savefig(ic.name) # Test passing a width and a height # Initialize figure fig = plt.figure() ax = fig.add_subplot(111) # add the beachball (a collection of two patches) to the axis # give it an axes to keep make the beachballs circular # even though axes are not scaled ax.add_collection(beach(mt, width=(400, 200), xy=(0, 0), linewidth=.6, axes=ax)) # set the x and y limits and save the output ax.axis(axis) # create and compare image with ImageComparison(self.path, filename_width_height) as ic: fig.savefig(ic.name)
def collection_aspect(self, axis, image_path): """ Common part of the test_collection_aspect_[xy] tests. """ mt = [0.91, -0.89, -0.02, 1.78, -1.55, 0.47] filename_width = image_path.parent / 'width.png' # Test passing only a width # Initialize figure fig = plt.figure() ax = fig.add_subplot(111) # add the beachball (a collection of two patches) to the axis # give it an axes to keep make the beachballs circular # even though axes are not scaled ax.add_collection( beach(mt, width=400, xy=(0, 0), linewidth=.6, axes=ax)) # set the x and y limits ax.axis(axis) fig.savefig(filename_width) # Test passing a width and a height filename_height = image_path.parent / 'height.png' # Initialize figure fig = plt.figure() ax = fig.add_subplot(111) # add the beachball (a collection of two patches) to the axis # give it an axes to keep make the beachballs circular # even though axes are not scaled ax.add_collection( beach(mt, width=(400, 200), xy=(0, 0), linewidth=.6, axes=ax)) # set the x and y limits ax.axis(axis) # save the output fig.savefig(filename_height)
def plot_si_bb_comp(ax, cmt, cmt_init, tag): # get moment tensor mt = [cmt.m_rr, cmt.m_tt, cmt.m_pp, cmt.m_rt, cmt.m_rp, cmt.m_tp] # plot beach ball b = beach(mt, linewidth=1, xy=(0, 0.6), width=1, size=2, facecolor='r') ax.add_collection(b) # set axis ax.set_xlim([-1, 1]) ax.set_ylim([-1, 1.5]) ax.set_aspect('equal') # magnitude text = r"$\Delta$Mw=%4.3f" % (cmt.moment_magnitude - cmt_init.moment_magnitude) plt.text(-0.9, -0.3, text, fontsize=7) # lat and lon text = r"$\Delta$lat=%6.3f$^\circ$; $\Delta$lon=%6.3f$^\circ$" \ % (cmt.latitude-cmt_init.latitude, cmt.longitude-cmt_init.longitude) plt.text(-0.9, -0.5, text, fontsize=7) # depth text = r"$\Delta$dep=%6.3f km;" % ( (cmt.depth_in_m - cmt_init.depth_in_m) / 1000.0) plt.text(-0.9, -0.7, text, fontsize=7) ax.set_xticks([]) ax.set_yticks([]) text = tag plt.text(-0.9, 1.3, text, fontsize=7)
def event_beachball_durationmap(event_id, m, anno=False): """plot event beachball on basemap 'm' object for a given geonet event_id most events are yshift=.025 xshift=-.0775 if annotation sits above if below yshift=-.0675 xshift=-.0825 right justified .025 -.15 2015p768477: .025 -.1275 yshift :type anno: bool :param anno: if to annotate the event information next to beachball """ from obspy.imaging.beachball import beach MT = getdata.get_moment_tensor(event_id) eventx, eventy = m(MT['Longitude'], MT['Latitude']) FM = [MT['strike2'], MT['dip2'], MT['rake2']] b = beach(FM, xy=(eventx, eventy), width=2.5E4, linewidth=1, facecolor='r') b.set_zorder(1000) ax = plt.gca() ax.add_collection(b) if anno: yshift = -.079 * (m.ymax - m.ymin) xshift = -.0825 * (m.xmax - m.xmin) plt.annotate("M{m}\n{e}\n(depth: {d:} km)".format(m=MT['Mw'], e=event_id, d=int(MT['CD'])), xy=(eventx, eventy), xytext=(eventx + xshift, eventy + yshift), fontsize=10, zorder=200, weight='bold', multialignment='center')
def plot_si_bb_comp(ax, cmt, cmt_init, tag): # get moment tensor mt = [cmt.m_rr, cmt.m_tt, cmt.m_pp, cmt.m_rt, cmt.m_rp, cmt.m_tp] # plot beach ball b = beach(mt, linewidth=1, xy=(0, 0.6), width=1, size=2, facecolor='r') ax.add_collection(b) # set axis ax.set_xlim([-1, 1]) ax.set_ylim([-1, 1.5]) ax.set_aspect('equal') # magnitude text = r"$\Delta$Mw=%4.3f" % ( cmt.moment_magnitude-cmt_init.moment_magnitude) plt.text(-0.9, -0.3, text, fontsize=7) # lat and lon text = r"$\Delta$lat=%6.3f$^\circ$; $\Delta$lon=%6.3f$^\circ$" \ % (cmt.latitude-cmt_init.latitude, cmt.longitude-cmt_init.longitude) plt.text(-0.9, -0.5, text, fontsize=7) # depth text = r"$\Delta$dep=%6.3f km;" % ( (cmt.depth_in_m-cmt_init.depth_in_m)/1000.0) plt.text(-0.9, -0.7, text, fontsize=7) ax.set_xticks([]) ax.set_yticks([]) text = tag plt.text(-0.9, 1.3, text, fontsize=7)
def event_beachball(m, event, fm_type="focal_mechanism", zorder=90, **kwargs): """ Plot event beachball for a given moment tensor attribute from event object. Note: if strike_dip_rake chosen, nodal plane 1 is used for focal mechanism, assuming that is the preferred plane :type m: Basemap :param m: basemap object :type fm_type: str :param fm_type: focal mech. type, "focal_mechanism" or "strike_dip_rake" :type event: obspy.core.event.Event :param event: event object which should contain focal mechanism """ width = kwargs.get("src_width", 2.6E4) src_marker = kwargs.get("src_marker", "o") src_markercolor = kwargs.get("src_markercolor", "r") src_markersize = kwargs.get("src_markersize", 105) src_linewidth = kwargs.get("src_linewidth", 1.75) eventx, eventy = m(event.preferred_origin().longitude, event.preferred_origin().latitude) # No focal mechanism? Just plot a ploint, same as connect_source_receiver() if not hasattr(event, "focal_mechanisms"): m.scatter(eventx, eventy, marker=src_marker, color=src_markercolor, edgecolor="k", s=src_markersize, linewidth=src_linewidth, zorder=90) else: if fm_type == "focal_mechanism": fm = event.focal_mechanisms[0].moment_tensor.tensor or \ event.preferred_focal_mechanism().moment_tensor.tensor beach_input = [ fm["m_rr"], fm["m_tt"], fm["m_pp"], fm["m_rt"], fm["m_rp"], fm["m_tp"] ] elif fm_type == "strike_dip_rake": nod_plane = event.focal_mechanisms[0].nodal_planes or \ event.preferred_focal_mechanism().nodal_planes # try determine the preferred nodal plane, default to 1 try: sdr = nod_plane[f"nodal_plane_{nod_plane.preferred_plane}"] except AttributeError: sdr = nod_plane.nodal_plane_1 beach_input = [sdr.strike, sdr.dip, sdr.rake] b = beach(beach_input, xy=(eventx, eventy), width=width, linewidth=src_linewidth, facecolor=src_markercolor) b.set_zorder(zorder) ax = plt.gca() ax.add_collection(b)
def event_beachball(m, event): """ Plot event beachball for a given geonet moment tensor list, read in the from the GeoNet moment tensor csv file. :type m: Basemap :param m: basemap object :type event: obspy.core.event.Event :param event: event object which should contain focal mechanism """ eventx, eventy = m(event.preferred_origin().longitude, event.preferred_origin().latitude) focal_mechanism = [ event.preferred_focal_mechanism().moment_tensor.tensor['m_rr'], event.preferred_focal_mechanism().moment_tensor.tensor['m_tt'], event.preferred_focal_mechanism().moment_tensor.tensor['m_pp'], event.preferred_focal_mechanism().moment_tensor.tensor['m_rt'], event.preferred_focal_mechanism().moment_tensor.tensor['m_rp'], event.preferred_focal_mechanism().moment_tensor.tensor['m_tp'] ] b = beach(focal_mechanism, xy=(eventx, eventy), width=10, linewidth=1, facecolor='r') b.set_zorder(1000) ax = plt.gca() ax.add_collection(b)
def _plot_hypo(ax, hypo): geodetic_transform = ccrs.PlateCarree() try: strike = hypo.strike dip = hypo.dip rake = hypo.rake xy = ax.projection.transform_point(hypo.longitude, hypo.latitude, geodetic_transform) meca = beach((strike, dip, rake), xy=xy, width=30, linewidth=1, facecolor='k', zorder=10, axes=ax) ax.add_collection(meca) except AttributeError: # plot hypocenter as a star ax.plot(hypo.longitude, hypo.latitude, marker='*', markersize=20, markeredgewidth=1, markeredgecolor='white', color='k', transform=geodetic_transform, zorder=10)
def plot_data(self, data, M, mag=None): # If data is Nxsides, newdata is Nx2. if self.scaling: # Scales data for you. tridata = np.dot((data.T / data.sum(-1)).T, self.basis) else: # Assumes data already sums to 1. tridata = np.dot(data, self.basis) ''' self.ax.plot(tridata[:,0], tridata[:,1], marker='o', ms=10, alpha=0.8, color='r') ''' if mag: width = mag * 0.05 else: width = 0.09 b = beach(M, xy=(tridata[:, 0], tridata[:, 1]), width=width, linewidth=1, facecolor='r') b.set_zorder(1) self.ax.add_collection(b)
def plot_global_map(self): """ Plot global map of event and stations """ # ax = plt.subplot(211) plt.title(self.cmtsource.eventname) m = Basemap(projection='cyl', lon_0=0.0, lat_0=0.0, resolution='c') m.drawcoastlines() m.fillcontinents() m.drawparallels(np.arange(-90., 120., 30.)) m.drawmeridians(np.arange(0., 420., 60.)) m.drawmapboundary() x, y = m(self.sta_lon, self.sta_lat) m.scatter(x, y, 30, color="r", marker="^", edgecolor="k", linewidth='0.3', zorder=3) cmt_lat = self.cmtsource.latitude cmt_lon = self.cmtsource.longitude focmecs = get_cmt_par(self.cmtsource)[:6] ax = plt.gca() bb = beach(focmecs, xy=(cmt_lon, cmt_lat), width=20, linewidth=1, alpha=1.0) bb.set_zorder(10) ax.add_collection(bb)
def plot_cmts(self): ax = plt.gca() for idx, (lon, lat, m) in enumerate( zip(self.longitude, self.latitude, self.ncmt[:, 1:7])): try: # Longitude fix because cartopy is being shitty if self.cl == 180.0: if lon <= 0: lon = lon + 180.0 else: lon = lon - 180.0 b = beach( m, linewidth=0.25, facecolor=get_color(self.dCMT[idx, 7], cmap=self.cmt_cmap, vmin=-self.dd_absmax, vmax=self.dd_absmax), bgcolor='w', edgecolor='k', alpha=1, xy=(lon, lat), width=10, size=10, nofill=False, zorder=-1, axes=ax, ) ax.add_collection(b) except Exception as e: for line in e.__str__().splitlines(): logger.error(line)
def plot_si_bb(ax, cmt): # get moment tensor mt = [cmt.m_rr, cmt.m_tt, cmt.m_pp, cmt.m_rt, cmt.m_rp, cmt.m_tp] # plot beach ball b = beach(mt, linewidth=1, xy=(0, 0.6), width=1, size=2, facecolor='r') ax.add_collection(b) # set axis ax.set_xlim([-1, 1]) ax.set_ylim([-1, 1.5]) ax.set_aspect('equal') # magnitude text = "Mw=%4.3f" % cmt.moment_magnitude plt.text(-0.9, -0.3, text, fontsize=7) # lat and lon text = "lat=%6.3f$^\\circ$; lon=%6.3f$^\\circ$" \ % (cmt.latitude, cmt.longitude) plt.text(-0.9, -0.5, text, fontsize=7) # depth text = "dep=%6.3f km;" % (cmt.depth_in_m / 1000.0) plt.text(-0.9, -0.7, text, fontsize=7) ax.set_xticks([]) ax.set_yticks([]) # title text = "Init CMT" plt.text(-0.9, 1.3, text, fontsize=7)
def plot_bb(ax): axb = fig.add_axes(ax.get_position().bounds, aspect='equal') axb.axison = False b = beach(sdr_mean, width=20, nofill=True, linewidth=1) axb.add_collection(b) axb.set_xlim(-10, 10) axb.set_ylim(-10, 10) return axb
def test_collection(self): """ Tests to plot beachballs as collection into an existing axis object. The moment tensor values are taken form the test_Beachball unit test. See that test for more information about the parameters. """ mt = [[0.91, -0.89, -0.02, 1.78, -1.55, 0.47], [274, 13, 55], [130, 79, 98], [264.98, 45.00, -159.99], [160.55, 76.00, -46.78], [1.45, -6.60, 5.14, -2.67, -3.16, 1.36], [235, 80, 35], [138, 56, 168], [1, 1, 1, 0, 0, 0], [-1, -1, -1, 0, 0, 0], [1, -2, 1, 0, 0, 0], [1, -1, 0, 0, 0, 0], [1, -1, 0, 0, 0, -1], [179, 55, -78], [10, 42.5, 90], [10, 42.5, 92], [150, 87, 1], [0.99, -2.00, 1.01, 0.92, 0.48, 0.15], [5.24, -6.77, 1.53, 0.81, 1.49, -0.05], [16.578, -7.987, -8.592, -5.515, -29.732, 7.517], [-2.39, 1.04, 1.35, 0.57, -2.94, -0.94], [150, 87, 1]] # Initialize figure try: plt.close("all") except: pass fig = plt.figure(figsize=(6, 6), dpi=300) ax = fig.add_subplot(111, aspect='equal') # Plot the stations or borders ax.plot([-100, -100, 100, 100], [-100, 100, -100, 100], 'rv') x = -100 y = -100 for i, t in enumerate(mt): # add the beachball (a collection of two patches) to the axis ax.add_collection(beach(t, width=30, xy=(x, y), linewidth=.6)) x += 50 if (i + 1) % 5 == 0: x = -100 y += 50 # set the x and y limits and save the output ax.axis([-120, 120, -120, 120]) # create and compare image with ImageComparison(self.path, 'bb_collection.png', plt_close_all_enter=False) as ic: fig.savefig(ic.name)
def mt_plot(): """ Return a moment tensor image. """ formats = { "png": "image/png", "svg": "image/svg+xml" } args = flask.request.args m_rr = float(args["m_rr"]) m_tt = float(args["m_tt"]) m_pp = float(args["m_pp"]) m_rt = float(args["m_rt"]) m_rp = float(args["m_rp"]) m_tp = float(args["m_tp"]) focmec = (m_rr, m_tt, m_pp, m_rt, m_rp, m_tp) # Allow hexcolors. color = args.get("color", "red") try: hexcolor = "#" + color hex2color(hexcolor) color = hexcolor except ValueError: pass size = int(args.get("size", 32)) lw = float(args.get("lw", 1)) format = args.get("format", "png") if format not in formats.keys(): flask.abort(500) dpi = 100 fig = plt.figure(figsize=(float(size) / float(dpi), float(size) / float(dpi)), dpi=dpi) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) bb = beach(focmec, xy=(0, 0), width=200, linewidth=lw, facecolor=color) ax.add_collection(bb) ax.set_xlim(-105, 105) ax.set_ylim(-105, 105) temp = io.BytesIO() plt.savefig(temp, format=format, dpi=dpi, transparent=True) plt.close(fig) plt.close("all") temp.seek(0, 0) return flask.send_file(temp, mimetype=formats[format], add_etags=False, attachment_filename="mt.%s" % format)
def maps(station_list, origin, strike, dip, rake, plot_file): """ Plotting a map with epicenter and possible stations according to distance and a map with with the beachball """ # sets figure's dimensions _fig_x = 10 _fig_y = 10 fig = plt.figure(figsize=(_fig_x,_fig_y)) # calculating map space _max = max(_station.distance_by_origin for _station in station_list) _max = int(round(_max * 1000 *2)) _size = _max + int(round(_max/7.0)) _diff = kilometer2degrees(round(_size/(2*2.0*1000))) parallels = [round(origin.latitude,2), round((origin.latitude-_diff),2), round((origin.latitude+_diff),2)] meridians = [round(origin.longitude,2), round((origin.longitude-_diff),2), round((origin.longitude+_diff),2)] m = Basemap(projection='laea', lat_0 = origin.latitude, lon_0 = origin.longitude, lat_ts=origin.latitude, resolution = 'i', area_thresh = 0.1, width = _size, height = _size) m.drawparallels(parallels,labels=[1,0,0,0], color='grey', fontsize=10) m.drawmeridians(meridians,labels=[0,0,0,1], color='grey', fontsize=10) m.drawrivers(color='aqua') m.drawcoastlines(color='0.2') m.drawcountries(color='0.4') m.drawmapboundary(fill_color='aqua') m.fillcontinents(color='coral',lake_color='aqua') x,y = m(origin.longitude, origin.latitude) # epicenter m.scatter(x, y, 1, color="#FFFF00", marker="*", zorder=3, linewidths=2, edgecolor="k") # beachball ax = plt.gca() b = beach.beach([strike, dip, rake], xy=(x,y), width=35000, linewidth=1, facecolor='r') b.set_zorder(10) ax.add_collection(b) # stations for station in station_list: x,y = m(station.longitude, station.latitude) m.scatter(x, y, 150, color="#33CC00", marker="^", zorder=3, linewidths=1, edgecolor="k") plt.text(x+1800, y+3000, station.code, family="monospace", fontsize=12) fig.savefig(plot_file)
def draw(self, fm, NP=None): fig = plt.figure(figsize=(8, 8)) ax = fig.add_axes([0.05, 0.05, 0.9, 0.9]) b = beach(fm, xy=(0.5, 0.5), facecolor=self.facecolor, linewidth=self.lw, bgcolor=self.bgcolor, edgecolor=self.edgecolor, alpha=self.alpha, width=1, size=1) b.set_zorder(10) ax.add_collection(b) if NP: b2 = beach( NP, xy=(0.5, 0.5), #facecolor=self.facecolor, linewidth=self.lw + 1, #bgcolor=self.bgcolor, #edgecolor=self.edgecolor, #alpha=self.alpha, nofill=True, width=1, size=1) b2.set_zorder(11) ax.add_collection(b2) ax.set_xticks(()) ax.set_yticks(()) ax.set_frame_on(False) if self.outputname: plt.savefig(self.outputname, bbox_inches='tight', transparent=True) else: plt.show()
def mt_plot(): """ Return a moment tensor image. """ formats = {"png": "image/png", "svg": "image/svg+xml"} args = flask.request.args m_rr = float(args["m_rr"]) m_tt = float(args["m_tt"]) m_pp = float(args["m_pp"]) m_rt = float(args["m_rt"]) m_rp = float(args["m_rp"]) m_tp = float(args["m_tp"]) focmec = (m_rr, m_tt, m_pp, m_rt, m_rp, m_tp) # Allow hexcolors. color = args.get("color", "red") try: hexcolor = "#" + color hex2color(hexcolor) color = hexcolor except ValueError: pass size = int(args.get("size", 32)) lw = float(args.get("lw", 1)) format = args.get("format", "png") if format not in formats.keys(): flask.abort(500) dpi = 100 fig = plt.figure(figsize=(float(size) / float(dpi), float(size) / float(dpi)), dpi=dpi) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) bb = beach(focmec, xy=(0, 0), width=200, linewidth=lw, facecolor=color) ax.add_collection(bb) ax.set_xlim(-105, 105) ax.set_ylim(-105, 105) temp = io.BytesIO() plt.savefig(temp, format=format, dpi=dpi, transparent=True) plt.close(fig) plt.close("all") temp.seek(0, 0) return flask.send_file(temp, mimetype=formats[format], add_etags=False, attachment_filename="mt.%s" % format)
def test_collection(self): """ Tests to plot beachballs as collection into an existing axis object. The moment tensor values are taken form the test_Beachball unit test. See that test for more information about the parameters. """ mt = [[0.91, -0.89, -0.02, 1.78, -1.55, 0.47], [274, 13, 55], [130, 79, 98], [264.98, 45.00, -159.99], [160.55, 76.00, -46.78], [1.45, -6.60, 5.14, -2.67, -3.16, 1.36], [235, 80, 35], [138, 56, 168], [1, 1, 1, 0, 0, 0], [-1, -1, -1, 0, 0, 0], [1, -2, 1, 0, 0, 0], [1, -1, 0, 0, 0, 0], [1, -1, 0, 0, 0, -1], [179, 55, -78], [10, 42.5, 90], [10, 42.5, 92], [150, 87, 1], [0.99, -2.00, 1.01, 0.92, 0.48, 0.15], [5.24, -6.77, 1.53, 0.81, 1.49, -0.05], [16.578, -7.987, -8.592, -5.515, -29.732, 7.517], [-2.39, 1.04, 1.35, 0.57, -2.94, -0.94], [150, 87, 1]] with ImageComparison(self.path, 'bb_collection.png') as ic: # Initialize figure fig = plt.figure(figsize=(6, 6), dpi=300) ax = fig.add_subplot(111, aspect='equal') # Plot the stations or borders ax.plot([-100, -100, 100, 100], [-100, 100, -100, 100], 'rv') x = -100 y = -100 for i, t in enumerate(mt): # add the beachball (a collection of two patches) to the axis ax.add_collection(beach(t, width=30, xy=(x, y), linewidth=.6)) x += 50 if (i + 1) % 5 == 0: x = -100 y += 50 # set the x and y limits ax.axis([-120, 120, -120, 120]) # save the output fig.savefig(ic.name)
def source(self, fm_type="focal_mechanism"): """ Plot the source, either as a focal mechanism, moment tensor, or as a simple point, based on the input. :type fm_type: str :param fm_type: choice to plot focal_mechanism: 6 component focal mechanism strike_dip_rake: classic double couple look """ marker = self.kwargs.get("source_marker", "o") color = self.kwargs.get("source_color", "indianred") lw = self.kwargs.get("source_lw", 1.75) width = self.kwargs.get("source_width", 35) # No focal mechanism? Just plot a marker self.m.scatter(self.ev_x, self.ev_y, marker=marker, color=color, edgecolor="k", linewidth=lw) if hasattr(self.event, "focal_mechanisms") and \ self.event.focal_mechanisms: if fm_type == "focal_mechanism": fm = self.event.focal_mechanisms[0].moment_tensor.tensor or \ self.event.preferred_focal_mechanism().moment_tensor.tensor beach_input = [ fm['m_rr'], fm['m_tt'], fm['m_pp'], fm['m_rt'], fm['m_rp'], fm['m_tp'] ] elif fm_type == "strike_dip_rake": nod_plane = self.event.focal_mechanisms[0].nodal_planes or \ self.event.preferred_focal_mechanism().nodal_planes # try determine the preferred nodal plane, default to 1 try: sdr = nod_plane[f"nodal_plane_{nod_plane.preferred_plane}"] except AttributeError: sdr = nod_plane.nodal_plane_1 beach_input = [sdr.strike, sdr.dip, sdr.rake] else: raise ValueError("fm_type must be 'focal_mechanism' or " "'strike_dip_rake") b = beach(beach_input, xy=(self.ev_x, self.ev_y), width=width, linewidth=lw, facecolor=color, axes=plt.gca()) b.set_zorder(10) plt.gca().add_collection(b)
def plot_global_map(self): """ Plot global map of event and stations """ # import basemap here due to error from mpl_toolkits.basemap import Basemap # ax = plt.subplot(211) plt.title(self.cmtsource.eventname) m = Basemap(projection='cyl', lon_0=0.0, lat_0=0.0, resolution='c') m.drawcoastlines() m.fillcontinents() m.drawparallels(np.arange(-90., 120., 30.)) m.drawmeridians(np.arange(0., 420., 60.)) m.drawmapboundary() x, y = m(self.sta_lon, self.sta_lat) m.scatter(x, y, 30, color="r", marker="^", edgecolor="k", linewidth='0.3', zorder=3) cmt_lat = self.cmtsource.latitude cmt_lon = self.cmtsource.longitude focmecs = get_cmt_par(self.cmtsource)[:6] ax = plt.gca() if self.mode == 'regional': minlon = min(self.sta_lon) maxlon = max(self.sta_lon) minlat = min(self.sta_lat) maxlat = max(self.sta_lat) padding = 5. m.drawparallels(np.arange(-90., 120., padding)) m.drawmeridians(np.arange(0., 420., padding)) ax.set_xlim(minlon - padding, maxlon + padding) ax.set_ylim(minlat - padding, maxlat + padding) width_beach = min((maxlon + 2 * padding - minlon) / (4 * padding), (maxlat + 2 * padding - minlat) / (4 * padding)) else: width_beach = 20 bb = beach(focmecs, xy=(cmt_lon, cmt_lat), width=width_beach, linewidth=1, alpha=1.0) bb.set_zorder(10) ax.add_collection(bb)
def bbb(event, data, chi): data0 = data[data['Sum'] < chi] X = data0['Strike'] Y = data0['Dip'] Z = data0['Rake'] C = data0['Sum'] d = {'Strike': X, 'Dip': Y, 'Rake': Y} df = pd.DataFrame.from_dict(d) faults = df.drop_duplicates(subset=["Strike", "Dip", "Rake"]) print(len(faults)) y_val = int(len(X) / 5) print('Event:', event) fig, ax = plt.subplots(figsize=(12, 10)) ax.set(xlim=(-1, 6), ylim=(0, y_val + 1)) n = 1 for index, rows in faults.iterrows(): if n <= y_val: f = [rows.Strike, rows.Dip, rows.Rake] bball = beach(f, xy=(0, n), width=0.6, nofill=True) ax.add_collection(bball) plt.annotate(f, (-0.5, n + 0.5), size=5) n += 1 elif n <= y_val * 2: f = [rows.Strike, rows.Dip, rows.Rake] bball = beach(f, xy=(1, n - y_val), width=0.6, nofill=True) ax.add_collection(bball) plt.annotate(f, (0.5, (n - y_val) + 0.5), size=5) n += 1 elif n <= y_val * 3: f = [rows.Strike, rows.Dip, rows.Rake] bball = beach(f, xy=(2, n - (y_val * 2)), width=0.6, nofill=True) ax.add_collection(bball) plt.annotate(f, (1.5, n - (y_val * 2) + 0.5), size=5) n += 1 elif n <= y_val * 4: f = [rows.Strike, rows.Dip, rows.Rake] bball = beach(f, xy=(3, n - (y_val * 3)), width=0.6, nofill=True) ax.add_collection(bball) plt.annotate(f, (2.5, n - (y_val * 3) + 0.5), size=5) n += 1 elif n <= y_val * 5: f = [rows.Strike, rows.Dip, rows.Rake] bball = beach(f, xy=(4, n - (y_val * 4)), width=0.6, nofill=True) ax.add_collection(bball) plt.annotate(f, (3.5, n - (y_val * 4) + 0.5), size=5) n += 1 elif n <= y_val * 6: f = [rows.Strike, rows.Dip, rows.Rake] bball = beach(f, xy=(5, n - (y_val * 5)), width=0.6, nofill=True) ax.add_collection(bball) plt.annotate(f, (4.5, n - (y_val * 5) + 0.5), size=5) n += 1 plt.show()
def bbb(event, data): # faults = data.drop_duplicates(subset = ["Strike","Dip","Rake"]) # print(len(faults)) y_val = int(len(data)/5) print('Event:', event) fig, ax = plt.subplots(figsize=(7,7)) ax.set(xlim=(-1, 6), ylim=(0, y_val+1)) ax.set_title(event) n=0 for index, rows in data.iterrows(): if n <= y_val: f = [rows.Strike, rows.Dip, rows.Rake] bball = beach(f, xy=(0,n+0.3), width=0.6) ax.add_collection(bball) fa = [rows.Strike, rows.Dip, rows.Rake, truncate(rows['Misfit'], 4)] plt.annotate(fa, (-0.5, n+0.6), size=4) n += 1 elif n <= y_val*2: f = [rows.Strike, rows.Dip, rows.Rake] bball = beach(f, xy=(1,n-y_val), width=0.6) ax.add_collection(bball) fa = [rows.Strike, rows.Dip, rows.Rake, truncate(rows['Misfit'], 4)] plt.annotate(fa, (0.5, (n-y_val)+0.5), size=4) n += 1 elif n <= y_val*3: f = [rows.Strike, rows.Dip, rows.Rake] bball = beach(f, xy=(2,n-(y_val*2)), width=0.6) ax.add_collection(bball) fa = [rows.Strike, rows.Dip, rows.Rake, truncate(rows['Misfit'], 4)] plt.annotate(fa, (1.5, n-(y_val*2)+0.5), size=4) n += 1 elif n <= y_val*4: f = [rows.Strike, rows.Dip, rows.Rake] bball = beach(f, xy=(3,n-(y_val*3)), width=0.6) ax.add_collection(bball) fa = [rows.Strike, rows.Dip, rows.Rake, truncate(rows['Misfit'], 4)] plt.annotate(fa, (2.5, n-(y_val*3)+0.5), size=4) n += 1 elif n <= y_val*5: f = [rows.Strike, rows.Dip, rows.Rake] bball = beach(f, xy=(4,n-(y_val*4)), width=0.6) ax.add_collection(bball) fa = [rows.Strike, rows.Dip, rows.Rake, truncate(rows['Misfit'], 4)] plt.annotate(fa, (3.5, n-(y_val*4)+0.5), size=4) n += 1 elif n <= y_val*6: f = [rows.Strike, rows.Dip, rows.Rake] bball = beach(f, xy=(5,n-(y_val*5)), width=0.6) ax.add_collection(bball) fa = [rows.Strike, rows.Dip, rows.Rake, truncate(rows['Misfit'], 4)] plt.annotate(fa, (4.5, n-(y_val*5)+0.5), size=4) n += 1 plt.show()
def plot_foc_mec(self, method, **kwargs): # Plot and save beachball from First Polarity or MTI if method == "First Polarity": strike = kwargs.pop('strike') dip = kwargs.pop('dip') rake = kwargs.pop('rake') fm = [strike, dip, rake] elif method == "MTI": mrr = kwargs.pop('mrr') mtt = kwargs.pop('mtt') mpp = kwargs.pop('mpp') mrt = kwargs.pop('mrt') mrp = kwargs.pop('mrp') mtp = kwargs.pop('mtp') fm = [mrr, mtt, mpp, mrt, mrp, mtp] ax = plt.axes() plt.axis('off') ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) lw = 2 plt.xlim(-100 - lw / 2, 100 + lw / 2) plt.ylim(-100 - lw / 2, 100 + lw / 2) if method == "First Polarity": beach2 = beach(fm, facecolor='r', linewidth=1., alpha=0.8, width=80) elif method == "MTI": beach2 = beach(fm, facecolor='b', linewidth=1., alpha=0.8, width=80) ax.add_collection(beach2) outfile = os.path.join(ROOT_DIR, 'db/map_class/foc_mec.png') plt.savefig(outfile, bbox_inches='tight', pad_inches=0, transparent=True, edgecolor='none') plt.clf() plt.close()
def plot_event(self, infname, evnumb, inbasemap): from obspy.imaging.beachball import beach dset=pyasdf.ASDFDataSet(infname) event=dset.events[evnumb-1] event_id=event.resource_id.id.split('=')[-1] magnitude=event.magnitudes[0].mag; Mtype=event.magnitudes[0].magnitude_type otime=event.origins[0].time evlo=event.origins[0].longitude; evla=event.origins[0].latitude; evdp=event.origins[0].depth/1000. mtensor=event.focal_mechanisms[0].moment_tensor.tensor mt=[mtensor.m_rr, mtensor.m_tt, mtensor.m_pp, mtensor.m_rt, mtensor.m_rp, mtensor.m_tp] x, y=inbasemap(evlo, evla) b = beach(mt, xy=(x, y), width=200000, linewidth=1, facecolor='b') b.set_zorder(10) ax = plt.gca() ax.add_collection(b) plt.suptitle('Depth: '+str(evdp)+' km'+ ' Magnitude: ' +str(magnitude) )
def _plot_focal_mech(axes, csda): """ :parameter axes: :parameter csda: """ if csda.gcmt is None: return olo = csda.csec.olo ola = csda.csec.ola cat_gcmt = csda.gcmt cmt_dst = geodetic_distance(olo, ola, cat_gcmt.data['longitude'], cat_gcmt.data['latitude']) cmt_dep = cat_gcmt.data['depth'] cmts = numpy.array(cat_gcmt.gcmts) idx = 0 for ddd, dep, eve, mag, yea in zip(list(cmt_dst), list(cmt_dep), list(cmts), cat_gcmt.data['magnitude'], cat_gcmt.data['year']): if yea > 1000 and mag > 1.0: # Kaverina classification plungeb = cat_gcmt.data['plunge_b'][idx] plungep = cat_gcmt.data['plunge_p'][idx] plunget = cat_gcmt.data['plunge_t'][idx] mclass = mecclass(plunget, plungeb, plungep) com = eve.moment_tensor._to_6component() # REMOVE try: bcc = beach(com, xy=(ddd, dep), width=eve.magnitude * 2, linewidth=1, zorder=20, size=mag, facecolor=KAVERINA[mclass]) bcc.set_alpha(0.5) axes.add_collection(bcc) except: pass idx += 1
def plot_beachball(tensor_info, segments, files=None, phase=None): """Here we plot the beachball for the event. Optionally, we add the location of teleseismic data used in the FFM modelling. """ # # Get the focal mechanism # plane_info = segments[0] strike = plane_info['strike'] dip = plane_info['dip'] rake = plane_info['rake'] fm = [strike, dip, rake] # # Plot the beach ball # fig = plt.figure(figsize=(7, 7)) bb = beach(fm, width=3.0, zorder=1) ax = plt.gca() ax.add_collection(bb) plt.plot(0, 0, 'b*', markersize=20) ax.set_aspect('equal') # # Load the station informations # if files: plt.plot(0, 0, 'r*', markersize=20) for file in files: comp = file['component'] if comp == 'BHZ': comp = 'P' dist = file['distance'] az = file['azimuth'] nam = file['name'] if comp == phase: r = dist * (3.0 / 2.) / 90. x1 = np.sin(az * np.pi / 180.) * r y1 = np.cos(az * np.pi / 180.) * r plt.plot(x1, y1, 'ro') plt.text(x1 + 0.01, y1 + 0.01, nam) fig.patch.set_visible(False) plt.gca().axis('off') name_plot = '{}_azimuthcover.png'.format(phase) if phase else 'Tensor.png' plt.savefig(name_plot) plt.close() return
def plot_events(events, map_object, beachball_size=0.02): """ """ beachballs = [] for event in events: # Add beachball plot. x, y = map_object(event["longitude"], event["latitude"]) focmec = [event["m_rr"], event["m_tt"], event["m_pp"], event["m_rt"], event["m_rp"], event["m_tp"]] # Attempt to calculate the best beachball size. width = max((map_object.xmax - map_object.xmin, map_object.ymax - map_object.ymin)) * beachball_size b = beach(focmec, xy=(x, y), width=width, linewidth=1, facecolor="red") b.set_zorder(200000000) map_object.ax.add_collection(b) beachballs.append(b) return beachballs
def plot_events(events, map_object, beachball_size=0.02): """ """ beachballs = [] for event in events: # Add beachball plot. x, y = map_object(event["longitude"], event["latitude"]) focmec = [ event["m_rr"], event["m_tt"], event["m_pp"], event["m_rt"], event["m_rp"], event["m_tp"] ] # Attempt to calculate the best beachball size. width = max((map_object.xmax - map_object.xmin, map_object.ymax - map_object.ymin)) * beachball_size b = beach(focmec, xy=(x, y), width=width, linewidth=1, facecolor="red") b.set_zorder(200000000) map_object.ax.add_collection(b) beachballs.append(b) return beachballs
def plot_events2018(events, bb=None): bbfname = 'data/focal_mechanism_2018swarm.txt' fig = plot_events_stations_map_depth(events, convert_coords=LATLON0, show=False) bbs = np.genfromtxt(bbfname, names=True) xys = [(0, 3), (0, 4), (1, 1), (1, 0), (0, 2), (0, 1), (0, 0), (1, 2), (0, 5), (0, 6), (1, 3), (1, 5), (1, 4)] for i, bb in enumerate(bbs): _, lat, lon, dep, mag, *sdr = bb xy = convert_coords2km([(lat, lon)], latlon0=LATLON0)[0] ax = fig.axes[0] xy2 = (xys[i][0] * 3.8 - 1.9, -(xys[i][1] + xys[i][0] * 0.5) / 6 * 4 + 2.2) ax.plot(*list(zip(xy, xy2)), lw=0.5, color='k', zorder=10) b = beach(sdr, xy=xy2, width=0.5, linewidth=0.5, facecolor='C0') ax.add_collection(b) fig.axes[0].set_xlim(-2.5, 2.5) fig.axes[0].set_ylim(-2.3, 2.7) fig.axes[1].set_xlim(5.95, 10.95) fig.savefig('figs/eventmap.pdf', bbox_inches='tight', pad_inches=0.1)
def plot_cmts(ax, latitude, longitude, depth, mt, nmmt, alpha): for (lon, lat, d, m, sm) \ in zip(longitude.tolist(), latitude.tolist(), depth.tolist(), mt.tolist(), nmmt.tolist()): try: b = beach(m, linewidth=0.25, facecolor='k', bgcolor='w', edgecolor='k', alpha=alpha, xy=(lon, lat), width=20, size=100, nofill=False, zorder=100, axes=ax) ax.add_collection(b) except Exception as e: print(e)
def plot_model(self): """ Quick plotting function of model dimensions. To do: add velocity model """ plt.figure(figsize=[10, 5]) plt.scatter(self.receivers['recxs'], self.receivers['reczs'], marker='v') if self.source['src_type'] == 4: from obspy.imaging.beachball import beach beach = beach(self.source['mt'], xy=(self.source['srcx'], self.source['srcz']), width=self.model_parameters['xmax'] * 0.05) ax = plt.gca() ax.add_collection(beach) ax.set_aspect("equal") else: plt.scatter(self.source['srcx'], self.source['srcz'], marker='*', color='r', s=200) plt.axhline(y=0, c='0.5') plt.xlim(0, self.model_parameters['xmax']) plt.ylim(self.model_parameters['zmax'], -0.1 * self.model_parameters['zmax']) plt.xlabel('Distance (km)') plt.ylabel('Depth (km)') plt.grid() plt.show()
clat = np.floor(filtered[0]['origins'][0]['latitude']) m = Basemap(projection='cyl',llcrnrlat=clat - 5,urcrnrlat= clat + 5,\ llcrnrlon= clon-5,urcrnrlon=clon+5,resolution='l') plt.figure(figsize=(8., 8.)) ax = plt.subplot(111) ########### #Earthquakes ########### for event in filtered: fc = event.focal_mechanisms[0] plane = fc.nodal_planes.nodal_plane_1 origin = event.origins[0] depth = origin bb = beach([plane.strike, plane.dip, plane.rake], xy=m(origin.longitude, origin.latitude), width=0.6, linewidth=0.5, facecolor='b') ax.add_collection(bb) m.fillcontinents(alpha=0.5) m.drawparallels(np.arange(-90.,91.,10.), labels=[False,True,True,False]) m.drawmeridians(np.arange(-180.,181.,10.), labels=[True,False,False,True]) #m.etopo(alpha=0.5) m.drawcoastlines(linewidth=0.5) m.arcgisimage(service='ESRI_Imagery_World_2D', xpixels = 1500, verbose= True) plt.title("Magnitude 8.3 Offshore Coquimbo, Chile") plt.show()
# 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]) # Plot station positions and names into the map # again we have to compute the projection of our lon/lat values lats = [47.761659, 47.7405, 47.755100, 47.737167] lons = [12.864466, 12.8671, 12.849660, 12.795714] names = [" RMOA", " RNON", " RTSH", " RJOB"] x, y = m(lons, lats) m.scatter(x, y, 200, color="r", marker="v", edgecolor="k", zorder=3) for i in range(len(names)): plt.text(x[i], y[i], names[i], va="top", family="monospace", weight="bold") # Add beachballs for two events lats = [47.751602, 47.75577] lons = [12.866492, 12.893850] x, y = m(lons, lats) # Two focal mechanisms for beachball routine, specified as [strike, dip, rake] focmecs = [[80, 50, 80], [85, 30, 90]] ax = plt.gca() for i in range(len(focmecs)): b = beach(focmecs[i], xy=(x[i], y[i]), width=1000, linewidth=1) b.set_zorder(10) ax.add_collection(b) plt.show()
from obspy import read_events from obspy.imaging.beachball import beach event = read_events( 'https://earthquake.usgs.gov/archive/product/moment-tensor/' 'us_20005ysu_mww/us/1470868224040/quakeml.xml', format='QUAKEML')[0] origin = event.preferred_origin() or event.origins[0] focmec = event.preferred_focal_mechanism() or event.focal_mechanisms[0] tensor = focmec.moment_tensor.tensor moment_list = [tensor.m_rr, tensor.m_tt, tensor.m_pp, tensor.m_rt, tensor.m_rp, tensor.m_tp] m = Basemap(projection='cyl', lon_0=origin.longitude, lat_0=origin.latitude, 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(origin.longitude, origin.latitude) ax = plt.gca() b = beach(moment_list, xy=(x, y), width=20, linewidth=1, alpha=0.85) b.set_zorder(10) ax.add_collection(b) plt.show()
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from obspy.imaging.beachball import beach m = Basemap(projection='cyl', lon_0=142.36929, lat_0=38.3215, 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(142.36929, 38.3215) focmecs = [0.136, -0.591, 0.455, -0.396, 0.046, -0.615] ax = plt.gca() b = beach(focmecs, xy=(x, y), width=10, linewidth=1, alpha=0.85) b.set_zorder(10) ax.add_collection(b) plt.show()
def correlation(depth_x, correlation_y, dc, beachballs, plot_file): """ Illustrates an example for plotting beachballs and data points on line with specific color based on values with a labelled colorbar. """ # sets figure's dimensions _fig_x = 30 _fig_y = 20 # creates figure fig, ax = plt.subplots(figsize=(_fig_x,_fig_y)) # plots (depth_x, correlation_y) points on line ax.plot(depth_x, correlation_y, '--', linewidth=2, color = 'k') # creates a grid on the (main) plot ax.grid() # sets labels plt.xlabel('Depth (km)') plt.ylabel('Correlation') # sets font size plt.rcParams.update({'font.size': 28}) # sets fixed y-axis range plt.ylim((0,1)) # sets margins on the plot plt.margins(0.1) # sets color canvas for coloring beachball cm = plt.cm.jet # creates a colorbar at the right of main plot: divider = make_axes_locatable(ax) # makes room for colorbar cax = divider.append_axes("right", size="2%", pad=1) # set values to colorbar norm = colors.Normalize(vmin=0, vmax=100) # creates colorbar on specific axes, norm, canvas color and orientation cb1 = colorbar.ColorbarBase(cax, norm=norm, cmap=cm, orientation='vertical') # sets colorbar label cb1.set_label('DC%') # plotting beachballs on specific x-axis and y-axis # with a color based on the data_dc values (normalized to 0-1) for i in xrange(len(depth_x)): # sets color value color = cm(dc[i]/100.0) # draws beachball b = beach.beach([beachballs[i][0], beachballs[i][1], beachballs[i][2]], xy=(depth_x[i], correlation_y[i]), width=80, linewidth=1, facecolor=color) # holds the aspect but fixes positioning: b.set_transform(transforms.IdentityTransform()) # brings the all patches to the origin (0, 0). for p in b._paths: p.vertices -= [depth_x[i], correlation_y[i]] # uses the offset property of the collection to position the patches b.set_offsets((depth_x[i], correlation_y[i])) b._transOffset = ax.transData # adds beachball to plot ax.add_collection(b) # saves plot to file plt.savefig(plot_file, dpi=fig.dpi)
def plot_misfit_map(items, component, pretty_misfit_name, filename, event=None): # Choose red to green colormap. cm = matplotlib.cm.RdYlGn_r longitudes = np.array([_i["longitude"] for _i in items]) latitudes = np.array([_i["latitude"] for _i in items]) misfit_all = np.array([_i["misfit_values"] for _i in items]) plt.close() if event is not None: lat_plot = np.append(latitudes, event.origins[0].latitude) lon_plot = np.append(longitudes, event.origins[0].longitude) else: lat_plot = latitudes lon_plot = longitudes lat_mean = (lat_plot.min() + lat_plot.max())/2 lon_mean = (lon_plot.min() + lon_plot.max())/2 m = get_basemap(lon_plot.ptp(), lat_plot.ptp(), lon_mean, lat_mean) x, y = m(longitudes, latitudes) misfit_all= np.asarray(misfit_all) nrows = 3 ncols = 4 bins_range = (misfit_all.min(), misfit_all.max()) fig = plt.figure(figsize=(3*ncols, 3*nrows)) # Get beachball info if event is not None: tensor = event.focal_mechanisms[0].moment_tensor.tensor ev_mt = [tensor.m_rr, tensor.m_tt, tensor.m_pp, tensor.m_rt, tensor.m_rp, tensor.m_tp] ex, ey = m(event.origins[0].longitude, event.origins[0].latitude) for i in range(len(items[0]["periods"])): ax = fig.add_subplot(nrows, ncols, i+1) m = get_basemap(lon_plot.ptp(), lat_plot.ptp(), lon_mean, lat_mean, stepsize=4, resolution='c') data = m.scatter(x, y, c=misfit_all[:,i], s=30, vmin=misfit_all.min(), vmax=misfit_all.max(), cmap=cm, alpha=0.9, zorder=10) # Add beachball if event is not None: b = beach(ev_mt, xy=(ex, ey), width=int(8000*event.magnitudes[0].mag), linewidth=.5, facecolor='deepskyblue') ax.add_collection(b) # Add colorbar for the last subplot #if i == (len(items[0]["periods"]) -1): # divider = make_axes_locatable(ax) # cax = divider.append_axes("right", size="5%", pad=0.05) # cbar = m.colorbar(data, location="right", pad="15%", shrink=0.75) # cbar.set_label(pretty_misfit_name) ax.set_title('t > ' + str(items[0]["periods"][i]) + ' s', fontsize=12) fig.subplots_adjust(right=0.85) cbar_ax = fig.add_axes([0.9, 0.1, 0.01, 0.85]) fig.colorbar(data, cax=cbar_ax) fig.tight_layout(rect=[0.08, 0.03, 0.9, 0.9]) fig.suptitle("%s distribution for component %s" % ( pretty_misfit_name, component)) fig.savefig(filename)
def plot_map(items, threshold, threshold_is_upper_limit, component, pretty_misfit_name, filename, event=None): # Choose red to green colormap. cm = matplotlib.cm.RdYlGn_r longitudes = np.array([_i["longitude"] for _i in items]) latitudes = np.array([_i["latitude"] for _i in items]) resolvable_periods = [] station_array = [] period_range = items[0]["periods"] for item in items: # Find the threshold. point = rightmost_threshold_crossing( item["periods"], item["misfit_values"], threshold, threshold_is_upper_limit) resolvable_periods.append(point[0]) station_array.append(item["network"] + '_' + item["station"]) resolvable_periods = np.array(resolvable_periods) plt.close() if event is not None: lat_plot = np.append(latitudes, event.origins[0].latitude) lon_plot = np.append(longitudes, event.origins[0].longitude) else: lat_plot = latitudes lon_plot = longitudes lat_mean = (lat_plot.min() + lat_plot.max())/2 lon_mean = (lon_plot.min() + lon_plot.max())/2 m = get_basemap(lon_plot.ptp(), lat_plot.ptp(), lon_mean, lat_mean) x, y = m(longitudes, latitudes) data = m.scatter(x, y, c=resolvable_periods, s=30, vmin=period_range[0], vmax=period_range[-1], cmap=cm, alpha=0.9, zorder=10) # add station label texts = [] for stnm, xi, yi in zip(station_array, x, y): texts.append(plt.text(xi, yi, stnm,fontsize=5)) if 'adjustText' in sys.modules: # require adjust_Text module adjustText.adjust_text(texts, force_points=1, force_text=1, expand_points=(1,1), expand_text=(1,1), arrowprops=dict(arrowstyle="<-", color='black', alpha=0.5, lw=0.5)) ax = plt.gca() # plot beachball if event is not None: tensor = event.focal_mechanisms[0].moment_tensor.tensor ev_mt = [tensor.m_rr, tensor.m_tt, tensor.m_pp, tensor.m_rt, tensor.m_rp, tensor.m_tp] ex, ey = m(event.origins[0].longitude, event.origins[0].latitude) b = beach(ev_mt, xy=(ex, ey), width=int(5000*event.magnitudes[0].mag), linewidth=0.5, facecolor='deepskyblue') ax.add_collection(b) cbar = m.colorbar(data, location="right", pad="15%") cbar.set_label("Minimum Resolvable Period [s]") plt.title("%s minimum resolvable period for component %s" % ( pretty_misfit_name, component), fontsize="small") plt.savefig(filename)
def contour(time_list, depth_list, dc_list, corr_list, beachball_list, plot_file): """ Plotting contour """ # sets figure's dimensions _fig_x = 60 _fig_y = 40 # creates figure fig, ax = plt.subplots(figsize=(_fig_x,_fig_y)) # creates a grid on the (main) plot ax.grid() # sets labels plt.xlabel('Time (sec)') plt.ylabel('Centroid Depth (km)') # sets font size plt.rcParams.update({'font.size': 28}) # sets margins on the plot plt.margins(0.05) tri.Triangulation(time_list, depth_list) levels=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] cont = plt.tricontour(time_list, depth_list, corr_list, len(levels), levels=levels, linewidths=0.5, colors='k') plt.tricontourf(time_list, depth_list, corr_list, len(levels), levels=levels, cmap=plt.cm.cool) plt.clabel(cont) cm=plt.cm.copper_r #gia dc # plotting beachballs on specific x-axis and y-axis # with a color based on the data_dc values (normalized to 0-1) _max_corr = max(corr_list) _index = corr_list.index(_max_corr) for i in xrange(len(beachball_list)): if i == _index: # sets best beachball's color value to red _color = 'red' _width = 45 # bigger beachball for best match else: # sets beachball's color value _color = cm(dc_list[i]/100.0) _width = 35 # draws beachball b = beach.beach([beachball_list[i][0], beachball_list[i][1], beachball_list[i][2]], xy=(time_list[i],depth_list[i]), width=_width, linewidth=1, facecolor=_color) # holds the aspect but fixes positioning: b.set_transform(transforms.IdentityTransform()) # brings the all patches to the origin (0, 0). for p in b._paths: p.vertices -= [time_list[i], depth_list[i]] # uses the offset property of the collection to position the patches b.set_offsets((time_list[i], depth_list[i])) b._transOffset = ax.transData # adds beachball to plot ax.add_collection(b) # creates a colorbar at the right of main plot divider = make_axes_locatable(ax) # makes room for colorbar cax = divider.append_axes("right", size="1%", pad=0.5) # set values to colorbar norm = colors.Normalize(vmin=0.0, vmax=1.0) # creates colorbar on specific axes, norm, canvas color and orientation colorbar.ColorbarBase(cax, cmap=plt.cm.cool, norm=norm, orientation='vertical', label='Correlation') cax = divider.append_axes("right", size="1%", pad=1.5) # set values to colorbar norm = colors.Normalize(vmin=0, vmax=100) # creates colorbar on specific axes, norm, canvas color and orientation colorbar.ColorbarBase(cax, cmap=plt.cm.copper_r , norm=norm, orientation='vertical', label='DC%') # save plot to file plt.savefig(plot_file, dpi=fig.dpi)
def plot_waveforms(st_data, st_synth, arr_times, CC, CClim, dA, dT, stf, depth, origin, tensor, iteration=-1, misfit=0.0, outdir='./waveforms/'): if not os.path.exists(outdir): os.mkdir(outdir) fig = plt.figure(figsize=(15, 10)) # Axis for the waveforms ax = fig.add_subplot(111) # Axis for the Source Time Function left, bottom, width, height = [0.75, 0.455, 0.14, 0.18] ax_stf = fig.add_axes([left, bottom, width, height]) # Axis for the Beachball left, bottom, width, height = [0.75, 0.65, 0.14, 0.14] ax_bb = fig.add_axes([left, bottom, width, height]) # Rectangle for the global map plot. Axis is created later rect_stf = [0.75, 0.155, 0.14, 0.25] nplots = len(st_data) nrows = int(np.sqrt(nplots)) + 1 ncols = nplots / nrows + 1 iplot = 0 st_data_plot = st_data.copy() st_data_plot.sort(keys=['azi']) for tr in st_data_plot: irow = np.mod(iplot, nrows) icol = np.int(iplot / nrows) normfac = max(np.abs(tr.data)) yoffset = irow * 1.5 xoffset = icol code = '%s.%s' % (tr.stats.station, tr.stats.location) if CC[code] > CClim: ls = '-' else: ls = 'dotted' # Plot data yvals = tr.data / normfac xvals = np.linspace(0, 0.8, num=len(yvals)) l_d, = ax.plot(xvals + xoffset, yvals + yoffset, color='k', linestyle=ls, linewidth=2.0) # Plot Green's function yvals = st_synth.select(station=tr.stats.station)[0].data / normfac xvals = np.linspace(0, 0.8, num=len(yvals)) l_g, = ax.plot(xvals + xoffset, yvals + yoffset, color='grey', linestyle=ls, linewidth=1) # Convolve with STF and plot synthetics yvals = np.convolve(st_synth.select(station=tr.stats.station)[0].data, stf, mode='full')[0:tr.stats.npts] / normfac xvals = np.linspace(0, 0.8, num=len(yvals)) l_s, = ax.plot(xvals + xoffset, yvals + yoffset, color='r', linestyle=ls, linewidth=1.5) ax.text(xoffset, yoffset + 0.2, '%s \nCC: %4.2f\ndA: %4.1f\ndT: %5.1f' % (tr.stats.station, CC[code], dA[code], dT[code]), size=8.0, color='darkgreen') # Plot picked P arrival time xvals = ((arr_times[code] / tr.times()[-1]) * 0.8 + xoffset) * \ np.ones(2) ax.plot(xvals, (yoffset + 0.5, yoffset - 0.5), 'b') iplot += 1 ax.legend((l_s, l_d, l_g), ('synthetic', 'data', 'Green''s fct')) ax.set_xlim(0, ncols * 1.2) ax.set_ylim(-1.5, nrows * 1.5) ax.set_xticks([]) ax.set_yticks([]) if (iteration >= 0): ax.set_title('Waveform fits, depth: %d m, it: %d, misfit: %9.3e' % (depth, iteration, misfit)) # Plot STF yvals = stf xoffset = _dict_mean(dT) * tr.stats.delta xvals = tr.stats.delta * np.arange(0, len(yvals)) + xoffset ax_stf.plot(xvals, yvals) ax_stf.hlines(0, xmin=xvals[0], xmax=xvals[-1], linestyles='--', color='darkgrey') ax_stf.set_ylim((-0.3, 1.1)) ax_stf.set_xlim((xvals[0], xvals[-1])) ax_stf.set_xlabel('time / seconds') ax_stf.set_yticks([0]) ax_stf.set_ylabel('Source Time Function') # Plot beach ball mt = [tensor.m_rr, tensor.m_tt, tensor.m_pp, tensor.m_rt, tensor.m_rp, tensor.m_tp] b = beach(mt, width=120, linewidth=1, facecolor='r', xy=(0, 0), axes=ax_bb) ax_bb.add_collection(b) ax_bb.set_xlim((-0.1, 0.1)) ax_bb.set_ylim((-0.1, 0.1)) ax_bb.set_xticks([]) ax_bb.set_yticks([]) ax_bb.axis('off') # Plot Map plot_map(st_synth, CC, origin.longitude, origin.latitude, fig=fig, CClim=CClim, rect=rect_stf, colormap='plasma') outfile = os.path.join(outdir, 'waveforms_it_%d.png' % iteration) fig.savefig(outfile, format='png') plt.close(fig)