pygimli.mplviewer

Matplotlib drawing functions used by pygimli.viewer.

Overview

Functions

addCoverageAlpha(patches, coverage[, …]) Add alpha values to the colors of a polygon collection.
adjustWorldAxes(ax) Set some common default properties for an axe.
autolevel(z, nLevs[, logScale, zmin, zmax]) Create nLevs bins for the data array z based on matplotlib ticker.
cacheFileName(fullname, vendor) Createfilename and path to cache download data.
cmapFromName([cmapname, ncols, bad]) Get a colormap either from name or from keyworld list.
createAnimation(fig, animate, nFrames, dpi, out) Create animation for the content of a given matplotlib figure.
createColorBar(gci[, orientation, size, pad]) Create a Colorbar.
createColorBarOnly([cMin, cMax, logScale, …]) Create figure with a colorbar.
createColorbar(*args, **kwargs)
createMeshPatches(ax, mesh[, verbose, …]) Utility function to create 2d mesh patches within a given ax.
createTriangles(mesh[, data]) Generate triangle objects for later drawing.
createTwinX(ax) Utility function to create (or return existing) twin x axes for ax.
createTwinY(ax) Utility function to create (or return existing) twin x axes for ax.
create_legend(ax, cmap, ids, classes) Create a list of patch objects that can be used for borehole legends.
deg2MapTile(lon_deg, lat_deg, zoom) TODO Documentme.
draw1DColumn(ax, x, val, thk[, width, …]) Draw a 1D column (e.g., from a 1D inversion) on a given ax.
draw1dmodel(x[, thk, xlab, zlab, islog, z0]) DEPRECATED.
draw1dmodelErr(x, xL[, xU, thk, xcol, ycol]) TODO.
draw1dmodelLU(x, xL, xU[, thk]) Draw 1d model with lower and upper bounds.
draw1dmodel__Redundant(x[, thk, xlab, zlab, …]) Draw 1d block model defined by value and thickness vectors.
drawField(ax, mesh[, data]) Draw a mesh-related (node or cell based) field onto a given MPL axis.
drawMPLTri(ax, mesh[, data, cMin, cMax, …]) Draw mesh based scalar field using matplotlib triplot.
drawMesh(ax, mesh, **kwargs) Draw a 2d mesh into a given ax.
drawMeshBoundaries(ax, mesh[, hideMesh, …]) Draw mesh on ax with boundary conditions colorized.
drawModel(ax, mesh[, data, logScale, cMin, …]) Draw a 2d mesh and color the cell by the data.
drawModel1D(ax[, thickness, values, model, …]) Draw 1d block model into axis ax.
drawPLC(ax, mesh[, fillRegion, …]) Draw 2D PLC into given axes.
drawParameterConstraints(ax, mesh, cMat[, …]) Draw inter parameter constraints between cells.
drawSelectedMeshBoundaries(ax, boundaries[, …]) Draw mesh boundaries into a given axes.
drawSelectedMeshBoundariesShadow(ax, boundaries) Draw mesh boundaries as shadows into a given axes.
drawSensorAsMarker(ax, data) Draw Sensor marker, these marker are pickable.
drawSensors(ax, sensors[, diam, coords, verbose]) Draw sensor positions as black dots with a given diameter.
drawStreamLines(ax, mesh, u[, nx, ny]) Draw streamlines for the gradients of field values u on a mesh.
drawStreams(ax, mesh, data[, startStream]) Draw streamlines based on an unstructured mesh.
findAndMaskBestClim(dataIn[, cMin, cMax, …]) TODO Documentme.
findColorBar(ax) Find the colorbar of an axes.
generateMatrix(xvec, yvec, vals, **kwargs) Generate a data matrix from x/y and value vectors.
getMapTile(xtile, ytile, zoom[, vendor, verbose]) Get a map tile from public mapping server.
hold([val]) TODO WRITEME.
insertUnitAtNextLastTick(ax, unit[, xlabel, …]) Replace the last-but-one tick label by unit symbol.
mapTile2deg(xtile, ytile, zoom) Calculate the NW-corner of the square.
patchMatrix(mat[, xmap, ymap, ax, cMin, …]) Plot previously generated (generateVecMatrix) matrix.
patchValMap(vals[, xvec, yvec, ax, cMin, …]) Plot previously generated (generateVecMatrix) y map (category).
plotDataContainerAsMatrix(data[, x, y, v]) Plot data container as matrix.
plotLines(ax, line_filename[, linewidth, step]) Read lines from file and plot over model.
plotMatrix(mat[, xmap, ymap, ax, cMin, …]) Plot previously generated (generateVecMatrix) matrix.
plotVecMatrix(xvec, yvec, vals[, full]) DEPRECATED for nameing
prettyFloat(v) Return pretty string for a given value suitable for graphical output.
renameDepthTicks(ax) Switch signs of depth ticks to be positive
saveAnimation(mesh, data, out[, vData, plc, …]) Create and save an animation for a given mesh with a set of field data.
saveAxes(ax, filename[, adjust]) Save axes as pdf.
saveFigure(fig, filename[, pdfTrim]) Save figure as pdf.
setCbarLevels(cbar[, cMin, cMax, nLevs]) TODO Documentme.
setMappableData(mappable, dataIn[, cMin, …]) Change the data values for a given mappable.
setMappableValues(mappable, dataIn) Change the data values for a given mapable.
setOutputStyle([dim, paperMargin, xScale, …]) Set preferred output style.
setPlotStuff([fontsize, dpi]) TODO merge with setOutputStyle.
show1dmodel(x[, thk, xlab, zlab, islog, z0]) Show 1d block model defined by value and thickness vectors.
showStitchedModels(models[, ax, x, cMin, …]) Show several 1d block models as (stitched) section.
showStitchedModelsOld(models[, x, cmin, …]) Show several 1d block models as (stitched) section.
showStitchedModels_Redundant(mods[, ax, …]) Show several 1d block models as (stitched) section.
showVecMatrix(xvec, yvec, vals[, full]) Plot three vectors as matrix.
showfdemsounding(freq, inphase, quadrat[, …]) Show FDEM sounding as real(inphase) and imaginary (quadrature) fields.
showmymatrix(mat, x, y[, dx, dy, xlab, …]) What is this good for?.
underlayBKGMap(ax[, mode, utmzone, epsg, …]) Underlay digital orthophoto or topographic (mode=’DTK’) map under axes.
underlayMap(ax, proj[, vendor, zoom, …]) Get a map from public mapping server and underlay it on the given ax.
updateAxes(ax[, a, force]) For internal use.
updateColorBar(cbar[, gci, cMin, cMax, …]) Update colorbar values.
wait(**kwargs) TODO WRITEME.

