def make(self, environ): from grond.problems.base import ProblemDataNotAvailable from grond.environment import NoRundirAvailable cm = environ.get_plot_collection_manager() mpl_init(fontsize=self.font_size) problem = environ.get_problem() dataset = environ.get_dataset() try: history = environ.get_history(subset='harvest') except (NoRundirAvailable, ProblemDataNotAvailable): history = None cm.create_group_mpl( self, self.draw_figures(problem, dataset, history), title=u'Seismic station locations', section='checks', feather_icon='target', description=u''' Plot showing seismic station locations and attributes. Station locations in dependence of distance and azimuth are shown. The center of the plot corresponds to the origin of the search space, not to the optimised location of the source. ''')
def make(self, environ): cm = environ.get_plot_collection_manager() history = environ.get_history(subset='harvest') mpl_init(fontsize=self.font_size) cm.create_group_mpl( self, self.draw_figures(history), title=u'Histogram', section='solution', feather_icon='bar-chart-2', description=u''' Distribution of the problem's parameters. The histograms are shown either as Gaussian kernel densities (red curved solid line) or as bar plots the distributions of the parameters (marginals) along with some characteristics: The red solid vertical line gives the median of the distribution and the dashed red vertical line the mean value. Dark gray vertical lines show reference parameter values if given in the event.txt file. The overlapping red-shaded areas show the 68% confidence intervals (innermost area), the 90% confidence intervals (middle area) and the minimum and maximum values (widest area). The plot ranges are defined by the given parameter bounds and show the model space. ''')
def make(self, environ): cm = environ.get_plot_collection_manager() history = environ.get_history(subset='harvest') optimiser = environ.get_optimiser() mpl_init(fontsize=self.font_size) cm.create_group_mpl( self, self.draw_figures(history, optimiser), title=u'Jointpar Plot', section='solution', feather_icon='crosshair', description=u'Source problem parameter\'s tradeoff plots.\n' u' The JointparPlot reveals relationships between' u' model parameters, like strong correlations or' u' non-linear trade-offs. A subset of model solutions' u' (from harvest) is shown in two dimensions for all' u' possible parameter pairs as points. The point color' u' indicates the misfit for the model solution with' u' cold colors (blue) for high misfit models and warm' u' colors (red) for low misfit models. The plot extend' u' is defined by the given parameter bounds and' u' shows the model space of the optimsation. Dark ' u' gray boxes show the reference parameters as given' u' in the event.txt.')
def my_model_plot(mod, axes=None): if axes is None: from matplotlib import pyplot as plt mpl_init() axes = plt.gca() else: plt = None labelspace(axes) labels_model(axes=axes) sketch_model(mod, axes=axes) z = mod.profile('z') vp = mod.profile('vp') vs = mod.profile('vs') axes.plot(vp, z, color=colors[0], lw=2.) axes.plot(vs, z, color=colors[2], lw=2.) ymin, ymax = axes.get_ylim() xmin, xmax = axes.get_xlim() xmin = 0. my = (ymax-ymin)*0.05 mx = (xmax-xmin)*0.2 axes.set_ylim(ymax+my, ymin-my) axes.set_xlim(xmin, xmax+mx) if plt: plt.show()
def make(self, environ): cm = environ.get_plot_collection_manager() history = environ.get_history() optimiser = environ.get_optimiser() mpl_init(fontsize=self.font_size) cm.create_group_mpl(self, self.draw_figures(history, optimiser), title=u'Bootstrap Misfit', section='optimiser', feather_icon='trending-down', description=u''' Sorted misfit (descending) of single bootstrap chains. For each bootstrap configuration, all models are sorted according to their misfit value (red lines) and their global misfit value (black line). (They are sorted individually for each line). The best model of every bootstrap configuration (right end model of red lines) is marked as a cross in the global misfit configuration. The horizontal black lines indicate mean and +- standard deviation of the y-axis values of these crosses. If the bootstrap configurations converge to the same region in model-space, all crosses should be close to the right end of the plot. If this is not the case, some bootstrap configurations have converged to very different places in model-space. This would indicate that there might be inconsistencies in the observations (maybe due to faulty or noisy or misoriented data). Also the shape of the curve in general can give information. A well-behaved optimisation run has approximately linear functions in this plot. Only at the end they should have a higher downward gradient. This would be the place where the objective functions of the bootstrap start to disagree. ''')
def make(self, environ): cm = environ.get_plot_collection_manager() history = environ.get_history() optimiser = environ.get_optimiser() dataset = environ.get_dataset() environ.setup_modelling() mpl_init(fontsize=self.font_size) cm.create_group_mpl(self, self.draw_figures(dataset, history, optimiser), title=u'Target Contributions', section='solution', feather_icon='thermometer', description=u''' Contributions of the targets to the total misfit. The relative contribution that each single target has in the global misfit result is plotted relative and unscales as a function of global misfit (descending). The target contribution is shown in color-filled curves with the bottom curve on the bottom and the best-fit target on top. This plot can be used to analyse the balance of targets in the optimisations. For ideal configurations, the target contributions are of similar size. If the contribution of a single target is much larger than those of all others, the weighting should be modified. ''')
def my_combi_plot(mod, paths, rays, zstart, zstop, distances=None, as_degrees=False, vred=None, phase_colors={}): from matplotlib import pyplot as plt mpl_init() ax1 = plt.subplot(211) labelspace(plt.gca()) xmin, xmax, ymin, ymax = plot_xt(paths, zstart, zstop, vred=vred, distances=distances, phase_colors=phase_colors) if distances is None: plt.xlim(xmin, xmax) labels_xt(vred=vred, as_degrees=as_degrees) plt.setp(ax1.get_xticklabels(), visible=False) plt.xlabel('') ax2 = plt.subplot(212, sharex=ax1) labelspace(plt.gca()) plot_rays(paths, rays, zstart, zstop, phase_colors=phase_colors) xmin, xmax = plt.xlim() ymin, ymax = plt.ylim() sketch_model(mod) plot_source(zstart) if distances is not None: plot_receivers(zstop, distances) labels_rays(as_degrees=as_degrees) mx = (xmax-xmin)*0.05 my = (ymax-ymin)*0.05 ax2.set_xlim(xmin-mx, xmax+mx) ax2.set_ylim(ymax+my, ymin-my) plt.show()
def make(self, environ): cm = environ.get_plot_collection_manager() mpl_init(fontsize=self.font_size) environ.setup_modelling() ds = environ.get_dataset() history = environ.get_history(subset='harvest') cm.create_group_mpl( self, self.draw_figures(ds, history), title=u'Waveform fits for best model', section='fits', feather_icon='activity', description=u' Best model\'s fits for all waveform targets. ' u' Each waveform plot gives a number of details:' u' 1) Target information (left side, from top to bottom) gives ' u' station name with component, distance to source, azimuth of ' u' station with respect to source, manual target weight, target ' u' misfit and starting time of the waveform relative to the origin ' u' time. 2) The background gray area shows the applied taper ' u' function. 3) The waveforms shown are: the observed, restituted' u' trace (light grey) and the tapered and filtered target trace ' u' (dark gray), the synthetic trace (light red) and the filtered, ' u' tapered and (if enabled) shifted synthetic target trace (red). ' u' The amplitude of the traces is scaled by the target weight (small ' u' weight, small amplitude) and normed relative to the maximum ' u' amplitude of the targets of the corresponding normalisation ' u' family. 4) Colored boxes on the upper right show the relative ' u' weight of the target within the entire dataset of the ' u' optimisation (top box, orange) and the relative misfit ' u' contribution to the global misfit of the optimisation (bottom ' u' box, red). 5) Bottom trace (red, filled) shows sample-wise the ' u' weighted misfit between observed (dark grey line) and synthetic ' u' (red) target waveforms. ')
def my_xp_plot(paths, zstart, zstop, distances=None, as_degrees=False, axes=None, phase_colors={}): if axes is None: from matplotlib import pyplot as plt mpl_init() axes = plt.gca() else: plt = None labelspace(axes) xmin, xmax = plot_xp(paths, zstart, zstop, axes=axes, phase_colors=phase_colors) if distances is not None: xmin, xmax = distances.min(), distances.max() axes.set_xlim(xmin, xmax) labels_xp(as_degrees=as_degrees, axes=axes) if plt: plt.show()
def my_rays_plot(mod, paths, rays, zstart, zstop, distances=None, as_degrees=False, axes=None, aspect=None, shade_model=True, phase_colors={}): if axes is None: from matplotlib import pyplot as plt mpl_init() axes = plt.gca() else: plt = None if paths is None: paths = list(set([ x.path for x in rays ])) labelspace(axes) plot_rays(paths, rays, zstart, zstop, axes=axes, aspect=aspect, phase_colors=phase_colors) xmin, xmax = axes.get_xlim() ymin, ymax = axes.get_ylim() sketch_model(mod, axes=axes, shade=shade_model) plot_source(zstart, axes=axes) if distances is not None: plot_receivers(zstop, distances, axes=axes) labels_rays(as_degrees=as_degrees, axes=axes) mx = (xmax-xmin)*0.05 my = (ymax-ymin)*0.05 axes.set_xlim(xmin-mx, xmax+mx) axes.set_ylim(ymax+my, ymin-my) if plt: plt.show()
def make(self, environ): cm = environ.get_plot_collection_manager() mpl_init(fontsize=self.font_size) environ.setup_modelling() ds = environ.get_dataset() history = environ.get_history(subset='harvest') scolor = { 'misfit': S(''' The synthetic markers are colored according to their respective global (non-bootstrapped) misfit value. Red indicates better fit, blue worse.'''), 'dist': S(''' The synthetic markers are colored according to their Mahalanobis distance from the mean solution.''') }.get( self.color_parameter, S(''' The synthetic markers are colored according to source parameter "%s".''' % self.color_parameter)) cm.create_group_mpl(self, self.draw_figures(ds, history), title=u'Fits of phase ratios', section='fits', feather_icon='activity', description=S(u''' Observed (black markers) and synthetic waveform amplitude phase ratio estimates (colored markers) at different stations for every Nth model in the bootstrap solution ensemble (N=%i). %s ''' % (self.istride_ensemble, scolor)))
def my_xp_plot( paths, zstart, zstop, distances=None, as_degrees=False, axes=None, phase_colors={}): if axes is None: from matplotlib import pyplot as plt mpl_init() axes = plt.gca() else: plt = None labelspace(axes) xmin, xmax = plot_xp( paths, zstart, zstop, axes=axes, phase_colors=phase_colors) if distances is not None: xmin, xmax = distances.min(), distances.max() axes.set_xlim(xmin, xmax) labels_xp(as_degrees=as_degrees, axes=axes) if plt: plt.show()
def make(self, environ): cm = environ.get_plot_collection_manager() history = environ.get_history(subset='harvest') mpl_init(fontsize=self.font_size) cm.create_group_mpl( self, self.draw_figures(history), title=u'Hudson Plot', section='solution', feather_icon='box', description=u'Hudson plot of the best fitting moment tensor.')
def make(self, environ): cm = environ.get_plot_collection_manager() mpl_init(fontsize=self.font_size) cm.create_group_mpl(self, self.draw_figures(history), title=u'shakemap', section='shakemap', feather_icon='box', description=u''' Shakemap ''')
def make(self, environ): cm = environ.get_plot_collection_manager() history = environ.get_history(subset='harvest') mpl_init(fontsize=self.font_size) cm.create_group_mpl( self, self.draw_figures(history), title=u'Moment Tensor Location', section='solution', feather_icon='target', description=u'Location plots of the best ensemble of solutions.')
def plot_init(size, save, show): fontsize = 9 mpl_init() fig = plt.figure(figsize=mpl_papersize(size, 'landscape')) labelpos = mpl_margins(fig, w=7., h=5., units=fontsize) axes = fig.add_subplot(1, 1, 1) labelpos(axes, 2., 1.5) showplt = bool(show or not save) return fig, axes, showplt
def make(self, environ): cm = environ.get_plot_collection_manager() history = environ.get_history(subset='harvest') mpl_init(fontsize=self.font_size) cm.create_group_mpl( self, self.draw_figures(history), title=u'Moment Tensor Decomopostion', section='solution', feather_icon='sun', description=u'Moment tensor decomposition of the best-fitting' u' solution.')
def make(self, environ): cm = environ.get_plot_collection_manager() history = environ.get_history(subset='harvest') mpl_init(fontsize=self.font_size) cm.create_group_mpl( self, self.draw_figures(history), title='Fuzzy Moment Tensor', section='solution', feather_icon='wind', description='A fuzzy moment tensor, illustrating the solution\'s' ' uncertainty.')
def make(self, environ): cm = environ.get_plot_collection_manager() mpl_init(fontsize=self.font_size) environ.setup_modelling() ds = environ.get_dataset() optimiser = environ.get_optimiser() environ.setup_modelling() history = environ.get_history(subset='harvest') cm.create_group_mpl( self, self.draw_figures(ds, history, optimiser), title=u'Waveform fits for best model', section='fits', feather_icon='activity', description=u''' Plot showing observed and synthetic waveform (attributes) for the best fitting model. Best model's waveform fits for all targets. Depending on the target configurations different types of comparisons are possible: (i) time domain waveform differences, (ii) amplitude spectra, (iii) envelopes, (iv) cross correlation functions. Each waveform plot gives a number of details: 1) Target information (left side, from top to bottom) gives station name with component, distance to source, azimuth of station with respect to source, target weight, target misfit and starting time of the waveform relative to the origin time. 2) The background gray area shows the applied taper function. 3) The waveforms shown are: the restituted and filtered observed trace without tapering (light grey) and the same trace with tapering and processing (dark gray), the synthetic trace (light red) and the filtered, tapered and (if enabled) shifted and processed synthetic target trace (red). The traces are scaled according to the target weight (small weight, small amplitude) and normed relative to the maximum amplitude of the targets of the corresponding normalisation family. 4) The bottom panel shows, depending on the type of comparison, sample-wise residuals for time domain comparisons (red filled), spectra of observed and synthetic traces for amplitude spectrum comparisons, or cross correlation traces. 5) Colored boxes on the upper right show the relative weight of the target within the entire dataset of the optimisation (top box, orange) and the relative misfit contribution to the global misfit of the optimisation (bottom box, red). ''')
def make(self, environ): cm = environ.get_plot_collection_manager() history = environ.get_history(subset='harvest') mpl_init(fontsize=self.font_size) cm.create_group_mpl(self, self.draw_figures(history), title=u'Hudson Plot', section='solution', feather_icon='box', description=u''' Hudson's source type plot with the ensemble of bootstrap solutions. For about 10% of the solutions (randomly chosen), the focal mechanism is depicted, others are represented as dots. The square marks the global best fitting solution. ''')
def my_rays_plot_gcs(mod, paths, rays, zstart, zstop, distances=None, phase_colors={}): from matplotlib import pyplot as plt mpl_init() globe_cross_section() axes = plt.subplot(1,1,1, projection='globe_cross_section') plot_rays(paths, rays, zstart, zstop, axes=axes, phase_colors=phase_colors) plot_source(zstart, axes=axes) if distances is not None: plot_receivers(zstop, distances, axes=axes) axes.set_ylim(0.,cake.earthradius) axes.get_yaxis().set_visible(False) if plt: plt.show()
def __init__(self, config=None): if config is None: config = SectionPlotConfig() self.config = config self._disconnect_data = [] self._width = self._height = self._pixels = None self._plt = plot.mpl_init(self.config.font_size) self._fig = fig = self._plt.figure(figsize=self.config.size_inch) rect = [0., 0., 1., 1.] self._axes_xy = Axes(fig, rect) self._axes_xz = Axes(fig, rect) self._axes_zy = Axes(fig, rect) self._view_limits = num.zeros((3, 2)) self._view_limits[:, :] = num.nan self._update_geometry() for axes in self.axes_list: fig.add_axes(axes) self._connect(axes, 'xlim_changed', self.lim_changed_handler) self._connect(axes, 'ylim_changed', self.lim_changed_handler) self._cid_resize = fig.canvas.mpl_connect('resize_event', self.resize_handler) self._connect(fig, 'dpi_changed', self.dpi_changed_handler) self._lim_changed_depth = 0
def make(self, environ): cm = environ.get_plot_collection_manager() mpl_init(fontsize=self.font_size) environ.setup_modelling() problem = environ.get_problem() results_list = [] sources = [] if self.n_random_synthetics == 0: x = problem.get_reference_model() sources.append(problem.base_source) results = problem.evaluate(x) results_list.append(results) else: for _ in range(self.n_random_synthetics): x = problem.get_random_model() sources.append(problem.get_source(x)) results = problem.evaluate(x) results_list.append(results) cm.create_group_mpl( self, self.draw_figures(sources, problem.targets, results_list), title=u'Waveform Check', section='checks', feather_icon='activity', description=u'Plot for checking the waveforms fit with a' u' number of synthetics.' u' Plot for checking the waveform fits for all' u' targets with a number of synthetics from models' u' randomly drawn from given model parameter ranges. ' u' The top waveform plot shows the observed and' u' filtered target trace. The cosine-shaped forms' u' around the observed trace shows the taper' u' positions for the drawn models in different' u' colors. ' u' the middle trace plot shows the filtered ' u' synthetic ' u' waveforms of the drawn models and the bottom plot ' u' shows the corresponding filtered and tapered' u' synthetic waveforms. The colors of taper and' u' synthetic traces are individual for each random' u' model. The given time is relative to the' u' reference event origin time.')
def make(self, environ): cm = environ.get_plot_collection_manager() history = environ.get_history(subset='harvest') mpl_init(fontsize=self.font_size) cm.create_group_mpl(self, self.draw_figures(history), title=u'MT Decomposition', section='solution', feather_icon='sun', description=u''' Moment tensor decomposition of the best-fitting solution into isotropic, deviatoric and best double couple components. Shown are the ensemble best, the ensemble mean%s and, if available, a reference mechanism. The symbol size indicates the relative strength of the components. The inversion result is consistent and stable if ensemble mean and ensemble best have similar symbol size and patterns. ''' % (', cluster results' if self.cluster_attribute else ''))
def make(self, environ): cm = environ.get_plot_collection_manager() history = environ.get_history(subset='harvest') mpl_init(fontsize=self.font_size) cm.create_group_mpl(self, self.draw_figures(history), title=u'Fuzzy MT', section='solution', feather_icon='wind', description=u''' A fuzzy moment tensor, illustrating the solution's uncertainty. The P wave radiation pattern strength of every ensemble solution is stacked for all ray spokes. The projection shows the stacked radiation pattern. If the variability of the ensemble solutions is small, the fuzzy plot has clearly separated black and white fields, consistent with the nodal lines of the %s best solution (indicated in red). ''' % ('cluster' if self.cluster_attribute is not None else 'global'))
def plot_geometry_carthesian(grid, receivers): from matplotlib import pyplot as plt plot.mpl_init() plt.figure(figsize=(9, 9)) axes = plt.subplot2grid((1, 1), (0, 0), aspect=1.0) plot.mpl_labelspace(axes) grid.plot_points(axes, system=('ne', grid.lat, grid.lon)) plot_receivers(axes, receivers, system=('ne', grid.lat, grid.lon)) distances = grid.distances(receivers) delta_grid = max(grid.dx, grid.dy, grid.dz) norm_map = gridmod.geometrical_normalization(distances, delta_grid) grid.plot(axes, norm_map, system=('ne', grid.lat, grid.lon)) plt.show()
def make(self, environ): cm = environ.get_plot_collection_manager() mpl_init(fontsize=self.font_size) environ.setup_modelling() problem = environ.get_problem() results_list = [] sources = [] if self.n_random_synthetics == 0: x = problem.get_reference_model() sources.append(problem.base_source) results = problem.evaluate(x) results_list.append(results) else: for _ in range(self.n_random_synthetics): x = problem.get_random_model() sources.append(problem.get_source(x)) results = problem.evaluate(x) results_list.append(results) cm.create_group_mpl(self, self.draw_figures(sources, problem.targets, results_list), title=u'Waveform Check', section='checks', feather_icon='activity', description=u''' Plot to judge waveform time window settings and source model parameter ranges. For each waveform target, observed and synthetic waveforms are shown. For the latter, models are randomly drawn from the configured parameter search space. The top panel shows the observed waveform; filtered (faint gray), and filtered and tapered (black). The colored outline around the observed trace shows the taper position for each drawn model in a different color. The middle panel shows the filtered synthetic waveforms of the drawn models and the bottom plot shows the corresponding filtered and tapered synthetic waveforms. The colors of taper and synthetic traces are consistent for each random model. The given time is relative to the reference event origin time. ''')
def make(self, environ): cm = environ.get_plot_collection_manager() mpl_init(fontsize=self.font_size) history = environ.get_history(subset='harvest') problem = environ.get_problem() dataset = environ.get_dataset() cm.create_group_mpl(self, self.draw_figures(problem, dataset, history), title=u'GNSS Station Distribution', section='checks', feather_icon='target', description=u''' Plots showing the GNSS station distribution and their weight. This polar plot visualises the station distribution in distance and azimuth, the marker's size is scaled to the stations weight (mean of spatial components). ''')
def make(self, environ): cm = environ.get_plot_collection_manager() history = environ.get_history() mpl_init(fontsize=self.font_size) cm.create_group_mpl( self, self.draw_figures(history), title=u'Target Contributions', section='solution', feather_icon='thermometer', description=u' Contributions of the targets to the total misfit.\n' u' The relative contribution that each single target' u' has in the global misfit result is plotted relative' u' and unscales as a function of global misfit' u' (descending). \nThe target contribution is shown in' u' color-filled curves with the bottom curve on the' u' bottom and the best-fit target on top. This plot' u' can be used to analyse the balance of targets in' u' the optimisations and it indicates poorly fitting' u' targets easily.')
def make(self, environ): environ.setup_modelling() cm = environ.get_plot_collection_manager() history = environ.get_history(subset='harvest') mpl_init(fontsize=self.font_size) self._to_be_closed = [] cm.create_group_mpl(self, self.draw_figures(history), title=u'Volume Location', section='solution', feather_icon='target', description=u''' Location plot of the ensemble of best solutions in three cross-sections. The coordinate range is defined by the search space given in the config file. Symbols show best volume locations, and colors indicate low (red) and high (blue) misfit. ''') for obj in self._to_be_closed: obj.close()
def make(self, environ): cm = environ.get_plot_collection_manager() history = environ.get_history() mpl_init(fontsize=self.font_size) cm.create_group_mpl(self, self.draw_figures(history), title=u'Sequence Plots', section='optimiser', description=u'Sequence plots for all parameters of' u' the optimisation.\n ' u' The sequence of all the parameter values' u' is either a function of the optimisation' u' in progress or of the misfit from high to' u' low. This plot can be used to check on' u' convergence or see if model parameters push' u' the given bounds. \nThe color always shows the' u' relative misfit. Relatively high misfits' u' are in cold blue colors and relatively low' u' misfits in red. The last panel gives the ' u' corresponding misfit values.', feather_icon='fast-forward')
from pyrocko import topo, plot, orthodrome as od lon_min, lon_max, lat_min, lat_max = 14.34, 14.50, 40.77, 40.87 dem_name = 'SRTMGL3' # extract gridded topography (possibly downloading first) tile = topo.get(dem_name, (lon_min, lon_max, lat_min, lat_max)) # geographic to local cartesian coordinates lons = tile.x() lats = tile.y() lons2 = num.tile(lons, lats.size) lats2 = num.repeat(lats, lons.size) norths, easts = od.latlon_to_ne_numpy(lats[0], lons[0], lats2, lons2) norths = norths.reshape((lats.size, lons.size)) easts = easts.reshape((lats.size, lons.size)) # plot it plt = plot.mpl_init(fontsize=10.) fig = plt.figure(figsize=plot.mpl_papersize('a5', 'landscape')) axes = fig.add_subplot(1, 1, 1, aspect=1.0) cbar = axes.pcolormesh(easts, norths, tile.data, cmap='gray', shading='gouraud') fig.colorbar(cbar, label='Altitude [m]') axes.set_title(dem_name) axes.set_xlim(easts.min(), easts.max()) axes.set_ylim(norths.min(), norths.max()) axes.set_xlabel('Easting [m]') axes.set_ylabel('Northing [m]') fig.savefig('topo_example.png')
from matplotlib import pyplot as plt from pyrocko.plot import mpl_init, mpl_margins, mpl_papersize # from pyrocko.plot import mpl_labelspace fontsize = 9. # in points # set some Pyrocko style defaults mpl_init(fontsize=fontsize) fig = plt.figure(figsize=mpl_papersize('a4', 'landscape')) # let margins be proportional to selected font size, e.g. top and bottom # margin are set to be 5*fontsize = 45 [points] labelpos = mpl_margins(fig, w=7., h=5., units=fontsize) axes = fig.add_subplot(1, 1, 1) # positioning of axis labels # mpl_labelspace(axes) # either: relative to axis tick labels labelpos(axes, 2., 1.5) # or: relative to left/bottom paper edge axes.plot([0, 1], [0, 9]) axes.set_xlabel('Time [s]') axes.set_ylabel('Amplitude [m]') fig.savefig('plot_skeleton.pdf') plt.show()
def plot( responses, filename=None, dpi=100, fmin=0.01, fmax=100., nf=100, normalize=False, fontsize=10., figsize=None, styles=None, labels=None): ''' Draw instrument responses in Bode plot style. :param responses: instrument responses as :py:class:`pyrocko.trace.FrequencyResponse` objects :param fmin: minimum frequency [Hz] :param fmax: maximum frequency [Hz] :param nf: number of frequencies where to evaluate the response :param normalize: if ``True`` normalize flat part of response to be ``1`` :param styles: :py:class:`list` of :py:class:`dict` objects with keyword arguments to be passed to matplotlib's :py:meth:`matplotlib.axes.Axes.plot` function when drawing the response lines. Length must match number of responses. :param filename: file name to pass to matplotlib's ``savefig`` function. If ``None``, the plot is shown with :py:func:`matplotlib.pyplot.show`. :param fontsize: font size in points used in axis labels and legend :param figsize: :py:class:`tuple`, ``(width, height)`` in inches :param labels: :py:class:`list` of names to show in legend. Length must correspond to number of responses. ''' from matplotlib import pyplot as plt from pyrocko.plot import mpl_init, mpl_margins, mpl_papersize from pyrocko.plot import graph_colors, to01 mpl_init(fontsize=fontsize) if figsize is None: figsize = mpl_papersize('a4', 'portrait') fig = plt.figure(figsize=figsize) labelpos = mpl_margins( fig, w=7., h=5., units=fontsize, nw=1, nh=2, hspace=2.) axes_amplitude = fig.add_subplot(2, 1, 1) labelpos(axes_amplitude, 2., 1.5) axes_phase = fig.add_subplot(2, 1, 2) labelpos(axes_phase, 2., 1.5) setup_axes(axes_amplitude, axes_phase) if styles is None: styles = [ dict(color=to01(graph_colors[i % len(graph_colors)])) for i in range(len(responses))] else: assert len(styles) == len(responses) if labels is None: labels = [None] * len(responses) else: assert len(labels) == len(responses) a_ranges, p_ranges = [], [] have_labels = False for style, resp, label in zip(styles, responses, labels): a_range, p_range = draw( response=resp, axes_amplitude=axes_amplitude, axes_phase=axes_phase, fmin=fmin, fmax=fmax, nf=nf, normalize=normalize, style=style, label=label) if label is not None: have_labels = True a_ranges.append(a_range) p_ranges.append(p_range) if have_labels: axes_amplitude.legend(loc='lower right', prop=dict(size=fontsize)) a_ranges = num.array(a_ranges) p_ranges = num.array(p_ranges) amin, amax = num.min(a_ranges), num.max(a_ranges) pmin, pmax = num.min(p_ranges), num.max(p_ranges) amin *= 0.5 amax *= 2.0 pmin -= 0.5 pmax += 0.5 axes_amplitude.set_ylim(amin, amax) axes_phase.set_ylim(pmin, pmax) axes_amplitude.set_xlim(fmin, fmax) axes_phase.set_xlim(fmin, fmax) if filename is not None: fig.savefig(filename, dpi=dpi) else: plt.show()