A very limited example of how to use Matplotlib

This is some sort of spin-off from my first question in this forum. The experts were really helpful, and I would like to pay back a little.

The users are recommended to use PyVista instead of Matplotlib, since the latter cannot handle the rich variety of output FEniCSx can produce. For some users, like myself, there are some cases when Matplotlib would be just right, like:

  • when the user is already familiar with Matplotlib, and would like to postpone learning PyVista until (s)he has decided to dive deeper into the world of FEniCSx.
  • when the user works with Debian, and has decided to wait for Trixie to be released.
  • when the user simply don’t need the features in FEniCSx that necessitate PyVista.

Anyhow, after having played around with the most basic example Poisson equation — reading the mesh from a file, setting the b.c. based on boundary tags instead of geometric conditions — I tried to figure out how to visualise the result with Matplotlib.

The following ‘solution’ is no doubt a kludge, verging on being a workaround in the sense of xkcd, but it could perhaps serve as a starting point for someone.

First the (2D) mesh has to be translated into something which Matplotlib understands:

from matplotlib import tri

connty = mesh.topology.connectivity(2, 0)
connty_array = np.array([connty.links(i) 
        for i in range(connty.num_nodes)])
tess = tri.Triangulation(
        mesh.geometry.x[:,0], 
        mesh.geometry.x[:,1], 
        triangles=connty_array)

After that, we can use one of the special plotting routines for triangulated data:

from matplotlib import pyplot as plt

fig, ax = plt.subplots()
ax.set_aspect(aspect=1)
ax.tripcolor(tess, uh.x.array)

Now, after having gone through the trouble of writing this, I bet I will find a pressing need for PyVista within the next 24 hours.

2 Likes

It doesn’t seem a kludge to me. And, to be honest, If it’s a two dimensional PDE I prefer using matplotlib rather than pyvista.

My two itches are:

  • Extracting and translating the connectivity table with the help of list comprehension feels slow and cumbersome. Is there no getter?
  • Am I breaking the law of Demeter, reaching too deep into objects for info?