Classes

BoreHole(fname) Class for handling (structural) borehole data for inclusion in plots.
BoreHoles(fnames) Class to load and handle several boreholes belonging to one profile.
CellBrowser(mesh[, data, ax]) Interactive cell browser on current or specified ax for a given mesh.

Functions

addCoverageAlpha

pygimli.mplviewer.addCoverageAlpha(patches, coverage, dropThreshold=0.4)[source]

Add alpha values to the colors of a polygon collection.

Parameters:
patches : 2D mpl mappable
coverage : array

coverage values. Maximum coverage mean no opaqueness.

dropThreshold : float

relative minimum coverage

adjustWorldAxes

pygimli.mplviewer.adjustWorldAxes(ax)[source]

Set some common default properties for an axe.

autolevel

pygimli.mplviewer.autolevel(z, nLevs, logScale=None, zmin=None, zmax=None)[source]

Create nLevs bins for the data array z based on matplotlib ticker.

Examples

>>> import numpy as np
>>> from pygimli.mplviewer import autolevel
>>> x = np.linspace(1, 10, 100)
>>> autolevel(x, 3)
array([  1.,   4.,   7.,  10.])
>>> autolevel(x, 3, logScale=True)
array([   0.1,    1. ,   10. ,  100. ])

cacheFileName

pygimli.mplviewer.cacheFileName(fullname, vendor)[source]

Createfilename and path to cache download data.

cmapFromName

pygimli.mplviewer.cmapFromName(cmapname='jet', ncols=256, bad=None, **kwargs)[source]

Get a colormap either from name or from keyworld list.

See http://matplotlib.org/examples/color/colormaps_reference.html

Parameters:
cmapname : str

Name for the colormap.

ncols : int

Amount of colors.

bad : [r,g,b,a]

Default color for bad values [nan, inf] [white]

**** kwargs :**
cMap : str

Name for the colormap

cmap : str

colormap name (old)

Returns
——-
cMap:

matplotlib Colormap

createAnimation

pygimli.mplviewer.createAnimation(fig, animate, nFrames, dpi, out)[source]

Create animation for the content of a given matplotlib figure.

Until I know a better place.

createColorBar

pygimli.mplviewer.createColorBar(gci, orientation='horizontal', size=0.2, pad=None, **kwargs)[source]

Create a Colorbar.

Shortcut to create a matplotlib colorbar within the ax for a given patchset.

Parameters:
gci : matplotlib graphical instance
orientation : string
size : float
pad : float
**kwargs :

Forwarded to updateColorBar

createColorBarOnly

pygimli.mplviewer.createColorBarOnly(cMin=1, cMax=100, logScale=False, cMap=None, nLevs=5, label=None, orientation='horizontal', savefig=None, **kwargs)[source]

Create figure with a colorbar.

Create figure with a colorbar.

Parameters:
**kwargs:

Forwarded to mpl.colorbar.ColorbarBase.

Returns:
fig:

The created figure.

Examples

>>> # import pygimli as pg
>>> # from pygimli.mplviewer import createColorBarOnly
>>> # createColorBarOnly(cMin=0.2, cMax=5, logScale=False,
>>> #                   cMap='b2r',
>>> #                   nLevs=7,
>>> #                   label=r'Ratio',
>>> #                   orientation='horizontal')
>>> # pg.wait()

createColorbar

pygimli.mplviewer.createColorbar(*args, **kwargs)[source]

createMeshPatches

pygimli.mplviewer.createMeshPatches(ax, mesh, verbose=True, rasterized=False)[source]

Utility function to create 2d mesh patches within a given ax.

createTriangles

pygimli.mplviewer.createTriangles(mesh, data=None)[source]

Generate triangle objects for later drawing.

Parameters:
mesh : GIMLI::Mesh

pyGimli mesh to plot

data : iterable [None]

cell-based values to plot

Returns:
x : numpy array

x position of nodes

y : numpy array

x position of nodes

triangles : numpy array Cx3

cell indices for each triangle

z : numpy array

data for given indices

dataIdx : list of int

list of indices into array to plot

createTwinX

pygimli.mplviewer.createTwinX(ax)[source]

Utility function to create (or return existing) twin x axes for ax.

createTwinY

pygimli.mplviewer.createTwinY(ax)[source]

Utility function to create (or return existing) twin x axes for ax.

create_legend

pygimli.mplviewer.create_legend(ax, cmap, ids, classes)[source]

Create a list of patch objects that can be used for borehole legends.

deg2MapTile

pygimli.mplviewer.deg2MapTile(lon_deg, lat_deg, zoom)[source]

TODO Documentme.

draw1DColumn

pygimli.mplviewer.draw1DColumn(ax, x, val, thk, width=30, ztopo=0, cmin=1, cmax=1000, cmap=None, name=None, textoffset=0.0)[source]

Draw a 1D column (e.g., from a 1D inversion) on a given ax.

Examples

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from pygimli.mplviewer import draw1DColumn
>>> thk = [1, 2, 3, 4]
>>> val = thk
>>> fig, ax = plt.subplots()
>>> draw1DColumn(ax, 0.5, val, thk, width=0.1, cmin=1, cmax=4, name="VES")
<matplotlib.collections.PatchCollection object at ...>
>>> ax.set_ylim(-np.sum(thk), 0)
(-10, 0)

(png, pdf)

../../_images/pygimli-mplviewer-1.png

draw1dmodel

pygimli.mplviewer.draw1dmodel(x, thk=None, xlab=None, zlab='z in m', islog=True, z0=0)[source]

DEPRECATED.

draw1dmodelErr

pygimli.mplviewer.draw1dmodelErr(x, xL, xU=None, thk=None, xcol='g', ycol='r', **kwargs)[source]

TODO.

draw1dmodelLU

pygimli.mplviewer.draw1dmodelLU(x, xL, xU, thk=None, **kwargs)[source]

Draw 1d model with lower and upper bounds.

draw1dmodel__Redundant

pygimli.mplviewer.draw1dmodel__Redundant(x, thk=None, xlab=None, zlab='z in m', islog=True, fs=14, z0=0, **kwargs)[source]

Draw 1d block model defined by value and thickness vectors.

drawField

pygimli.mplviewer.drawField(ax, mesh, data=None, **kwargs)[source]

Draw a mesh-related (node or cell based) field onto a given MPL axis.

Only for triangle/quadrangle meshes currently
Parameters:
ax : MPL axes
mesh : GIMLI::Mesh
data: iterable

Scalar field values. Can be of length mesh.cellCount() or mesh.nodeCount().

**kwargs:
  • shading: interpolation algorithm [flat]
  • fillContour: [True]
  • withContourLines: [True]
Returns
——-
gci : image object

The current image object useful for post color scaling

Examples

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> import pygimli as pg
>>> from pygimli.mplviewer import drawField
>>> n = np.linspace(0, -2, 11)
>>> mesh = pg.createGrid(x=n, y=n)
>>> nx = pg.x(mesh.positions())
>>> ny = pg.y(mesh.positions())
>>> data = np.cos(1.5 * nx) * np.sin(1.5 * ny)
>>> fig, ax = plt.subplots()
>>> drawField(ax, mesh, data)
<matplotlib.tri.tricontour.TriContourSet ...>

(png, pdf)

../../_images/pygimli-mplviewer-2.png

drawMPLTri

pygimli.mplviewer.drawMPLTri(ax, mesh, data=None, cMin=None, cMax=None, logScale=True, **kwargs)[source]

Draw mesh based scalar field using matplotlib triplot.

Draw scalar field into MPL axes using matplotlib triplot.

TODO
  • Examples
  • Doc: Interpolation variants
Parameters:
data: iterable

Scalar field values. Can be of length mesh.cellCount() or mesh.nodeCount().

**kwargs:
  • shading: interpolation algorithm [flat]
  • fillContour: [True]
  • withContourLines: [True]
Returns
——-
gci : image object

The current image object useful for post color scaling

Examples
——–
>>>

drawMesh

pygimli.mplviewer.drawMesh(ax, mesh, **kwargs)[source]

Draw a 2d mesh into a given ax.

Set the limits of the ax tor the mesh extent.

Parameters:
mesh : GIMLI::Mesh

The plotted mesh to browse through.

ax : mpl axe instance, optional

Axis instance where the mesh is plotted (default is current axis).

fitView: bool [True]

Adjust ax limits to mesh bounding box.

Examples

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> import pygimli as pg
>>> from pygimli.mplviewer import drawMesh
>>> n = np.linspace(1, 2, 10)
>>> mesh = pg.createGrid(x=n, y=n)
>>> fig, ax = plt.subplots()
>>> drawMesh(ax, mesh)
>>> plt.show()

(png, pdf)

../../_images/pygimli-mplviewer-3.png

