Consider the following minimal example:
import numpy as np
import matplotlib.pyplot as plt
from mpi4py import MPI
import dolfinx
import ufl
# define mesh and function space
N = 10
degree = 1
msh = dolfinx.mesh.create_unit_square(MPI.COMM_WORLD,N,N)
V = dolfinx.fem.functionspace(msh, ("Lagrange", degree))
x = ufl.SpatialCoordinate(msh)
uf = dolfinx.fem.Function(V)
uf.interpolate(lambda x : np.sin(2*np.pi*x[0]) + 3*x[1])
# points = msh.geometry.x # I can use either this or tabulate_dof_coordinates() to get coordinates of corresponding nodal values
# dof_coor = np.delete(points,2,1)
array = uf.x.array
# print(dof_coor.dtype)
dof_coord = V.tabulate_dof_coordinates()[:, :2]
# Compute input index
indices = dof_coord / (1./N)
input_indices = np.round(indices).astype(np.int32)
y_sort = np.argsort(input_indices[:, 1])
sorted_coords = dof_coord[y_sort]
sorted_values = array[y_sort]
# Check that x-axis is sorted by increasing x coordinate (per y coord)
for i in range(N+1):
sub_indices = np.flatnonzero(input_indices[y_sort, 1]==i)
sub_sort = np.argsort(input_indices[y_sort[sub_indices], 0])
sub_coords = sorted_coords[sub_indices]
sub_vals = sorted_values[sub_indices]
sorted_coords[sub_indices] = sub_coords[sub_sort]
sorted_values[sub_indices] = sub_vals[sub_sort]
sorted_values = sorted_values.reshape(N+1, N+1)
X_ = sorted_coords[:, 0].reshape(N+1, N+1)
Y_ = sorted_coords[:, 1].reshape(N+1, N+1)
a = 0
b = 1
x, y = np.linspace(a,b,N+1,dtype = np.float64), np.linspace(a,b,N+1,dtype = np.float64)
X,Y = np.meshgrid(x,y)
np.testing.assert_allclose(X_, X, atol=1e-15, rtol=1e-12)
np.testing.assert_allclose(Y_, Y, atol=1e-15, rtol=1e-12)
X_flat, Y_flat = X.flatten(), Y.flatten()
# Use the mapping to assign values to new coordinates
fig = plt.figure()
ax = plt.gca()
im1 = ax.imshow(sorted_values, cmap="viridis")
ax.invert_yaxis()
fig.colorbar(im1)
plt.savefig("test.png")
fig2 = plt.figure()
ax2 = plt.gca()
im2 = ax2.scatter(dof_coord[:,0], dof_coord[:,1], c=uf.x.array, cmap="viridis")
fig2.colorbar(im2)
plt.savefig("test2.png")
yielding: