1import numpy as np
2from matplotlib.tri._triangulation import Triangulation
3import matplotlib.cbook as cbook
4import matplotlib.lines as mlines
5
6
7def triplot(ax, *args, **kwargs):
8 """
9 Draw an unstructured triangular grid as lines and/or markers.
10
11 Call signatures::
12
13 triplot(triangulation, ...)
14 triplot(x, y, [triangles], *, [mask=mask], ...)
15
16 The triangular grid can be specified either by passing a `.Triangulation`
17 object as the first parameter, or by passing the points *x*, *y* and
18 optionally the *triangles* and a *mask*. If neither of *triangulation* or
19 *triangles* are given, the triangulation is calculated on the fly.
20
21 Parameters
22 ----------
23 triangulation : `.Triangulation`
24 An already created triangular grid.
25 x, y, triangles, mask
26 Parameters defining the triangular grid. See `.Triangulation`.
27 This is mutually exclusive with specifying *triangulation*.
28 other_parameters
29 All other args and kwargs are forwarded to `~.Axes.plot`.
30
31 Returns
32 -------
33 lines : `~matplotlib.lines.Line2D`
34 The drawn triangles edges.
35 markers : `~matplotlib.lines.Line2D`
36 The drawn marker nodes.
37 """
38 import matplotlib.axes
39
40 tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs)
41 x, y, edges = (tri.x, tri.y, tri.edges)
42
43 # Decode plot format string, e.g., 'ro-'
44 fmt = args[0] if args else ""
45 linestyle, marker, color = matplotlib.axes._base._process_plot_format(fmt)
46
47 # Insert plot format string into a copy of kwargs (kwargs values prevail).
48 kw = cbook.normalize_kwargs(kwargs, mlines.Line2D)
49 for key, val in zip(('linestyle', 'marker', 'color'),
50 (linestyle, marker, color)):
51 if val is not None:
52 kw.setdefault(key, val)
53
54 # Draw lines without markers.
55 # Note 1: If we drew markers here, most markers would be drawn more than
56 # once as they belong to several edges.
57 # Note 2: We insert nan values in the flattened edges arrays rather than
58 # plotting directly (triang.x[edges].T, triang.y[edges].T)
59 # as it considerably speeds-up code execution.
60 linestyle = kw['linestyle']
61 kw_lines = {
62 **kw,
63 'marker': 'None', # No marker to draw.
64 'zorder': kw.get('zorder', 1), # Path default zorder is used.
65 }
66 if linestyle not in [None, 'None', '', ' ']:
67 tri_lines_x = np.insert(x[edges], 2, np.nan, axis=1)
68 tri_lines_y = np.insert(y[edges], 2, np.nan, axis=1)
69 tri_lines = ax.plot(tri_lines_x.ravel(), tri_lines_y.ravel(),
70 **kw_lines)
71 else:
72 tri_lines = ax.plot([], [], **kw_lines)
73
74 # Draw markers separately.
75 marker = kw['marker']
76 kw_markers = {
77 **kw,
78 'linestyle': 'None', # No line to draw.
79 }
80 kw_markers.pop('label', None)
81 if marker not in [None, 'None', '', ' ']:
82 tri_markers = ax.plot(x, y, **kw_markers)
83 else:
84 tri_markers = ax.plot([], [], **kw_markers)
85
86 return tri_lines + tri_markers