Examples using pygimli.mplviewer.drawMesh

drawMeshBoundaries

pygimli.mplviewer.drawMeshBoundaries(ax, mesh, hideMesh=False, useColorMap=False, **kwargs)[source]

Draw mesh on ax with boundary conditions colorized.

Parameters:
hideMesh: bool [False]

Show only the boundary of the mesh and omit inner edges that separate the cells.

useColorMap: bool[False]

Apply the default colormap to boundaries with marker values > 0

**kwargs:
  • fitView : bool [True]
  • linewidth : float [0.3]
    linewidth for edges with marker == 0 if hideMesh is False.

Examples

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> import pygimli as pg
>>> from pygimli.mplviewer import drawMeshBoundaries
>>> n = np.linspace(0, -2, 11)
>>> mesh = pg.createGrid(x=n, y=n)
>>> for bound in mesh.boundaries():
...     if not bound.rightCell():
...         bound.setMarker(pg.MARKER_BOUND_MIXED)
...     if bound.center().y() == 0:
...         bound.setMarker(pg.MARKER_BOUND_HOMOGEN_NEUMANN)
>>> fig, ax = plt.subplots()
>>> drawMeshBoundaries(ax, mesh)

(png, pdf)

../../_images/pygimli-mplviewer-4.png

drawModel

pygimli.mplviewer.drawModel(ax, mesh, data=None, logScale=True, cMin=None, cMax=None, xlabel=None, ylabel=None, verbose=False, tri=False, rasterized=False, **kwargs)[source]

Draw a 2d mesh and color the cell by the data.

Parameters:
mesh : GIMLI::Mesh

The plotted mesh to browse through.

ax : mpl axis instance, optional

Axis instance where the mesh is plotted (default is current axis).

data : array, optional

Data to draw. Should either equal numbers of cells or nodes of the corresponding mesh.

tri : boolean, optional

use MPL tripcolor (experimental)

rasterized : boolean, optional

Rasterize mesh patches to reduce file size and avoid zooming artifacts in some PDF viewers.

**kwargs : Additional keyword arguments

Will be forwarded to the draw functions and matplotlib methods, respectively.

Returns:
gci : matplotlib graphics object

Examples

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> import pygimli as pg
>>> from pygimli.mplviewer import drawModel
>>> n = np.linspace(0, -2, 11)
>>> mesh = pg.createGrid(x=n, y=n)
>>> mx = pg.x(mesh.cellCenter())
>>> my = pg.y(mesh.cellCenter())
>>> data = np.cos(1.5 * mx) * np.sin(1.5 * my)
>>> fig, ax = plt.subplots()
>>> drawModel(ax, mesh, data)
<matplotlib.collections.PolyCollection object at ...>

(png, pdf)

../../_images/pygimli-mplviewer-5.png

Examples using pygimli.mplviewer.drawModel

drawModel1D

pygimli.mplviewer.drawModel1D(ax, thickness=None, values=None, model=None, depths=None, plot='plot', xlabel='Resistivity $[\\Omega$m$]$', zlabel='Depth [m]', z0=0, **kwargs)[source]

Draw 1d block model into axis ax.

Draw 1d block model into axis ax defined by values and thickness vectors using plot function. For log y cases, z0 should be set > 0 so that the default becomes 1.

Parameters:
ax : mpl axes

Matplotlib Axes object to plot into.

values : iterable [float]

[N] Values for each layer plus lower background.

thickness : iterable [float]

[N-1] thickness for each layer. Either thickness or depths must be set.

depths : iterable [float]

[N-1] Values for layer depths (positive z-coordinates). Either thickness or depths must be set.

model : iterable [float]

Shortcut to use default model definition. thks = model[0:nLay] values = model[nLay:]

plot : string

Matplotlib plotting function. ‘plot’, ‘semilogx’, ‘semilogy’, ‘loglog’

xlabel : str

Label for x axis.

ylabel : str

Label for y axis.

z0 : float

Starting depth [m]

**kwargs : dict()

Forwarded to the plot routine

Examples

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> import pygimli as pg
>>> # plt.style.use('ggplot')
>>> thk = [1, 4, 4]
>>> res = np.array([10., 5, 15, 50])
>>> fig, ax = plt.subplots()
>>> pg.mplviewer.drawModel1D(ax, values=res*5, depths=np.cumsum(thk),
...                          plot='semilogx', color='blue')
>>> pg.mplviewer.drawModel1D(ax, values=res, thickness=thk, z0=1,
...                          plot='semilogx', color='red')
>>> pg.wait()

(png, pdf)

../../_images/pygimli-mplviewer-6.png

Examples using pygimli.mplviewer.drawModel1D

drawPLC

pygimli.mplviewer.drawPLC(ax, mesh, fillRegion=True, regionMarker=True, boundaryMarker=False, showNodes=False, **kwargs)[source]

Draw 2D PLC into given axes.

Parameters:
fillRegion: bool [True]

Fill the regions with default colormap.

regionMarker: bool [True]

show region marker

boundaryMarker: bool [False]

show boundary marker

showNodes: bool [False]

draw all nodes

**kwargs

Examples

