def plot(self, projection='global', resolution='l', continent_fill_color='0.9', water_fill_color='1.0', label='magnitude', color='depth', colormap=None, show=True, outfile=None, method=None, fig=None, title=None, **kwargs): # @UnusedVariable """ Creates preview map of all events in current Catalog object. :type projection: str, optional :param projection: The map projection. Currently supported are: * ``"global"`` (Will plot the whole world.) * ``"ortho"`` (Will center around the mean lat/long.) * ``"local"`` (Will plot around local events) Defaults to "global" :type resolution: str, optional :param resolution: Resolution of the boundary database to use. Will be based directly to the basemap module. Possible values are: * ``"c"`` (crude) * ``"l"`` (low) * ``"i"`` (intermediate) * ``"h"`` (high) * ``"f"`` (full) Defaults to ``"l"`` :type continent_fill_color: Valid matplotlib color, optional :param continent_fill_color: Color of the continents. Defaults to ``"0.9"`` which is a light gray. :type water_fill_color: Valid matplotlib color, optional :param water_fill_color: Color of all water bodies. Defaults to ``"white"``. :type label: str, optional :param label: Events will be labelled based on the chosen property. Possible values are: * ``"magnitude"`` * ``None`` Defaults to ``"magnitude"`` :type color: str, optional :param color: The events will be color-coded based on the chosen property. Possible values are: * ``"date"`` * ``"depth"`` Defaults to ``"depth"`` :type colormap: str, any matplotlib colormap, optional :param colormap: The colormap for color-coding the events. The event with the smallest property will have the color of one end of the colormap and the event with the biggest property the color of the other end with all other events in between. Defaults to None which will use the default colormap for the date encoding and a colormap going from green over yellow to red for the depth encoding. :type show: bool :param show: Whether to show the figure after plotting or not. Can be used to do further customization of the plot before showing it. Has no effect if `outfile` is specified. :type outfile: str :param outfile: Output file path to directly save the resulting image (e.g. ``"/tmp/image.png"``). Overrides the ``show`` option, image will not be displayed interactively. The given path/filename is also used to automatically determine the output format. Supported file formats depend on your matplotlib backend. Most backends support png, pdf, ps, eps and svg. Defaults to ``None``. The figure is closed after saving it to file. :type method: str :param method: Method to use for plotting. Possible values are: * ``'basemap'`` to use the Basemap library * ``'cartopy'`` to use the Cartopy library * ``None`` to pick the best available library Defaults to ``None``. :type fig: :class:`matplotlib.figure.Figure` (or :class:`matplotlib.axes.Axes`) :param fig: Figure instance to reuse, returned from a previous inventory/catalog plot call with `method=basemap`. If a previous basemap plot is reused, any kwargs regarding the basemap plot setup will be ignored (i.e. `projection`, `resolution`, `continent_fill_color`, `water_fill_color`). Note that multiple plots using colorbars likely are problematic, but e.g. one station plot (without colorbar) and one event plot (with colorbar) together should work well. If an :class:`~matplotlib.axes.Axes` is supplied, the given axes is used to plot into and no colorbar will be produced. :type title: str :param title: Title above plot. If left ``None``, an automatic title will be generated. Set to ``""`` for no title. :returns: Figure instance with the plot. .. rubric:: Examples Mollweide projection for global overview: >>> from obspy import read_events >>> cat = read_events() >>> cat.plot() # doctest:+SKIP .. plot:: from obspy import read_events cat = read_events() cat.plot() Orthographic projection: >>> cat.plot(projection="ortho") # doctest:+SKIP .. plot:: from obspy import read_events cat = read_events() cat.plot(projection="ortho") Local (Albers equal area) projection: >>> cat.plot(projection="local") # doctest:+SKIP .. plot:: from obspy import read_events cat = read_events() cat.plot(projection="local") Combining a station and event plot (uses basemap): >>> from obspy import read_inventory, read_events >>> inv = read_inventory() >>> cat = read_events() >>> fig = inv.plot(method=basemap, show=False) # doctest:+SKIP >>> cat.plot(method=basemap, fig=fig) # doctest:+SKIP .. plot:: from obspy import read_inventory, read_events inv = read_inventory() cat = read_events() fig = inv.plot(show=False) cat.plot(fig=fig) """ from obspy.imaging.maps import plot_map, _plot_basemap_into_axes import matplotlib import matplotlib.pyplot as plt if color not in ('date', 'depth'): raise ValueError('Events can be color coded by date or depth. ' "'%s' is not supported." % (color, )) if label not in (None, 'magnitude', 'depth'): raise ValueError('Events can be labeled by magnitude or events can' ' not be labeled. ' "'%s' is not supported." % (label, )) # lat/lon coordinates, magnitudes, dates lats = [] lons = [] labels = [] mags = [] colors = [] times = [] for event in self: if not event.origins: msg = ("Event '%s' does not have an origin and will not be " "plotted." % str(event.resource_id)) warnings.warn(msg) continue if not event.magnitudes: msg = ("Event '%s' does not have a magnitude and will not be " "plotted." % str(event.resource_id)) warnings.warn(msg) continue origin = event.preferred_origin() or event.origins[0] lats.append(origin.latitude) lons.append(origin.longitude) times.append(origin.time) magnitude = event.preferred_magnitude() or event.magnitudes[0] mag = magnitude.mag mags.append(mag) labels.append((' %.1f' % mag) if mag and label == 'magnitude' else '') if color == 'date': c_ = origin.get('time') or np.nan else: c_ = (origin.get('depth') or np.nan) / 1e3 colors.append(c_) # Create the colormap for date based plotting. if colormap is None: colormap = obspy_sequential if title is None: if len(lons) > 1: # if we have a `None` in the origin time list it likely ends up # as min and/or max and causes problems.. times_ = np.ma.masked_equal(times, None).compressed() min_time = times_.min() max_time = times_.max() title = ( "{event_count} events ({start} to {end}) " "- Color codes {colorcode}, size the magnitude".format( event_count=len(self.events), start=min_time.strftime("%Y-%m-%d"), end=max_time.strftime("%Y-%m-%d"), colorcode="origin time" if color == "date" else "depth")) else: title = "Event at %s" % times[0].strftime("%Y-%m-%d") if color not in ("date", "depth"): msg = "Invalid option for 'color' parameter (%s)." % color raise ValueError(msg) min_size = 2 max_size = 30 min_size_ = min(mags) - 1 max_size_ = max(mags) + 1 if len(lons) > 1: frac = [(0.2 + (_i - min_size_)) / (max_size_ - min_size_) for _i in mags] size_plot = [(_i * (max_size - min_size))**2 for _i in frac] else: size_plot = 15.0**2 if isinstance(fig, matplotlib.axes.Axes): if method is not None and method != "basemap": msg = ("Plotting into an matplotlib.axes.Axes instance " "currently only implemented for `method='basemap'`.") raise NotImplementedError(msg) ax = fig fig = ax.figure _plot_basemap_into_axes(ax=ax, lons=lons, lats=lats, size=size_plot, color=colors, bmap=None, labels=labels, projection=projection, resolution=resolution, continent_fill_color=continent_fill_color, water_fill_color=water_fill_color, colormap=colormap, marker="o", title=title, show=False, **kwargs) else: fig = plot_map(method, lons, lats, size_plot, colors, labels, projection=projection, resolution=resolution, continent_fill_color=continent_fill_color, water_fill_color=water_fill_color, colormap=colormap, marker="o", title=title, show=False, fig=fig, **kwargs) if outfile: fig.savefig(outfile) plt.close(fig) else: if show: plt.show() return fig
def plot(self, projection='global', resolution='l', continent_fill_color='0.9', water_fill_color='1.0', marker="v", size=15**2, label=True, color='#b15928', color_per_network=False, colormap="Paired", legend="upper left", time=None, show=True, outfile=None, method=None, fig=None, **kwargs): # @UnusedVariable """ Creates a preview map of all networks/stations in current inventory object. :type projection: str, optional :param projection: The map projection. Currently supported are: * ``"global"`` (Will plot the whole world.) * ``"ortho"`` (Will center around the mean lat/long.) * ``"local"`` (Will plot around local events) Defaults to ``"global"`` :type resolution: str, optional :param resolution: Resolution of the boundary database to use. Will be based directly to the basemap module. Possible values are: * ``"c"`` (crude) * ``"l"`` (low) * ``"i"`` (intermediate) * ``"h"`` (high) * ``"f"`` (full) Defaults to ``"l"`` :type continent_fill_color: Valid matplotlib color, optional :param continent_fill_color: Color of the continents. Defaults to ``"0.9"`` which is a light gray. :type water_fill_color: Valid matplotlib color, optional :param water_fill_color: Color of all water bodies. Defaults to ``"white"``. :type marker: str :param marker: Marker symbol (see :func:`matplotlib.pyplot.scatter`). :type size: float :param size: Marker size (see :func:`matplotlib.pyplot.scatter`). :type label: bool :param label: Whether to label stations with "network.station" or not. :type color: str :param color: Face color of marker symbol (see :func:`matplotlib.pyplot.scatter`). Defaults to the first color from the single-element "Paired" color map. :type color_per_network: bool or dict :param color_per_network: If set to ``True``, each network will be drawn in a different color. A dictionary can be provided that maps network codes to color values (e.g. ``color_per_network={"GR": "black", "II": "green"}``). :type colormap: str, any matplotlib colormap, optional :param colormap: Only used if ``color_per_network=True``. Specifies which colormap is used to draw the colors for the individual networks. Defaults to the "Paired" color map. :type legend: str or None :param legend: Location string for legend, if networks are plotted in different colors (i.e. option ``color_per_network`` in use). See :func:`matplotlib.pyplot.legend` for possible values for legend location string. To disable legend set to ``None``. :type time: :class:`~obspy.core.utcdatetime.UTCDateTime` :param time: Only plot stations available at given point in time. :type show: bool :param show: Whether to show the figure after plotting or not. Can be used to do further customization of the plot before showing it. :type outfile: str :param outfile: Output file path to directly save the resulting image (e.g. ``"/tmp/image.png"``). Overrides the ``show`` option, image will not be displayed interactively. The given path/file name is also used to automatically determine the output format. Supported file formats depend on your matplotlib backend. Most backends support png, pdf, ps, eps and svg. Defaults to ``None``. :type method: str :param method: Method to use for plotting. Possible values are: * ``'basemap'`` to use the Basemap library * ``'cartopy'`` to use the Cartopy library * ``None`` to use the best available library Defaults to ``None``. :type fig: :class:`matplotlib.figure.Figure` :param fig: Figure instance to reuse, returned from a previous inventory/catalog plot call with `method=basemap`. If a previous basemap plot is reused, any kwargs regarding the basemap plot setup will be ignored (i.e. `projection`, `resolution`, `continent_fill_color`, `water_fill_color`). Note that multiple plots using colorbars likely are problematic, but e.g. one station plot (without colorbar) and one event plot (with colorbar) together should work well. :returns: Figure instance with the plot. .. rubric:: Example Mollweide projection for global overview: >>> from obspy import read_inventory >>> inv = read_inventory() >>> inv.plot(label=False) # doctest:+SKIP .. plot:: from obspy import read_inventory inv = read_inventory() inv.plot(label=False) Orthographic projection, automatic colors per network: >>> inv.plot(projection="ortho", label=False, ... color_per_network=True) # doctest:+SKIP .. plot:: from obspy import read_inventory inv = read_inventory() inv.plot(projection="ortho", label=False, color_per_network=True) Local (Albers equal area) projection, with custom colors: >>> colors = {'GR': 'blue', 'BW': 'green'} >>> inv.plot(projection="local", ... color_per_network=colors) # doctest:+SKIP .. plot:: from obspy import read_inventory inv = read_inventory() inv.plot(projection="local", color_per_network={'GR': 'blue', 'BW': 'green'}) Combining a station and event plot (uses basemap): >>> from obspy import read_inventory, read_events >>> inv = read_inventory() >>> cat = read_events() >>> fig = inv.plot(method=basemap, show=False) # doctest:+SKIP >>> cat.plot(method=basemap, fig=fig) # doctest:+SKIP .. plot:: from obspy import read_inventory, read_events inv = read_inventory() cat = read_events() fig = inv.plot(show=False) cat.plot(fig=fig) """ from obspy.imaging.maps import plot_map import matplotlib.pyplot as plt # The empty ones must be kept as otherwise inventory files without # channels will end up with nothing. inv = self.select(time=time, keep_empty=True) # lat/lon coordinates, magnitudes, dates lats = [] lons = [] labels = [] colors = [] if color_per_network and not isinstance(color_per_network, dict): from matplotlib.cm import get_cmap codes = set([n.code for n in inv]) cmap = get_cmap(name=colormap, lut=len(codes)) color_per_network = dict([(code, cmap(i)) for i, code in enumerate(sorted(codes))]) for net in inv: for sta in net: if sta.latitude is None or sta.longitude is None: msg = ("Station '%s' does not have latitude/longitude " "information and will not be plotted." % label) warnings.warn(msg) continue if color_per_network: label_ = " %s" % sta.code color_ = color_per_network.get(net.code, "k") else: label_ = " " + ".".join((net.code, sta.code)) color_ = color lats.append(sta.latitude) lons.append(sta.longitude) labels.append(label_) colors.append(color_) if not label: labels = None fig = plot_map(method, lons, lats, size, colors, labels, projection=projection, resolution=resolution, continent_fill_color=continent_fill_color, water_fill_color=water_fill_color, colormap=None, colorbar=False, marker=marker, title=None, show=False, fig=fig, **kwargs) if legend is not None and color_per_network: ax = fig.axes[0] count = len(ax.collections) for code, color in sorted(color_per_network.items()): ax.scatter([0], [0], size, color, label=code, marker=marker) # workaround for older matplotlib versions try: ax.legend(loc=legend, fancybox=True, scatterpoints=1, fontsize="medium", markerscale=0.8, handletextpad=0.1) except TypeError: leg_ = ax.legend(loc=legend, fancybox=True, scatterpoints=1, markerscale=0.8, handletextpad=0.1) leg_.prop.set_size("medium") # remove collections again solely created for legend handles ax.collections = ax.collections[:count] if outfile: fig.savefig(outfile) else: if show: plt.show() return fig
def plot(self, projection='global', resolution='l', continent_fill_color='0.9', water_fill_color='1.0', marker="v", size=15**2, label=True, color='#b15928', time=None, show=True, outfile=None, method=None, fig=None, **kwargs): # @UnusedVariable """ Creates a preview map of all stations in current network object. :type projection: str, optional :param projection: The map projection. Currently supported are: * ``"global"`` (Will plot the whole world.) * ``"ortho"`` (Will center around the mean lat/long.) * ``"local"`` (Will plot around local events) Defaults to "global" :type resolution: str, optional :param resolution: Resolution of the boundary database to use. Will be based directly to the basemap module. Possible values are: * ``"c"`` (crude) * ``"l"`` (low) * ``"i"`` (intermediate) * ``"h"`` (high) * ``"f"`` (full) Defaults to ``"l"`` :type continent_fill_color: Valid matplotlib color, optional :param continent_fill_color: Color of the continents. Defaults to ``"0.9"`` which is a light gray. :type water_fill_color: Valid matplotlib color, optional :param water_fill_color: Color of all water bodies. Defaults to ``"white"``. :type marker: str :param marker: Marker symbol (see :func:`matplotlib.pyplot.scatter`). :type label: bool :param label: Whether to label stations with "network.station" or not. :type color: str :param color: Face color of marker symbol (see :func:`matplotlib.pyplot.scatter`). Defaults to the first color from the single-element "Paired" color map. :type time: :class:`~obspy.core.utcdatetime.UTCDateTime` :param time: Only plot stations available at given point in time. :type show: bool :param show: Whether to show the figure after plotting or not. Can be used to do further customization of the plot before showing it. :type outfile: str :param outfile: Output file path to directly save the resulting image (e.g. ``"/tmp/image.png"``). Overrides the ``show`` option, image will not be displayed interactively. The given path/file name is also used to automatically determine the output format. Supported file formats depend on your matplotlib backend. Most backends support png, pdf, ps, eps and svg. Defaults to ``None``. :type method: str :param method: Method to use for plotting. Possible values are: * ``'basemap'`` to use the Basemap library * ``'cartopy'`` to use the Cartopy library * ``None`` to use the best available library Defaults to ``None``. :type fig: :class:`matplotlib.figure.Figure` :param fig: Figure instance to reuse, returned from a previous inventory/catalog plot call with `method=basemap`. If a previous basemap plot is reused, any kwargs regarding the basemap plot setup will be ignored (i.e. `projection`, `resolution`, `continent_fill_color`, `water_fill_color`). Note that multiple plots using colorbars likely are problematic, but e.g. one station plot (without colorbar) and one event plot (with colorbar) together should work well. :returns: Figure instance with the plot. .. rubric:: Example Mollweide projection for global overview: >>> from obspy import read_inventory >>> net = read_inventory()[0] >>> net.plot(label=False) # doctest:+SKIP .. plot:: from obspy import read_inventory net = read_inventory()[0] net.plot(label=False) Orthographic projection: >>> net.plot(projection="ortho") # doctest:+SKIP .. plot:: from obspy import read_inventory net = read_inventory()[0] net.plot(projection="ortho") Local (Albers equal area) projection: >>> net.plot(projection="local") # doctest:+SKIP .. plot:: from obspy import read_inventory net = read_inventory()[0] net.plot(projection="local") """ from obspy.imaging.maps import plot_map import matplotlib.pyplot as plt # lat/lon coordinates, magnitudes, dates lats = [] lons = [] labels = [] for sta in self.select(time=time).stations: label_ = " " + ".".join((self.code, sta.code)) if sta.latitude is None or sta.longitude is None: msg = ("Station '%s' does not have latitude/longitude " "information and will not be plotted." % label) warnings.warn(msg) continue lats.append(sta.latitude) lons.append(sta.longitude) labels.append(label_) if not label: labels = None fig = plot_map(method, lons, lats, size, color, labels, projection=projection, resolution=resolution, continent_fill_color=continent_fill_color, water_fill_color=water_fill_color, colormap=None, marker=marker, title=None, show=False, **kwargs) if outfile: fig.savefig(outfile) else: if show: plt.show() return fig
def plot(self, projection='global', resolution='l', continent_fill_color='0.9', water_fill_color='1.0', marker="v", size=15**2, label=True, color='#b15928', color_per_network=False, colormap="Paired", legend="upper left", time=None, show=True, outfile=None, method=None, fig=None, **kwargs): # @UnusedVariable """ Creates a preview map of all networks/stations in current inventory object. :type projection: str, optional :param projection: The map projection. Currently supported are: * ``"global"`` (Will plot the whole world.) * ``"ortho"`` (Will center around the mean lat/long.) * ``"local"`` (Will plot around local events) Defaults to ``"global"`` :type resolution: str, optional :param resolution: Resolution of the boundary database to use. Will be based directly to the basemap module. Possible values are: * ``"c"`` (crude) * ``"l"`` (low) * ``"i"`` (intermediate) * ``"h"`` (high) * ``"f"`` (full) Defaults to ``"l"`` :type continent_fill_color: Valid matplotlib color, optional :param continent_fill_color: Color of the continents. Defaults to ``"0.9"`` which is a light gray. :type water_fill_color: Valid matplotlib color, optional :param water_fill_color: Color of all water bodies. Defaults to ``"white"``. :type marker: str :param marker: Marker symbol (see :func:`matplotlib.pyplot.scatter`). :type size: float :param size: Marker size (see :func:`matplotlib.pyplot.scatter`). :type label: bool :param label: Whether to label stations with "network.station" or not. :type color: str :param color: Face color of marker symbol (see :func:`matplotlib.pyplot.scatter`). Defaults to the first color from the single-element "Paired" color map. :type color_per_network: bool or dict :param color_per_network: If set to ``True``, each network will be drawn in a different color. A dictionary can be provided that maps network codes to color values (e.g. ``color_per_network={"GR": "black", "II": "green"}``). :type colormap: str, any matplotlib colormap, optional :param colormap: Only used if ``color_per_network=True``. Specifies which colormap is used to draw the colors for the individual networks. Defaults to the "Paired" color map. :type legend: str or None :param legend: Location string for legend, if networks are plotted in different colors (i.e. option ``color_per_network`` in use). See :func:`matplotlib.pyplot.legend` for possible values for legend location string. To disable legend set to ``None``. :type time: :class:`~obspy.core.utcdatetime.UTCDateTime` :param time: Only plot stations available at given point in time. :type show: bool :param show: Whether to show the figure after plotting or not. Can be used to do further customization of the plot before showing it. :type outfile: str :param outfile: Output file path to directly save the resulting image (e.g. ``"/tmp/image.png"``). Overrides the ``show`` option, image will not be displayed interactively. The given path/file name is also used to automatically determine the output format. Supported file formats depend on your matplotlib backend. Most backends support png, pdf, ps, eps and svg. Defaults to ``None``. :type method: str :param method: Method to use for plotting. Possible values are: * ``'basemap'`` to use the Basemap library * ``'cartopy'`` to use the Cartopy library * ``None`` to use the best available library Defaults to ``None``. :type fig: :class:`matplotlib.figure.Figure` :param fig: Figure instance to reuse, returned from a previous inventory/catalog plot call with `method=basemap`. If a previous basemap plot is reused, any kwargs regarding the basemap plot setup will be ignored (i.e. `projection`, `resolution`, `continent_fill_color`, `water_fill_color`). Note that multiple plots using colorbars likely are problematic, but e.g. one station plot (without colorbar) and one event plot (with colorbar) together should work well. :returns: Figure instance with the plot. .. rubric:: Example Mollweide projection for global overview: >>> from obspy import read_inventory >>> inv = read_inventory() >>> inv.plot(label=False) # doctest:+SKIP .. plot:: from obspy import read_inventory inv = read_inventory() inv.plot(label=False) Orthographic projection, automatic colors per network: >>> inv.plot(projection="ortho", label=False, ... color_per_network=True) # doctest:+SKIP .. plot:: from obspy import read_inventory inv = read_inventory() inv.plot(projection="ortho", label=False, color_per_network=True) Local (Albers equal area) projection, with custom colors: >>> colors = {'GR': 'blue', 'BW': 'green'} >>> inv.plot(projection="local", ... color_per_network=colors) # doctest:+SKIP .. plot:: from obspy import read_inventory inv = read_inventory() inv.plot(projection="local", color_per_network={'GR': 'blue', 'BW': 'green'}) Combining a station and event plot (uses basemap): >>> from obspy import read_inventory, read_events >>> inv = read_inventory() >>> cat = read_events() >>> fig = inv.plot(method="basemap", show=False) # doctest:+SKIP >>> cat.plot(method="basemap", fig=fig) # doctest:+SKIP .. plot:: from obspy import read_inventory, read_events inv = read_inventory() cat = read_events() fig = inv.plot(show=False) cat.plot(fig=fig) """ from obspy.imaging.maps import plot_map import matplotlib.pyplot as plt # The empty ones must be kept as otherwise inventory files without # channels will end up with nothing. inv = self.select(time=time, keep_empty=True) # lat/lon coordinates, magnitudes, dates lats = [] lons = [] labels = [] colors = [] if color_per_network and not isinstance(color_per_network, dict): from matplotlib.cm import get_cmap codes = set([n.code for n in inv]) cmap = get_cmap(name=colormap, lut=len(codes)) color_per_network = dict([(code, cmap(i)) for i, code in enumerate(sorted(codes))]) for net in inv: for sta in net: if sta.latitude is None or sta.longitude is None: msg = ("Station '%s' does not have latitude/longitude " "information and will not be plotted." % label) warnings.warn(msg) continue if color_per_network: label_ = " %s" % sta.code color_ = color_per_network.get(net.code, "k") else: label_ = " " + ".".join((net.code, sta.code)) color_ = color lats.append(sta.latitude) lons.append(sta.longitude) labels.append(label_) colors.append(color_) if not label: labels = None fig = plot_map(method, lons, lats, size, colors, labels, projection=projection, resolution=resolution, continent_fill_color=continent_fill_color, water_fill_color=water_fill_color, colormap=None, colorbar=False, marker=marker, title=None, show=False, fig=fig, **kwargs) if legend is not None and color_per_network: ax = fig.axes[0] count = len(ax.collections) for code, color in sorted(color_per_network.items()): ax.scatter([0], [0], size, color, label=code, marker=marker) # workaround for older matplotlib versions try: ax.legend(loc=legend, fancybox=True, scatterpoints=1, fontsize="medium", markerscale=0.8, handletextpad=0.1) except TypeError: leg_ = ax.legend(loc=legend, fancybox=True, scatterpoints=1, markerscale=0.8, handletextpad=0.1) leg_.prop.set_size("medium") # remove collections again solely created for legend handles ax.collections = ax.collections[:count] if outfile: fig.savefig(outfile) else: if show: plt.show() return fig
def plot(self, projection='global', resolution='l', continent_fill_color='0.9', water_fill_color='1.0', label='magnitude', color='depth', colormap=None, show=True, outfile=None, method=None, fig=None, title=None, **kwargs): # @UnusedVariable """ Creates preview map of all events in current Catalog object. :type projection: str, optional :param projection: The map projection. Currently supported are: * ``"global"`` (Will plot the whole world.) * ``"ortho"`` (Will center around the mean lat/long.) * ``"local"`` (Will plot around local events) Defaults to "global" :type resolution: str, optional :param resolution: Resolution of the boundary database to use. Will be based directly to the basemap module. Possible values are: * ``"c"`` (crude) * ``"l"`` (low) * ``"i"`` (intermediate) * ``"h"`` (high) * ``"f"`` (full) Defaults to ``"l"`` :type continent_fill_color: Valid matplotlib color, optional :param continent_fill_color: Color of the continents. Defaults to ``"0.9"`` which is a light gray. :type water_fill_color: Valid matplotlib color, optional :param water_fill_color: Color of all water bodies. Defaults to ``"white"``. :type label: str, optional :param label: Events will be labelled based on the chosen property. Possible values are: * ``"magnitude"`` * ``None`` Defaults to ``"magnitude"`` :type color: str, optional :param color: The events will be color-coded based on the chosen property. Possible values are: * ``"date"`` * ``"depth"`` Defaults to ``"depth"`` :type colormap: str, any matplotlib colormap, optional :param colormap: The colormap for color-coding the events. The event with the smallest property will have the color of one end of the colormap and the event with the biggest property the color of the other end with all other events in between. Defaults to None which will use the default colormap for the date encoding and a colormap going from green over yellow to red for the depth encoding. :type show: bool :param show: Whether to show the figure after plotting or not. Can be used to do further customization of the plot before showing it. Has no effect if `outfile` is specified. :type outfile: str :param outfile: Output file path to directly save the resulting image (e.g. ``"/tmp/image.png"``). Overrides the ``show`` option, image will not be displayed interactively. The given path/filename is also used to automatically determine the output format. Supported file formats depend on your matplotlib backend. Most backends support png, pdf, ps, eps and svg. Defaults to ``None``. The figure is closed after saving it to file. :type method: str :param method: Method to use for plotting. Possible values are: * ``'basemap'`` to use the Basemap library * ``'cartopy'`` to use the Cartopy library * ``None`` to pick the best available library Defaults to ``None``. :type fig: :class:`matplotlib.figure.Figure` (or :class:`matplotlib.axes.Axes`) :param fig: Figure instance to reuse, returned from a previous inventory/catalog plot call with `method=basemap`. If a previous basemap plot is reused, any kwargs regarding the basemap plot setup will be ignored (i.e. `projection`, `resolution`, `continent_fill_color`, `water_fill_color`). Note that multiple plots using colorbars likely are problematic, but e.g. one station plot (without colorbar) and one event plot (with colorbar) together should work well. If an :class:`~matplotlib.axes.Axes` is supplied, the given axes is used to plot into and no colorbar will be produced. :type title: str :param title: Title above plot. If left ``None``, an automatic title will be generated. Set to ``""`` for no title. :returns: Figure instance with the plot. .. rubric:: Examples Mollweide projection for global overview: >>> from obspy import read_events >>> cat = read_events() >>> cat.plot() # doctest:+SKIP .. plot:: from obspy import read_events cat = read_events() cat.plot() Orthographic projection: >>> cat.plot(projection="ortho") # doctest:+SKIP .. plot:: from obspy import read_events cat = read_events() cat.plot(projection="ortho") Local (Albers equal area) projection: >>> cat.plot(projection="local") # doctest:+SKIP .. plot:: from obspy import read_events cat = read_events() cat.plot(projection="local") Combining a station and event plot (uses basemap): >>> from obspy import read_inventory, read_events >>> inv = read_inventory() >>> cat = read_events() >>> fig = inv.plot(method=basemap, show=False) # doctest:+SKIP >>> cat.plot(method=basemap, fig=fig) # doctest:+SKIP .. plot:: from obspy import read_inventory, read_events inv = read_inventory() cat = read_events() fig = inv.plot(show=False) cat.plot(fig=fig) """ from obspy.imaging.maps import plot_map, _plot_basemap_into_axes import matplotlib import matplotlib.pyplot as plt if color not in ('date', 'depth'): raise ValueError('Events can be color coded by date or depth. ' "'%s' is not supported." % (color,)) if label not in (None, 'magnitude', 'depth'): raise ValueError('Events can be labeled by magnitude or events can' ' not be labeled. ' "'%s' is not supported." % (label,)) # lat/lon coordinates, magnitudes, dates lats = [] lons = [] labels = [] mags = [] colors = [] times = [] for event in self: if not event.origins: msg = ("Event '%s' does not have an origin and will not be " "plotted." % str(event.resource_id)) warnings.warn(msg) continue if not event.magnitudes: msg = ("Event '%s' does not have a magnitude and will not be " "plotted." % str(event.resource_id)) warnings.warn(msg) continue origin = event.preferred_origin() or event.origins[0] lats.append(origin.latitude) lons.append(origin.longitude) times.append(origin.time) magnitude = event.preferred_magnitude() or event.magnitudes[0] mag = magnitude.mag mags.append(mag) labels.append((' %.1f' % mag) if mag and label == 'magnitude' else '') if color == 'date': c_ = origin.get('time') or np.nan else: c_ = (origin.get('depth') or np.nan) / 1e3 colors.append(c_) # Create the colormap for date based plotting. if colormap is None: colormap = obspy_sequential if title is None: if len(lons) > 1: # if we have a `None` in the origin time list it likely ends up # as min and/or max and causes problems.. times_ = np.ma.masked_equal(times, None).compressed() min_time = times_.min() max_time = times_.max() title = ( "{event_count} events ({start} to {end}) " "- Color codes {colorcode}, size the magnitude".format( event_count=len(self.events), start=min_time.strftime("%Y-%m-%d"), end=max_time.strftime("%Y-%m-%d"), colorcode="origin time" if color == "date" else "depth")) else: title = "Event at %s" % times[0].strftime("%Y-%m-%d") if color not in ("date", "depth"): msg = "Invalid option for 'color' parameter (%s)." % color raise ValueError(msg) min_size = 2 max_size = 30 min_size_ = min(mags) - 1 max_size_ = max(mags) + 1 if len(lons) > 1: frac = [(0.2 + (_i - min_size_)) / (max_size_ - min_size_) for _i in mags] size_plot = [(_i * (max_size - min_size)) ** 2 for _i in frac] else: size_plot = 15.0 ** 2 if isinstance(fig, matplotlib.axes.Axes): if method is not None and method != "basemap": msg = ("Plotting into an matplotlib.axes.Axes instance " "currently only implemented for `method='basemap'`.") raise NotImplementedError(msg) ax = fig fig = ax.figure _plot_basemap_into_axes( ax=ax, lons=lons, lats=lats, size=size_plot, color=colors, bmap=None, labels=labels, projection=projection, resolution=resolution, continent_fill_color=continent_fill_color, water_fill_color=water_fill_color, colormap=colormap, marker="o", title=title, show=False, **kwargs) else: fig = plot_map(method, lons, lats, size_plot, colors, labels, projection=projection, resolution=resolution, continent_fill_color=continent_fill_color, water_fill_color=water_fill_color, colormap=colormap, marker="o", title=title, show=False, fig=fig, **kwargs) if outfile: fig.savefig(outfile) plt.close(fig) else: if show: plt.show() return fig