-
Notifications
You must be signed in to change notification settings - Fork 82
/
matplotlib.py
389 lines (325 loc) · 11.7 KB
/
matplotlib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# type: ignore
"""Drawing meshes and solutions using matplotlib."""
from functools import singledispatch
import numpy as np
from numpy import ndarray
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
from matplotlib.collections import PolyCollection
from ..assembly import CellBasis
from ..mesh import Mesh2D, MeshLine1, MeshQuad1, MeshTri1, Mesh3D
@singledispatch
def draw(m, **kwargs) -> Axes:
"""Visualize meshes."""
raise NotImplementedError("Type {} not supported.".format(type(m)))
@draw.register(CellBasis)
def draw_basis(ib: CellBasis, **kwargs) -> Axes:
if "nrefs" in kwargs:
nrefs = kwargs["nrefs"]
elif "Nrefs" in kwargs:
nrefs = kwargs["Nrefs"]
else:
nrefs = 1
m, _ = ib.refinterp(ib.mesh.p[0], nrefs=nrefs)
return draw(m, boundaries_only=True, **kwargs)
@draw.register(Mesh3D)
def draw_mesh3d(m: Mesh3D, **kwargs) -> Axes:
"""Visualize a three-dimensional mesh by drawing the edges."""
if 'ax' not in kwargs:
ax = plt.figure().add_subplot(1, 1, 1, projection='3d')
else:
ax = kwargs['ax']
for ix in m.boundary_edges():
ax.plot3D(
m.p[0, m.edges[:, ix]].flatten(),
m.p[1, m.edges[:, ix]].flatten(),
m.p[2, m.edges[:, ix]].flatten(),
kwargs['color'] if 'color' in kwargs else 'k',
linewidth=kwargs['linewidth'] if 'linewidth' in kwargs else .5,
)
ax.set_axis_off()
ax.show = lambda: plt.show()
return ax
@draw.register(Mesh2D)
def draw_mesh2d(m: Mesh2D, **kwargs) -> Axes:
"""Visualise a two-dimensional mesh by drawing the edges.
Parameters
----------
m
A two-dimensional mesh.
ax (optional)
A preinitialised Matplotlib axes for plotting.
node_numbering (optional)
If ``True``, draw node numbering.
facet_numbering (optional)
If ``True``, draw facet numbering.
element_numbering (optional)
If ``True``, draw element numbering.
aspect (optional)
Ratio of vertical to horizontal length-scales; ignored if ``ax`` is
specified
boundaries_only (optional)
If ``True``, draw only boundary edges.
Returns
-------
Axes
The Matplotlib axes onto which the mesh was plotted.
"""
if "ax" not in kwargs:
# create new figure
fig = plt.figure(**{k: v for k, v in kwargs.items()
if k in ['figsize']})
ax = fig.add_subplot(111)
aspect = kwargs["aspect"] if "aspect" in kwargs else 1.0
ax.set_aspect(aspect)
ax.set_axis_off()
else:
ax = kwargs["ax"]
if "boundaries_only" in kwargs:
facets = m.facets[:, m.boundary_facets()]
else:
facets = m.facets
plot_kwargs = kwargs["plot_kwargs"] if "plot_kwargs" in kwargs else {}
# faster plotting is achieved through
# None insertion trick.
xs = []
ys = []
for s, t, u, v in zip(m.p[0, facets[0]],
m.p[1, facets[0]],
m.p[0, facets[1]],
m.p[1, facets[1]]):
xs.append(s)
xs.append(u)
xs.append(None)
ys.append(t)
ys.append(v)
ys.append(None)
ax.plot(xs,
ys,
kwargs['color'] if 'color' in kwargs else 'k',
linewidth=kwargs['linewidth'] if 'linewidth' in kwargs else .5,
**plot_kwargs)
if "subdomain" in kwargs:
y = np.zeros(m.t.shape[1])
y[m.subdomains[kwargs['subdomain']]] = 1
plot(m, y, ax=ax)
if "boundaries" in kwargs:
cm = plt.get_cmap('gist_rainbow')
colors = [cm(1.*i/len(m.boundaries)) for i in range(len(m.boundaries))]
for i, k in enumerate(m.boundaries):
facets = m.facets[:, m.boundaries[k]]
xs = []
ys = []
for s, t, u, v in zip(m.p[0, facets[0]],
m.p[1, facets[0]],
m.p[0, facets[1]],
m.p[1, facets[1]]):
xs.append(s)
xs.append(u)
xs.append(None)
ys.append(t)
ys.append(v)
ys.append(None)
ax.plot(xs,
ys,
color=colors[i % len(colors)],
linewidth=(kwargs['linewidth']
if 'linewidth' in kwargs else 2.),
**plot_kwargs)
if hasattr(m.boundaries[k], 'ori'):
tris = m.f2t[m.boundaries[k].ori, m.boundaries[k]]
color = colors[i % len(colors)][:3] + (.1,)
collec = PolyCollection(m.p[:, m.t[:, tris]].T,
color=color)
ax.add_collection(collec)
if "node_numbering" in kwargs:
for itr in range(m.p.shape[1]):
ax.text(m.p[0, itr], m.p[1, itr], str(itr))
if "facet_numbering" in kwargs:
mx = .5*(m.p[0, m.facets[0]] +
m.p[0, m.facets[1]])
my = .5*(m.p[1, m.facets[0]] +
m.p[1, m.facets[1]])
for itr in range(m.facets.shape[1]):
ax.text(mx[itr], my[itr], str(itr))
if "element_numbering" in kwargs:
mx = np.sum(m.p[0, m.t], axis=0) / m.t.shape[0]
my = np.sum(m.p[1, m.t], axis=0) / m.t.shape[0]
for itr in range(m.t.shape[1]):
ax.text(mx[itr], my[itr], str(itr))
ax.show = lambda: plt.show()
return ax
@draw.register(MeshLine1)
def draw_meshline(m: MeshLine1, **kwargs):
"""Draw the nodes of one-dimensional mesh."""
if "ax" not in kwargs:
# create new figure
fig = plt.figure()
ax = fig.add_subplot(111)
else:
ax = kwargs["ax"]
color = kwargs["color"] if "color" in kwargs else 'ko-'
ix = np.argsort(m.p[0])
plot_kwargs = kwargs["plot_kwargs"] if "plot_kwargs" in kwargs else {}
ax.plot(m.p[0][ix], 0. * m.p[0][ix], color, **plot_kwargs)
ax.show = lambda: plt.show()
return ax
@singledispatch
def plot(m, u, **kwargs) -> Axes:
"""Plot functions defined on nodes of the mesh."""
raise NotImplementedError("Type {} not supported.".format(type(m)))
@plot.register(MeshLine1)
def plot_meshline(m: MeshLine1, z: ndarray, **kwargs):
"""Plot a function defined at the nodes of the 1D mesh."""
if "ax" not in kwargs:
# create new figure
fig = plt.figure()
ax = fig.add_subplot(111)
else:
ax = kwargs["ax"]
color = kwargs["color"] if "color" in kwargs else 'ko-'
plot_kwargs = kwargs["plot_kwargs"] if "plot_kwargs" in kwargs else {}
ix = np.argsort(m.p[0])
ax.plot(m.p[0][ix], z[ix], color, **plot_kwargs)
ax.show = lambda: plt.show()
return ax
@plot.register(MeshTri1)
def plot_meshtri(m: MeshTri1, z: ndarray, **kwargs) -> Axes:
"""Visualise piecewise-linear function on a triangular mesh.
Parameters
----------
m
A triangular mesh.
z
An array of nodal values.
ax (optional)
Plot onto the given preinitialised Matplotlib axes.
aspect (optional)
The ratio of vertical to horizontal length-scales; ignored if ax
specified.
colorbar (optional)
If True, show colorbar. If a string, use it as a label for the
colorbar. Not shown by default.
figsize (optional)
Passed on to matplotlib.
shading (optional)
vmin (optional)
vmax (optional)
Passed on to matplotlib.
Returns
-------
Axes
The Matplotlib axes onto which the mesh was plotted.
"""
if "ax" not in kwargs:
fig = plt.figure(**{k: v for k, v in kwargs.items()
if k in ['figsize']})
ax = fig.add_subplot(111)
aspect = kwargs["aspect"] if "aspect" in kwargs else 1.0
ax.set_aspect(aspect)
ax.set_axis_off()
else:
ax = kwargs["ax"]
if 'cmap' in kwargs:
cmap = kwargs['cmap']
else:
cmap = plt.cm.jet
plot_kwargs = kwargs["plot_kwargs"] if "plot_kwargs" in kwargs else {}
if len(z) == 2 * len(m.p[0]):
im = ax.quiver(m.p[0], m.p[1], *z.reshape(2, -1),
**{k: v for k, v in kwargs.items()
if k in ['angles',
'scale',
'width',
'headwidth',
'headlength',
'minshaft',
'pivot',
'color']}, # for backwards compatibility
**plot_kwargs)
else:
im = ax.tripcolor(m.p[0], m.p[1], m.t.T, z, cmap=cmap,
**{k: v for k, v in kwargs.items()
if k in ['shading',
'edgecolors',
'vmin',
'vmax']}, # for backwards compatibility
**plot_kwargs)
if "levels" in kwargs:
ax.tricontour(m.p[0], m.p[1], m.t.T, z,
levels=kwargs["levels"],
**{**{'colors': 'k'}, **plot_kwargs})
if "colorbar" in kwargs and kwargs["colorbar"] is not False:
if isinstance(kwargs["colorbar"], str):
plt.colorbar(im, ax=ax, label=kwargs["colorbar"])
elif isinstance(kwargs["colorbar"], dict):
plt.colorbar(im, ax=ax, **kwargs["colorbar"])
else:
plt.colorbar(im, ax=ax)
ax.show = lambda: plt.show()
return ax
@plot.register(MeshQuad1)
def plot_meshquad(m: MeshQuad1, z, **kwargs):
"""Visualise nodal functions on quadrilateral meshes.
The quadrilaterals are split into two triangles
(:class:`skfem.mesh.MeshTri`) and the respective plotting function for the
triangular mesh is used.
"""
if len(z) == m.t.shape[-1]:
m, z = m.to_meshtri(z)
else:
m = m.to_meshtri()
return plot(m, z, **kwargs)
@plot.register(CellBasis)
def plot_basis(basis: CellBasis, z: ndarray, **kwargs) -> Axes:
"""Plot on a refined mesh via :meth:`CellBasis.refinterp`."""
if "nrefs" in kwargs:
nrefs = kwargs["nrefs"]
elif "Nrefs" in kwargs:
nrefs = kwargs["Nrefs"]
else:
nrefs = 1
return plot(*basis.refinterp(z, nrefs=nrefs), **kwargs)
@singledispatch
def plot3(m, z: ndarray, **kwargs) -> Axes:
"""Plot functions defined on nodes of the mesh (3D)."""
raise NotImplementedError("Type {} not supported.".format(type(m)))
@plot3.register(MeshTri1)
def plot3_meshtri(m: MeshTri1, z: ndarray, **kwargs) -> Axes:
"""Visualise piecewise-linear function, 3D plot.
Parameters
----------
z
An array of nodal values (Nvertices).
ax (optional)
Plot onto the given preinitialised Matplotlib axes.
Returns
-------
Axes
The Matplotlib axes onto which the mesh was plotted.
"""
ax = kwargs.get("ax", plt.figure().add_subplot(1, 1, 1, projection='3d'))
if 'cmap' in kwargs:
cmap = kwargs['cmap']
else:
cmap = plt.cm.jet
ax.plot_trisurf(m.p[0], m.p[1], z,
triangles=m.t.T,
cmap=cmap,
antialiased=False)
ax.show = lambda: plt.show()
return ax
@plot3.register(CellBasis)
def plot3_basis(basis: CellBasis, z: ndarray, **kwargs) -> Axes:
"""Plot on a refined mesh via :meth:`CellBasis.refinterp`."""
if "nrefs" in kwargs:
nrefs = kwargs["nrefs"]
elif "Nrefs" in kwargs:
nrefs = kwargs["Nrefs"]
else:
nrefs = 1
return plot3(*basis.refinterp(z, nrefs=nrefs), **kwargs)
def savefig(*args, **kwargs):
plt.savefig(*args, **kwargs)
def show(*args, **kwargs):
plt.show(*args, **kwargs)