>>> import matplotlib.pyplot as plt
>>> import pygimli as pg
>>> import pygimli.meshtools as mt
>>> # Create geometry definition for the modeling domain
>>> world = mt.createWorld(start=[-20, 0], end=[20, -16],
...                        layers=[-2, -8], worldMarker=False)
>>> # Create a heterogeneous block
>>> block = mt.createRectangle(start=[-6, -3.5], end=[6, -6.0],
...                            marker=10,  boundaryMarker=10, area=0.1)
>>> fig, ax = plt.subplots()
>>> geom = mt.mergePLC([world, block])
>>> pg.mplviewer.drawPLC(ax, geom)

(png, pdf)

../../_images/pygimli-mplviewer-7.png

drawParameterConstraints

pygimli.mplviewer.drawParameterConstraints(ax, mesh, cMat, cWeight=None)[source]

Draw inter parameter constraints between cells.

Parameters:
ax : MPL axes
mesh :

drawSelectedMeshBoundaries

pygimli.mplviewer.drawSelectedMeshBoundaries(ax, boundaries, color=None, linewidth=1.0)[source]

Draw mesh boundaries into a given axes.

Parameters:
ax : matplotlib axes

axes to plot into

boundaries : GIMLI::Mesh boundary vector

collection of boundaries to plot

color : matplotlib color |str [None]

matching color or string, else colors are according to markers

linewidth : float [1.0]

line width

Returns:
lco : matplotlib line collection object

drawSelectedMeshBoundariesShadow

pygimli.mplviewer.drawSelectedMeshBoundariesShadow(ax, boundaries, first='x', second='y', color=(0.3, 0.3, 0.3, 1.0))[source]

Draw mesh boundaries as shadows into a given axes.

Parameters:
ax : matplotlib axes

axes to plot into

boundaries : GIMLI::Mesh boundary vector

collection of boundaries to plot

first / second : str [‘x’ / ‘y’]

attribute names to retrieve from nodes

color : matplotlib color |str [None]

matching color or string, else colors are according to markers

linewidth : float [1.0]

line width

Returns:
lco : matplotlib line collection object

drawSensorAsMarker

pygimli.mplviewer.drawSensorAsMarker(ax, data)[source]

Draw Sensor marker, these marker are pickable.

drawSensors

pygimli.mplviewer.drawSensors(ax, sensors, diam=None, coords=None, verbose=False, **kwargs)[source]

Draw sensor positions as black dots with a given diameter.

Parameters:
sensors : vector or list of RVector3

list of positions to plot

diam : float [None]

diameter of circles (None leads to point distance by 8)

coords: (int, int) [0, 1]

Coordinates to take (usually x and y)

Examples

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> import pygimli as pg
>>> from pygimli.mplviewer import drawSensors
>>> sensors = np.random.rand(5, 2)
>>> fig, ax = pg.plt.subplots()
>>> drawSensors(ax, sensors, diam=0.02, coords=[0, 1])
>>> ax.set_aspect('equal')
>>> pg.wait()

(png, pdf)

../../_images/pygimli-mplviewer-8.png

drawStreamLines

pygimli.mplviewer.drawStreamLines(ax, mesh, u, nx=25, ny=25, **kwargs)[source]

Draw streamlines for the gradients of field values u on a mesh.

The matplotlib routine streamplot needs equidistant spacings so we interpolate first on a grid defined by nx and ny nodes. Additionally arguments are piped to streamplot.

This works only for rectangular regions. You should use pg.mplviewer.drawStreams, which is more comfortable and more flexible.

Examples using pygimli.mplviewer.drawStreamLines

drawStreams

pygimli.mplviewer.drawStreams(ax, mesh, data, startStream=3, **kwargs)[source]

Draw streamlines based on an unstructured mesh.

Every cell contains only one streamline and every new stream line starts in the center of a cell. You can alternatively provide a second mesh with coarser mesh to draw streams for.

Parameters:
ax : matplotlib.ax

ax to draw into

mesh : GIMLI::Mesh

2d Mesh to draw the streamline

data : iterable float | [float, float] | pg.R3Vector

If data is an array (per cell or node) gradients are calculated otherwise the data will be interpreted as vector field.

startStream : int

variate the start stream drawing, try values from 1 to 3 what every you like more.

**kwargs: forward to drawStreamLine_
  • coarseMesh

    Instead of draw a stream for every cell in mesh, draw a streamline segment for each cell in coarseMesh.

  • quiver: bool

    Draw arrows instead of streamlines.

Examples

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> import pygimli as pg
>>> from pygimli.mplviewer import drawStreams
>>> n = np.linspace(0, 1, 10)
>>> mesh = pg.createGrid(x=n, y=n)
>>> nx = pg.x(mesh.positions())
>>> ny = pg.y(mesh.positions())
>>> data = np.cos(1.5 * nx) * np.sin(1.5 * ny)
>>> fig, ax = plt.subplots()
>>> drawStreams(ax, mesh, data, color='red')
>>> drawStreams(ax, mesh, data, dropTol=0.9)
>>> drawStreams(ax, mesh, pg.solver.grad(mesh, data),
...             color='green', quiver=True)
>>> ax.set_aspect('equal')
>>> pg.wait()

(png, pdf)

../../_images/pygimli-mplviewer-9.png

