1# http://pyrocko.org - GPLv3
2#
3# The Pyrocko Developers, 21st Century
4# ---|P------/S----------~Lg----------
6from __future__ import print_function
8from collections import defaultdict
9import math
10import logging
12import numpy as num
13from matplotlib.axes import Axes
14# from matplotlib.ticker import MultipleLocator
15from matplotlib import cm, colors, colorbar
17from pyrocko.guts import Tuple, Float, Object
18from pyrocko import plot
20import scipy.optimize
22logger = logging.getLogger('pyrocko.plot.smartplot')
24guts_prefix = 'pf'
26inch = 2.54
29def limits(points):
30 lims = num.zeros((3, 2))
31 if points.size != 0:
32 lims[:, 0] = num.min(points, axis=0)
33 lims[:, 1] = num.max(points, axis=0)
35 return lims
38def wcenter(rect):
39 return rect[0] + rect[2]*0.5
42def hcenter(rect):
43 return rect[1] + rect[3]*0.5
46def window_min(n, w, ml, mu, s, x):
47 return ml + x/float(n) * (w - (ml + mu + (n-1)*s)) + math.floor(x) * s
50def window_max(n, w, ml, mu, s, x):
51 return ml + x/float(n) * (w - (ml + mu + (n-1)*s)) + (math.floor(x)-1) * s
54def make_smap(cmap, norm=None):
55 if isinstance(norm, tuple):
56 norm = colors.Normalize(*norm, clip=False)
57 smap = cm.ScalarMappable(cmap=cmap, norm=norm)
58 smap._A = [] # not needed in newer versions of mpl?
59 return smap
62def solve_layout_fixed_panels(size, shape, limits, aspects, fracs=None):
64 weight_aspect = 1000.
66 sx, sy = size
67 nx, ny = shape
68 nvar = nx+ny
69 vxs, vys = limits
70 uxs = vxs[:, 1] - vxs[:, 0]
71 uys = vys[:, 1] - vys[:, 0]
72 aspects_xx, aspects_yy, aspects_xy = aspects
74 if fracs is None:
75 wxs = num.full(nx, sx / nx)
76 wys = num.full(ny, sy / ny)
77 else:
78 frac_x, frac_y = fracs
79 wxs = sx * frac_x / num.sum(frac_x)
80 wys = sy * frac_y / num.sum(frac_y)
82 data = []
83 weights = []
84 rows = []
85 bounds = []
86 for ix in range(nx):
87 u = uxs[ix]
88 assert u > 0.0
89 row = num.zeros(nvar)
90 row[ix] = u
91 rows.append(row)
92 data.append(wxs[ix])
93 weights.append(1.0 / u)
94 bounds.append((0, wxs[ix] / u))
96 for iy in range(ny):
97 u = uys[iy]
98 assert u > 0.0
99 row = num.zeros(nvar)
100 row[nx+iy] = u
101 rows.append(row)
102 data.append(wys[iy])
103 weights.append(1.0)
104 bounds.append((0, wys[iy] / u))
106 for ix1, ix2, aspect in aspects_xx:
107 row = num.zeros(nvar)
108 row[ix1] = aspect
109 row[ix2] = -1.0
110 weights.append(weight_aspect/aspect)
111 rows.append(row)
112 data.append(0.0)
114 for iy1, iy2, aspect in aspects_yy:
115 row = num.zeros(nvar)
116 row[nx+iy1] = aspect
117 row[nx+iy2] = -1.0
118 weights.append(weight_aspect/aspect)
119 rows.append(row)
120 data.append(0.0)
122 for ix, iy, aspect in aspects_xy:
123 row = num.zeros(nvar)
124 row[ix] = aspect
125 row[nx+iy] = -1.0
126 weights.append(weight_aspect/aspect)
127 rows.append(row)
128 data.append(0.0)
130 weights = num.array(weights)
131 data = num.array(data)
132 mat = num.vstack(rows) * weights[:, num.newaxis]
133 data *= weights
135 bounds = num.array(bounds).T
137 model = scipy.optimize.lsq_linear(mat, data, bounds).x
139 cxs = model[:nx]
140 cys = model[nx:nx+ny]
142 vlimits_x = num.zeros((nx, 2))
143 for ix in range(nx):
144 u = wxs[ix] / cxs[ix]
145 vmin, vmax = vxs[ix]
146 udata = vmax - vmin
147 eps = 1e-7 * u
148 assert(udata <= u + eps)
149 vlimits_x[ix, 0] = (vmin + vmax) / 2.0 - u / 2.0
150 vlimits_x[ix, 1] = (vmin + vmax) / 2.0 + u / 2.0
152 vlimits_y = num.zeros((ny, 2))
153 for iy in range(ny):
154 u = wys[iy] / cys[iy]
155 vmin, vmax = vys[iy]
156 udata = vmax - vmin
157 eps = 1e-7 * u
158 assert(udata <= u + eps)
159 vlimits_y[iy, 0] = (vmin + vmax) / 2.0 - u / 2.0
160 vlimits_y[iy, 1] = (vmin + vmax) / 2.0 + u / 2.0
162 def check_aspect(a, awant, eps=1e-2):
163 if abs(1.0 - (a/awant)) > eps:
164 logger.error(
165 'Unable to comply with requested aspect ratio '
166 '(wanted: %g, achieved: %g)' % (awant, a))
168 for ix1, ix2, aspect in aspects_xx:
169 check_aspect(cxs[ix2] / cxs[ix1], aspect)
171 for iy1, iy2, aspect in aspects_yy:
172 check_aspect(cys[iy2] / cys[iy1], aspect)
174 for ix, iy, aspect in aspects_xy:
175 check_aspect(cys[iy] / cxs[ix], aspect)
177 return (vlimits_x, vlimits_y), (wxs, wys)
180def solve_layout_iterative(size, shape, limits, aspects, niterations=3):
182 sx, sy = size
183 nx, ny = shape
184 vxs, vys = limits
185 uxs = vxs[:, 1] - vxs[:, 0]
186 uys = vys[:, 1] - vys[:, 0]
187 aspects_xx, aspects_yy, aspects_xy = aspects
189 fracs_x, fracs_y = num.ones(nx), num.ones(ny)
190 for i in range(niterations):
191 (vlimits_x, vlimits_y), (wxs, wys) = solve_layout_fixed_panels(
192 size, shape, limits, aspects, (fracs_x, fracs_y))
194 uxs_view = vlimits_x[:, 1] - vlimits_x[:, 0]
195 uys_view = vlimits_y[:, 1] - vlimits_y[:, 0]
196 wxs_used = wxs * uxs / uxs_view
197 wys_used = wys * uys / uys_view
198 # wxs_wasted = wxs * (1.0 - uxs / uxs_view)
199 # wys_wasted = wys * (1.0 - uys / uys_view)
201 fracs_x = wxs_used
202 fracs_y = wys_used
204 return (vlimits_x, vlimits_y), (wxs, wys)
207class NotEnoughSpace(Exception):
208 pass
211class PlotConfig(Object):
213 font_size = Float.T(default=9.0)
215 size_cm = Tuple.T(
216 2, Float.T(), default=(20., 20.))
218 margins_em = Tuple.T(
219 4, Float.T(), default=(7., 5., 7., 5.))
221 separator_em = Float.T(default=1.5)
223 colorbar_width_em = Float.T(default=2.0)
225 @property
226 def size_inch(self):
227 return self.size_cm[0]/inch, self.size_cm[1]/inch
230class Plot(object):
232 def __init__(
233 self, x_dims=['x'], y_dims=['y'], z_dims=[], config=None,
234 fig=None):
236 if config is None:
237 config = PlotConfig()
239 self._shape = len(x_dims), len(y_dims)
241 dims = []
242 for dim in x_dims + y_dims + z_dims:
243 dim = dim.lstrip('-')
244 if dim not in dims:
245 dims.append(dim)
247 self.config = config
248 self._disconnect_data = []
249 self._width = self._height = self._pixels = None
250 self._plt = plot.mpl_init(self.config.font_size)
252 if fig is None:
253 fig = self._plt.figure(figsize=self.config.size_inch)
255 self._fig = fig
256 self._colorbar_width = 0.0
257 self._colorbar_height = 0.0
258 self._colorbar_axes = []
260 self._dims = dims
261 self._dim_index = self._dims.index
262 self._ndims = len(dims)
263 self._labels = {}
264 self._aspects = {}
266 self.setup_axes()
268 self._view_limits = num.zeros((self._ndims, 2))
270 self._view_limits[:, :] = num.nan
271 self._last_mpl_view_limits = None
273 self._x_dims = [dim.lstrip('-') for dim in x_dims]
274 self._x_dims_invert = [dim.startswith('-') for dim in x_dims]
276 self._y_dims = [dim.lstrip('-') for dim in y_dims]
277 self._y_dims_invert = [dim.startswith('-') for dim in y_dims]
279 self._z_dims = [dim.lstrip('-') for dim in z_dims]
280 self._z_dims_invert = [dim.startswith('-') for dim in z_dims]
282 self._mappables = {}
283 self._updating_layout = False
285 self._update_geometry()
287 for axes in self.axes_list:
288 fig.add_axes(axes)
289 self._connect(axes, 'xlim_changed', self.lim_changed_handler)
290 self._connect(axes, 'ylim_changed', self.lim_changed_handler)
292 self._cid_resize = fig.canvas.mpl_connect(
293 'resize_event', self.resize_handler)
295 self._connect(fig, 'dpi_changed', self.dpi_changed_handler)
297 self._lim_changed_depth = 0
299 def axes(self, ix, iy):
300 if not (isinstance(ix, int) and isinstance(iy, int)):
301 ix = self._x_dims.index(ix)
302 iy = self._y_dims.index(iy)
304 return self._axes[iy][ix]
306 def set_color_dim(self, mappable, dim):
307 assert dim in self._dims
308 self._mappables[mappable] = dim
310 def set_aspect(self, ydim, xdim, aspect=1.0):
311 self._aspects[ydim, xdim] = aspect
313 @property
314 def dims(self):
315 return self._dims
317 @property
318 def fig(self):
319 return self._fig
321 @property
322 def axes_list(self):
323 axes = []
324 for row in self._axes:
325 axes.extend(row)
326 return axes
328 @property
329 def axes_bottom_list(self):
330 return self._axes[0]
332 @property
333 def axes_left_list(self):
334 return [row[0] for row in self._axes]
336 def setup_axes(self):
337 rect = [0., 0., 1., 1.]
338 nx, ny = self._shape
339 axes = []
340 for iy in range(ny):
341 axes.append([])
342 for ix in range(nx):
343 axes[-1].append(Axes(self.fig, rect))
345 self._axes = axes
347 def _connect(self, obj, sig, handler):
348 cid = obj.callbacks.connect(sig, handler)
349 self._disconnect_data.append((obj, cid))
351 def _disconnect_all(self):
352 for obj, cid in self._disconnect_data:
353 obj.callbacks.disconnect(cid)
355 self._fig.canvas.mpl_disconnect(self._cid_resize)
357 def dpi_changed_handler(self, fig):
358 if self._updating_layout:
359 return
361 self._update_geometry()
363 def resize_handler(self, event):
364 if self._updating_layout:
365 return
367 self._update_geometry()
369 def lim_changed_handler(self, axes):
370 if self._updating_layout:
371 return
373 current = self._get_mpl_view_limits()
374 last = self._last_mpl_view_limits
376 for iy, ix, axes in self.iaxes():
377 acurrent = current[iy][ix]
378 alast = last[iy][ix]
379 if acurrent[0] != alast[0]:
380 xdim = self._x_dims[ix]
381 logger.debug(
382 'X limits have been changed interactively in subplot '
383 '(%i, %i)' % (ix, iy))
384 self.set_lim(xdim, *sorted(acurrent[0]))
386 if acurrent[1] != alast[1]:
387 ydim = self._y_dims[iy]
388 logger.debug(
389 'Y limits have been changed interactively in subplot '
390 '(%i, %i)' % (ix, iy))
391 self.set_lim(ydim, *sorted(acurrent[1]))
393 self._update_layout()
395 def _update_geometry(self):
396 w, h = self._fig.canvas.get_width_height()
397 p = self.get_pixels_factor()
399 if (self._width, self._height, self._pixels) != (w, h, p):
400 self._width = w
401 self._height = h
402 self._pixels = p
403 self._update_layout()
405 @property
406 def margins(self):
407 return tuple(
408 x * self.config.font_size / self._pixels
409 for x in self.config.margins_em)
411 @property
412 def separator(self):
413 return self.config.separator_em * self.config.font_size / self._pixels
415 def rect_to_figure_coords(self, rect):
416 left, bottom, width, height = rect
417 return (
418 left / self._width,
419 bottom / self._height,
420 width / self._width,
421 height / self._height)
423 def point_to_axes_coords(self, axes, point):
424 x, y = point
425 aleft, abottom, awidth, aheight = axes.get_position().bounds
427 x_fig = x / self._width
428 y_fig = y / self._height
430 x_axes = (x_fig - aleft) / awidth
431 y_axes = (y_fig - abottom) / aheight
433 return (x_axes, y_axes)
435 def get_pixels_factor(self):
436 try:
437 r = self._fig.canvas.get_renderer()
438 return 1.0 / r.points_to_pixels(1.0)
439 except AttributeError:
440 return 1.0
442 def make_limits(self, lims):
443 a = plot.AutoScaler(space=0.05)
444 return a.make_scale(lims)[:2]
446 def iaxes(self):
447 for iy, row in enumerate(self._axes):
448 for ix, axes in enumerate(row):
449 yield iy, ix, axes
451 def get_data_limits(self):
452 dim_to_values = defaultdict(list)
453 for iy, ix, axes in self.iaxes():
454 dim_to_values[self._y_dims[iy]].extend(
455 axes.get_yaxis().get_data_interval())
456 dim_to_values[self._x_dims[ix]].extend(
457 axes.get_xaxis().get_data_interval())
459 for mappable, dim in self._mappables.items():
460 dim_to_values[dim].extend(mappable.get_clim())
462 lims = num.zeros((self._ndims, 2))
463 for idim in range(self._ndims):
464 dim = self._dims[idim]
465 if dim in dim_to_values:
466 vs = num.array(
467 dim_to_values[self._dims[idim]], dtype=float)
468 vs = vs[num.isfinite(vs)]
469 if vs.size > 0:
470 lims[idim, :] = num.min(vs), num.max(vs)
471 else:
472 lims[idim, :] = num.nan, num.nan
473 else:
474 lims[idim, :] = num.nan, num.nan
476 lims[num.logical_not(num.isfinite(lims))] = 0.0
477 return lims
479 def set_lim(self, dim, vmin, vmax):
480 assert(vmin <= vmax)
481 self._view_limits[self._dim_index(dim), :] = vmin, vmax
483 def _get_mpl_view_limits(self):
484 vl = []
485 for row in self._axes:
486 vl_row = []
487 for axes in row:
488 vl_row.append((
489 axes.get_xaxis().get_view_interval().tolist(),
490 axes.get_yaxis().get_view_interval().tolist()))
492 vl.append(vl_row)
494 return vl
496 def _remember_mpl_view_limits(self):
497 self._last_mpl_view_limits = self._get_mpl_view_limits()
499 def window_xmin(self, x):
500 return window_min(
501 self._shape[0], self._width,
502 self.margins[0], self.margins[2] + self._colorbar_width,
503 self.separator, x)
505 def window_xmax(self, x):
506 return window_max(
507 self._shape[0], self._width,
508 self.margins[0], self.margins[2] + self._colorbar_width,
509 self.separator, x)
511 def window_ymin(self, y):
512 return window_min(
513 self._shape[1], self._height,
514 self.margins[3] + self._colorbar_height, self.margins[1],
515 self.separator, y)
517 def window_ymax(self, y):
518 return window_max(
519 self._shape[1], self._height,
520 self.margins[3] + self._colorbar_height, self.margins[1],
521 self.separator, y)
523 def _update_layout(self):
524 assert not self._updating_layout
525 self._updating_layout = True
526 data_limits = self.get_data_limits()
528 limits = num.zeros((self._ndims, 2))
529 for idim in range(self._ndims):
530 limits[idim, :] = self.make_limits(data_limits[idim, :])
532 mask = num.isfinite(self._view_limits)
533 limits[mask] = self._view_limits[mask]
535 # deltas = limits[:, 1] - limits[:, 0]
537 # data_w = deltas[0]
538 # data_h = deltas[1]
540 ml, mt, mr, mb = self.margins
541 mr += self._colorbar_width
542 mb += self._colorbar_height
543 sw = sh = self.separator
545 nx, ny = self._shape
547 # data_r = data_h / data_w
548 em = self.config.font_size
549 w = self._width
550 h = self._height
551 fig_w_avail = w - mr - ml - (nx-1) * sw
552 fig_h_avail = h - mt - mb - (ny-1) * sh
554 if fig_w_avail <= 0.0 or fig_h_avail <= 0.0:
555 raise NotEnoughSpace()
557 x_limits = num.zeros((nx, 2))
558 for ix, xdim in enumerate(self._x_dims):
559 x_limits[ix, :] = limits[self._dim_index(xdim)]
561 y_limits = num.zeros((ny, 2))
562 for iy, ydim in enumerate(self._y_dims):
563 y_limits[iy, :] = limits[self._dim_index(ydim)]
565 def get_aspect(dim1, dim2):
566 if (dim2, dim1) in self._aspects:
567 return 1.0/self._aspects[dim2, dim1]
569 return self._aspects.get((dim1, dim2), None)
571 aspects_xx = []
572 for ix1, xdim1 in enumerate(self._x_dims):
573 for ix2, xdim2 in enumerate(self._x_dims):
574 aspect = get_aspect(xdim2, xdim1)
575 if aspect:
576 aspects_xx.append((ix1, ix2, aspect))
578 aspects_yy = []
579 for iy1, ydim1 in enumerate(self._y_dims):
580 for iy2, ydim2 in enumerate(self._y_dims):
581 aspect = get_aspect(ydim2, ydim1)
582 if aspect:
583 aspects_yy.append((iy1, iy2, aspect))
585 aspects_xy = []
586 for iy, ix, axes in self.iaxes():
587 xdim = self._x_dims[ix]
588 ydim = self._y_dims[iy]
589 aspect = get_aspect(ydim, xdim)
590 if aspect:
591 aspects_xy.append((ix, iy, aspect))
593 (x_limits, y_limits), (aws, ahs) = solve_layout_iterative(
594 size=(fig_w_avail, fig_h_avail),
595 shape=(nx, ny),
596 limits=(x_limits, y_limits),
597 aspects=(
598 aspects_xx,
599 aspects_yy,
600 aspects_xy))
602 for iy, ix, axes in self.iaxes():
603 rect = [
604 ml + num.sum(aws[:ix])+(ix*sw),
605 mb + num.sum(ahs[:iy])+(iy*sh),
606 aws[ix], ahs[iy]]
608 axes.set_position(
609 self.rect_to_figure_coords(rect), which='both')
611 self.set_label_coords(
612 axes, 'x', [wcenter(rect), 3*em + self._colorbar_height])
614 self.set_label_coords(
615 axes, 'y', [3*em, hcenter(rect)])
617 axes.get_xaxis().set_tick_params(
618 bottom=(iy == 0), top=(iy == ny-1),
619 labelbottom=(iy == 0), labeltop=False)
621 axes.get_yaxis().set_tick_params(
622 left=(ix == 0), right=(ix == nx-1),
623 labelleft=(ix == 0), labelright=False)
625 istride = -1 if self._x_dims_invert[ix] else 1
626 axes.set_xlim(*x_limits[ix, ::istride])
627 istride = -1 if self._y_dims_invert[iy] else 1
628 axes.set_ylim(*y_limits[iy, ::istride])
630 self._remember_mpl_view_limits()
632 for mappable, dim in self._mappables.items():
633 mappable.set_clim(*limits[self._dim_index(dim)])
635 # scaler = plot.AutoScaler()
637 # aspect tick incs same
638 #
639 # inc = scaler.make_scale(
640 # [0, min(data_expanded_w, data_expanded_h)],
641 # override_mode='off')[2]
642 #
643 # for axes in self.axes_list:
644 # axes.set_xlim(*limits[0, :])
645 # axes.set_ylim(*limits[1, :])
646 #
647 # tl = MultipleLocator(inc)
648 # axes.get_xaxis().set_major_locator(tl)
649 # tl = MultipleLocator(inc)
650 # axes.get_yaxis().set_major_locator(tl)
652 for axes, orientation, position in self._colorbar_axes:
653 if orientation == 'horizontal':
654 xmin = self.window_xmin(position[0])
655 xmax = self.window_xmax(position[1])
656 ymin = mb - self._colorbar_height
657 ymax = mb - self._colorbar_height \
658 + self.config.colorbar_width_em * em
659 else:
660 ymin = self.window_ymin(position[0])
661 ymax = self.window_ymax(position[1])
662 xmin = w - mr + 2 * sw
663 xmax = w - mr + 2 * sw + self.config.colorbar_width_em * em
665 rect = [xmin, ymin, xmax-xmin, ymax-ymin]
666 axes.set_position(
667 self.rect_to_figure_coords(rect), which='both')
669 for ix, axes in enumerate(self.axes_bottom_list):
670 dim = self._x_dims[ix]
671 s = self._labels.get(dim, dim)
672 axes.set_xlabel(s)
674 for iy, axes in enumerate(self.axes_left_list):
675 dim = self._y_dims[iy]
676 s = self._labels.get(dim, dim)
677 axes.set_ylabel(s)
679 self._updating_layout = False
681 def set_label_coords(self, axes, which, point):
682 axis = axes.get_xaxis() if which == 'x' else axes.get_yaxis()
683 axis.set_label_coords(*self.point_to_axes_coords(axes, point))
685 def plot(self, points, *args, **kwargs):
686 for iy, row in enumerate(self._axes):
687 y = points[:, self._dim_index(self._y_dims[iy])]
688 for ix, axes in enumerate(row):
689 x = points[:, self._dim_index(self._x_dims[ix])]
690 axes.plot(x, y, *args, **kwargs)
692 def close(self):
693 self._disconnect_all()
694 self._plt.close(self._fig)
696 def show(self):
697 self._plt.show()
699 def set_label(self, dim, s):
700 # just set attrbitute handle in update_layout
701 self._labels[dim] = s
703 def colorbar(
704 self, dim,
705 orientation='vertical',
706 position=None):
708 if dim not in self._dims:
709 raise Exception(
710 'dimension "%s" is not defined')
712 if orientation not in ('vertical', 'horizontal'):
713 raise Exception(
714 'orientation must be "vertical" or "horizontal"')
716 mappable = None
717 for mappable_, dim_ in self._mappables.items():
718 if dim_ == dim:
719 if mappable is None:
720 mappable = mappable_
721 else:
722 mappable_.set_cmap(mappable.get_cmap())
724 if mappable is None:
725 raise Exception(
726 'no mappable registered for dimension "%s"' % dim)
728 if position is None:
729 if orientation == 'vertical':
730 position = (0, self._shape[1])
731 else:
732 position = (0, self._shape[0])
734 em = self.config.font_size
736 if orientation == 'vertical':
737 self._colorbar_width = self.config.colorbar_width_em*em + \
738 self.separator * 2.0
739 else:
740 self._colorbar_height = self.config.colorbar_width_em*em + \
741 self.separator + self.margins[3]
743 axes = Axes(self.fig, [0., 0., 1., 1.])
744 self.fig.add_axes(axes)
746 self._colorbar_axes.append(
747 (axes, orientation, position))
749 self._update_layout()
750 # axes.plot([1], [1])
751 label = self._labels.get(dim, dim)
752 return colorbar.Colorbar(
753 axes, mappable, orientation=orientation, label=label)
755 def __call__(self, *args):
756 return self.axes(*args)
759if __name__ == '__main__':
760 import sys
761 from pyrocko import util
763 logging.getLogger('matplotlib').setLevel(logging.WARNING)
764 util.setup_logging('smartplot', 'debug')
766 iplots = [int(x) for x in sys.argv[1:]]
768 if 0 in iplots:
769 p = Plot(['x'], ['y'])
770 n = 100
771 x = num.arange(n) * 2.0
772 y = num.random.normal(size=n)
773 p(0, 0).plot(x, y, 'o')
774 p.show()
776 if 1 in iplots:
777 p = Plot(['x', 'x'], ['y'])
778 n = 100
779 x = num.arange(n) * 2.0
780 y = num.random.normal(size=n)
781 p(0, 0).plot(x, y, 'o')
782 x = num.arange(n) * 2.0
783 y = num.random.normal(size=n)
784 p(1, 0).plot(x, y, 'o')
785 p.show()
787 if 11 in iplots:
788 p = Plot(['x'], ['y'])
789 p.set_aspect('y', 'x', 2.0)
790 n = 100
791 xy = num.random.normal(size=(n, 2))
792 p(0, 0).plot(xy[:, 0], xy[:, 1], 'o')
793 p.show()
795 if 12 in iplots:
796 p = Plot(['x', 'x2'], ['y'])
797 p.set_aspect('x2', 'x', 2.0)
798 p.set_aspect('y', 'x', 2.0)
799 n = 100
800 xy = num.random.normal(size=(n, 2))
801 p(0, 0).plot(xy[:, 0], xy[:, 1], 'o')
802 p(1, 0).plot(xy[:, 0], xy[:, 1], 'o')
803 p.show()
805 if 13 in iplots:
806 p = Plot(['x'], ['y', 'y2'])
807 p.set_aspect('y2', 'y', 2.0)
808 p.set_aspect('y', 'x', 2.0)
809 n = 100
810 xy = num.random.normal(size=(n, 2))
811 p(0, 0).plot(xy[:, 0], xy[:, 1], 'o')
812 p(0, 1).plot(xy[:, 0], xy[:, 1], 'o')
813 p.show()
815 if 2 in iplots:
816 p = Plot(['easting', 'depth'], ['northing', 'depth'])
818 n = 100
820 ned = num.random.normal(size=(n, 3))
821 p(0, 0).plot(ned[:, 1], ned[:, 0], 'o')
822 p(1, 0).plot(ned[:, 2], ned[:, 0], 'o')
823 p(0, 1).plot(ned[:, 1], ned[:, 2], 'o')
824 p.show()
826 if 3 in iplots:
827 p = Plot(['easting', 'depth'], ['-depth', 'northing'])
828 p.set_aspect('easting', 'northing', 1.0)
829 p.set_aspect('easting', 'depth', 0.5)
830 p.set_aspect('northing', 'depth', 0.5)
832 n = 100
834 ned = num.random.normal(size=(n, 3))
835 ned[:, 2] *= 0.25
836 p(0, 1).plot(ned[:, 1], ned[:, 0], 'o', color='black')
837 p(0, 0).plot(ned[:, 1], ned[:, 2], 'o')
838 p(1, 1).plot(ned[:, 2], ned[:, 0], 'o')
839 p(1, 0).set_visible(False)
840 p.set_lim('depth', 0., 0.2)
841 p.show()
843 if 5 in iplots:
844 p = Plot(['time'], ['northing', 'easting', '-depth'], ['depth'])
846 n = 100
848 t = num.arange(n)
849 xyz = num.random.normal(size=(n, 4))
850 xyz[:, 0] *= 0.5
852 smap = make_smap('summer')
854 p(0, 0).scatter(
855 t, xyz[:, 0], c=xyz[:, 2], cmap=smap.cmap, norm=smap.norm)
856 p(0, 1).scatter(
857 t, xyz[:, 1], c=xyz[:, 2], cmap=smap.cmap, norm=smap.norm)
858 p(0, 2).scatter(
859 t, xyz[:, 2], c=xyz[:, 2], cmap=smap.cmap, norm=smap.norm)
861 p.set_lim('depth', -1., 1.)
863 p.set_color_dim(smap, 'depth')
865 p.set_aspect('northing', 'easting', 1.0)
866 p.set_aspect('northing', 'depth', 1.0)
868 p.set_label('time', 'Time [s]')
869 p.set_label('depth', 'Depth [km]')
870 p.set_label('easting', 'Easting [km]')
871 p.set_label('northing', 'Northing [km]')
873 p.colorbar('depth')
875 p.show()
877 if 6 in iplots:
878 km = 1000.
879 p = Plot(
880 ['easting'], ['northing']*3, ['displacement'])
882 nn, ne = 50, 40
883 n = num.linspace(-5*km, 5*km, nn)
884 e = num.linspace(-10*km, 10*km, ne)
886 displacement = num.zeros((nn, ne, 3))
887 g = num.exp(
888 -(n[:, num.newaxis]**2 + e[num.newaxis, :]**2) / (5*km)**2)
890 displacement[:, :, 0] = g
891 displacement[:, :, 1] = g * 0.5
892 displacement[:, :, 2] = -g * 0.2
894 for icomp in (0, 1, 2):
895 c = p(0, icomp).pcolormesh(
896 e/km, n/km, displacement[:, :, icomp], shading='gouraud')
897 p.set_color_dim(c, 'displacement')
899 p.colorbar('displacement')
900 p.set_lim('displacement', -1.0, 1.0)
901 p.set_label('easting', 'Easting [km]')
902 p.set_label('northing', 'Northing [km]')
903 p.set_aspect('northing', 'easting')
905 p.set_lim('northing', -5.0, 5.0)
906 p.set_lim('easting', -3.0, 3.0)
907 p.show()