Matplotlib instead of pyvista in Dolfinx

Hey everyone! Thank you very much for helping me last time. I really appreciate them.

Right now I have a question. Maybe it is kind of basic but I really want to figure it out. I am converting some of my fenics code in fenicsx. However, I noticed all fenicsx demo use pyvista to plot instead of matplotlib. Since I am solving a 1D problem, matplotlib is enough for me to use. However, it seems that the situation is different in the new version of dolfin. In old fenics. I just write

plot(uh)
plt.show()

and I can get a nice plot from matplotlib. However, with dolfinx, I get an error. The code is

from dolfinx import plot

plot(uh) # uh is the solution, which is uh = problem.solve()
plt.show()

and the error is

Traceback (most recent call last):
  File "/home/henryyuan/PycharmProjects/Fenicsx simulation/main.py", line 38, in <module>
    plot(uh)
TypeError: 'module' object is not callable

So how can I use matplotlib to plot in this situation? Any help and advice would be appreciated.

We do not have integrated supported for matplotlib, as it is severely limited in plotting unstructured meshes. However, as you are using a 1D mesh, you could simply call

import dolfinx
import numpy as np
from mpi4py import MPI
mesh = dolfinx.mesh.create_unit_interval(MPI.COMM_WORLD, 15)
P = 3
V = dolfinx.fem.FunctionSpace(mesh, ("Lagrange", P))
uh = dolfinx.fem.Function(V)
uh.interpolate(lambda x: np.sin(2*np.pi*x[0]))
x = V.tabulate_dof_coordinates()
x_order = np.argsort(x[:,0])

import matplotlib.pyplot as plt
plt.plot(x[x_order, 0], uh.x.array[x_order])
plt.savefig("u_1d.png")
2 Likes

Thank you very much for your help! I am also planning to use more about pyvista in the future.

So is the same approach also work for 2D mesh? Or it is just for 1D cases?

For 2D meshes you should use pyvista, as matplotlib doesn’t support unstructured quadrilateral meshes, and thus one cannot matplotlib for those.

This is one of the reasons for moving from matplotlib to pyvista, as pyvista uses VTK.

I see. Thank you again for your help. I hope you are having a great day.

Was not matplotlib integrated in FEniCS (not FEniCSx) ?

Legacy fenics had primary support for first order triangles and tetrahedrons, and not higher order or non simplex shapes.