Examples using pygimli.mplviewer.drawStreams

findAndMaskBestClim

pygimli.mplviewer.findAndMaskBestClim(dataIn, cMin=None, cMax=None, dropColLimitsPerc=5, logScale=True)[source]

TODO Documentme.

findColorBar

pygimli.mplviewer.findColorBar(ax)[source]

Find the colorbar of an axes.

Find the colorbar that is associated with given axes or return None.

generateMatrix

pygimli.mplviewer.generateMatrix(xvec, yvec, vals, **kwargs)[source]

Generate a data matrix from x/y and value vectors.

Parameters:
xvec, yvec, vals : iterables (list, np.array, pg.RVector) of same length
full: bool [False]

generate a fully symmetric matrix containing all unique xvec+yvec otherwise A is squeezed to the individual unique vectors

Returns:
A : np.ndarray(2d)

matrix containing the values sorted according to unique xvec/yvec

xmap/ymap : dict {key: num}

dictionaries for accessing matrix position (row/col number from x/y[i])

getMapTile

pygimli.mplviewer.getMapTile(xtile, ytile, zoom, vendor='OSM', verbose=False)[source]

Get a map tile from public mapping server.

Its not recommended to use the google maps tile server without the google maps api so if you use it to often your IP will be blacklisted

TODO: look here for more vendors https://github.com/Leaflet/Leaflet TODO: Try http://scitools.org.uk/cartopy/docs/v0.14/index.html TODO: Try https://github.com/jwass/mplleaflet

Parameters:
xtile : int
ytile : int
zoom : int
vendor : str

. ‘OSM’ or ‘Open Street Map’ (tile.openstreetmap.org) . ‘GM’ or ‘Google Maps’ (mt.google.com) (do not use it to much)

verbose : bool [false]

be verbose

hold

pygimli.mplviewer.hold(val=1)[source]

TODO WRITEME.

insertUnitAtNextLastTick

pygimli.mplviewer.insertUnitAtNextLastTick(ax, unit, xlabel=True, position=-2)[source]

Replace the last-but-one tick label by unit symbol.

mapTile2deg

pygimli.mplviewer.mapTile2deg(xtile, ytile, zoom)[source]

Calculate the NW-corner of the square.

Use the function with xtile+1 and/or ytile+1 to get the other corners. With xtile+0.5 ytile+0.5 it will return the center of the tile.

patchMatrix

pygimli.mplviewer.patchMatrix(mat, xmap=None, ymap=None, ax=None, cMin=None, cMax=None, logScale=None, label=None, dx=1, **kwargs)[source]

Plot previously generated (generateVecMatrix) matrix.

Parameters:
mat : numpy.array2d

matrix to show

xmap : dict {i:num}

dict (must match A.shape[0])

ymap : iterable

vector for x axis (must match A.shape[0])

ax : mpl.axis

axis to plot, if not given a new figure is created

cMin/cMax : float

minimum/maximum color values

logScale : bool

logarithmic colour scale [min(A)>0]

label : string

colorbar label

dx : float

width of the matrix elements (by default 1)

patchValMap

pygimli.mplviewer.patchValMap(vals, xvec=None, yvec=None, ax=None, cMin=None, cMax=None, logScale=None, label=None, dx=1, dy=None, **kwargs)[source]

Plot previously generated (generateVecMatrix) y map (category).

Parameters:
vals : iterable

Data values to show.

xvec : dict {i:num}

dict (must match vals.shape[0])

ymap : iterable

vector for x axis (must match vals.shape[0])

ax : mpl.axis

axis to plot, if not given a new figure is created

cMin/cMax : float

minimum/maximum color values

logScale : bool

logarithmic colour scale [min(vals)>0]

label : string

colorbar label

**** kwargs:**
  • circular : bool
    Plot in polar coordinates.

plotDataContainerAsMatrix

pygimli.mplviewer.plotDataContainerAsMatrix(data, x=None, y=None, v=None, **kwargs)[source]

Plot data container as matrix.

for each x, y and v token strings or vectors should be given

plotLines

pygimli.mplviewer.plotLines(ax, line_filename, linewidth=1.0, step=1)[source]

Read lines from file and plot over model.

plotMatrix

pygimli.mplviewer.plotMatrix(mat, xmap=None, ymap=None, ax=None, cMin=None, cMax=None, logScale=None, label=None, **kwargs)[source]

Plot previously generated (generateVecMatrix) matrix.

Parameters:
mat : numpy.array2d

matrix to show

xmap : dict {i:num}

dict (must match A.shape[0])

ymap : iterable

vector for x axis (must match A.shape[0])

ax : mpl.axis

axis to plot, if not given a new figure is created

cMin/cMax : float

minimum/maximum color values

logScale : bool

logarithmic colour scale [min(A)>0]

label : string

colorbar label

Returns:
ax : matplotlib axes object

axes object

cb : matplotlib colorbar

colorbar object

plotVecMatrix

pygimli.mplviewer.plotVecMatrix(xvec, yvec, vals, full=False, **kwargs)[source]

DEPRECATED for nameing

prettyFloat

pygimli.mplviewer.prettyFloat(v)[source]

Return pretty string for a given value suitable for graphical output.

renameDepthTicks

pygimli.mplviewer.renameDepthTicks(ax)[source]

Switch signs of depth ticks to be positive

saveAnimation

pygimli.mplviewer.saveAnimation(mesh, data, out, vData=None, plc=None, label='', cMin=None, cMax=None, logScale=False, cmap=None, **kwargs)[source]

Create and save an animation for a given mesh with a set of field data.

Until I know a better place.

saveAxes

pygimli.mplviewer.saveAxes(ax, filename, adjust=False)[source]

Save axes as pdf.

saveFigure

pygimli.mplviewer.saveFigure(fig, filename, pdfTrim=False)[source]

Save figure as pdf.

setCbarLevels

pygimli.mplviewer.setCbarLevels(cbar, cMin=None, cMax=None, nLevs=5)[source]

TODO Documentme.

setMappableData

pygimli.mplviewer.setMappableData(mappable, dataIn, cMin=None, cMax=None, logScale=False)[source]

Change the data values for a given mappable.

DEPRECATED

setMappableValues

pygimli.mplviewer.setMappableValues(mappable, dataIn)[source]

Change the data values for a given mapable.

setOutputStyle

pygimli.mplviewer.setOutputStyle(dim='w', paperMargin=5, xScale=1.0, yScale=1.0, fontsize=9, scale=1, usetex=True)[source]

Set preferred output style.

setPlotStuff

pygimli.mplviewer.setPlotStuff(fontsize=7, dpi=None)[source]

TODO merge with setOutputStyle.

Change ugly name.

show1dmodel

pygimli.mplviewer.show1dmodel(x, thk=None, xlab=None, zlab='z in m', islog=True, z0=0, **kwargs)[source]

Show 1d block model defined by value and thickness vectors.

showStitchedModels

pygimli.mplviewer.showStitchedModels(models, ax=None, x=None, cMin=None, cMax=None, logScale=True, title=None, zMin=0, zMax=0, zLog=False, cmap='jet', **kwargs)[source]

Show several 1d block models as (stitched) section.

Parameters:
model : iterable of iterable (np.ndarray or list of np.array)

1D models (consisting of thicknesses and values) to plot

ax : matplotlib axes [None - create new]

axes object to plot in

x : iterable

positions of individual models

cMin/cMax : float [None - autodetection from range]

minimum and maximum colorscale range

logScale : bool [True]

use logarithmic color scaling

zMin/zMax : float [0 - automatic]

range for z (y axis) limits

zLog : bool

use logarithmic z (y axis) instead of linear

topo : iterable

vector of elevation for shifting

Returns
——-
ax : matplotlib axes [None - create new]

axes object to plot in

showStitchedModelsOld

pygimli.mplviewer.showStitchedModelsOld(models, x=None, cmin=None, cmax=None, islog=True, title=None)[source]

Show several 1d block models as (stitched) section.

showStitchedModels_Redundant

pygimli.mplviewer.showStitchedModels_Redundant(mods, ax=None, cmin=None, cmax=None, **kwargs)[source]

Show several 1d block models as (stitched) section.

showVecMatrix

pygimli.mplviewer.showVecMatrix(xvec, yvec, vals, full=False, **kwargs)[source]

Plot three vectors as matrix.

Parameters:
xvec, yvec : iterable (e.g. list, np.array, pg.RVector) of identical length

vectors defining the indices into the matrix

vals : iterable of same length as xvec/yvec

vector containing the values to show

full: bool [False]

use a fully symmetric matrix containing all unique xvec+yvec otherwise A is squeezed to the individual unique xvec/yvec values

**kwargs: forwarded to plotMatrix
  • ax : mpl.axis Axis to plot, if not given a new figure is created
  • cMin/cMax : float
    Minimum/maximum color values
  • logScale : bool
    Lgarithmic colour scale [min(A)>0]
  • label : string
    Colorbar label
Returns:
ax : matplotlib axes object

axes object

cb : matplotlib colorbar

colorbar object

showfdemsounding

pygimli.mplviewer.showfdemsounding(freq, inphase, quadrat, response=None, npl=2)[source]

Show FDEM sounding as real(inphase) and imaginary (quadrature) fields.

Show FDEM sounding as real(inphase) and imaginary (quadrature) fields
normalized by the (purely real) free air solution.

showmymatrix

pygimli.mplviewer.showmymatrix(mat, x, y, dx=2, dy=1, xlab=None, ylab=None, cbar=None)[source]

What is this good for?.

underlayBKGMap

pygimli.mplviewer.underlayBKGMap(ax, mode='DOP', utmzone=32, epsg=0, imsize=2500, uuid='', usetls=False)[source]

Underlay digital orthophoto or topographic (mode=’DTK’) map under axes.

First accessed, the image is obtained from BKG, saved and later loaded.

Parameters:
mode : str

‘DOP’ (digital orthophoto 40cm) or ‘DTK’ (digital topo map 1:25000)

imsize : int

image width in pixels (height will be automatically determined

underlayMap

pygimli.mplviewer.underlayMap(ax, proj, vendor='OSM', zoom=-1, pixelLimit=None, verbose=False, fitMap=False)[source]

Get a map from public mapping server and underlay it on the given ax.

Parameters:
ax : matplotlib.ax
proj : pyproy

Proj Projection

vendor : str

. ‘OSM’ or ‘Open Street Map’ (tile.openstreetmap.org) . ‘GM’ or ‘Google Maps’ (mt.google.com)

zoom : int [-1]

Zoom level. If zoom is set to -1, the pixel size of the resulting image is lower than pixelLimit.

pixelLimit : [int,int]
verbose : bool [false]

be verbose

fitMap : bool

The ax is resized to fit the whole map.

updateAxes

pygimli.mplviewer.updateAxes(ax, a=None, force=False)[source]

For internal use.

updateColorBar

pygimli.mplviewer.updateColorBar(cbar, gci=None, cMin=None, cMax=None, cMap=None, logScale=None, nLevs=5, label=None)[source]

Update colorbar values.

Update limits and label of a given colorbar.

Parameters:
cbar: matplotlib colorbar
gci : matplotlib graphical instance
cMin: float
cMax: float
cLog: bool
cMap: matplotlib colormap
nLevs: int
label: str

wait

pygimli.mplviewer.wait(**kwargs)[source]

TODO WRITEME.

Classes

BoreHole

class pygimli.mplviewer.BoreHole(fname)[source]

Class for handling (structural) borehole data for inclusion in plots.

Each row in the data file must contain a start depth [m], end depth and a classification. The values should be separated by whitespace. The first line should contain the inline position (x and z), text ID and an offset for the text (for plotting).

The format is very simple, and a sample file could look like this:

16.0 0.0 BOREHOLEID_TEXTOFFSET n 0.0 1.6 clti n 1.6 10.0 shale

Methods

add_legend(ax, cmap, **legend_kwargs) Add a legend to the plot.
plot(ax[, plot_thickness, cmin, cmax, cm, …]) Plots the data on the specified axis.
__init__(fname)[source]

Initialize self. See help(type(self)) for accurate signature.

add_legend(ax, cmap, **legend_kwargs)[source]

Add a legend to the plot.

plot(ax, plot_thickness=1.0, cmin=None, cmax=None, cm=None, do_legend=True, **legend_kwargs)[source]

Plots the data on the specified axis.

BoreHoles

class pygimli.mplviewer.BoreHoles(fnames)[source]

Class to load and handle several boreholes belonging to one profile.

It makes the color coding consistent across boreholes.

Methods

add_legend(ax, cmap, **legend_kwargs) Add a legend to the plot.
plot(ax[, plot_thickness, do_legend]) Plot the boreholes on the specified axis.
__init__(fnames)[source]

Load a list of bore hole from filenames.

add_legend(ax, cmap, **legend_kwargs)[source]

Add a legend to the plot.

plot(ax, plot_thickness=1.0, do_legend=True, **legend_kwargs)[source]

Plot the boreholes on the specified axis.

CellBrowser

class pygimli.mplviewer.CellBrowser(mesh, data=None, ax=None)[source]

Interactive cell browser on current or specified ax for a given mesh.

Cell information can be displayed by mouse picking. Arrow keys up and down can be used to scroll through the cells, while ESC closes the cell information window.

Parameters:
mesh : 2D pygimli.Mesh instance

The plotted mesh to browse through.

data : iterable

Cell data.

ax : mpl axis instance, optional

Axis instance where the mesh is plotted (default is current axis).

Examples

>>> import matplotlib.pyplot as plt
>>> import pygimli as pg
>>> from pygimli.mplviewer import drawModel
>>> from pygimli.mplviewer import CellBrowser
>>>
>>> mesh = pg.createGrid(range(5), range(5))
>>> fig, ax = plt.subplots()
>>> plc = drawModel(ax, mesh, mesh.cellMarkers())
>>> browser = CellBrowser(mesh)
>>> browser.connect()

(png, pdf)

../../_images/pygimli-mplviewer-10.png

Methods

connect() Connect to matplotlib figure canvas.
disconnect() Disconnect from matplotlib figure canvas.
hide() Hide info window.
highlightCell(cell) Highlight selected cell.
onPick(event) Call self.update() on mouse pick event.
onPress(event) Call self.update() if up, down, or escape keys are pressed.
removeHighlightCell() Remove cell highlights.
setData([data]) Set data, if not set look for the artist array data.
update() Update the information window.
initText  
setMesh  
__init__(mesh, data=None, ax=None)[source]

Construct CellBrowser on a specific mesh.

connect()[source]

Connect to matplotlib figure canvas.

disconnect()[source]

Disconnect from matplotlib figure canvas.

hide()[source]

Hide info window.

highlightCell(cell)[source]

Highlight selected cell.

initText()[source]
onPick(event)[source]

Call self.update() on mouse pick event.

onPress(event)[source]

Call self.update() if up, down, or escape keys are pressed.

removeHighlightCell()[source]

Remove cell highlights.

setData(data=None)[source]

Set data, if not set look for the artist array data.

setMesh(mesh)[source]
update()[source]

Update the information window. Hide the information window for self.cellID == -1



2018 - GIMLi Development Team
Created using Bootstrap, Sphinx and pyGIMLi 1.0.9+87.g68804698 on Dec 16, 2018.