# Color each face of a mesh with a colormap gradient depending on external data

Motivation: Post-process a finite element solver answer file (in my case FEMM).

I'm creating a mesh with Python with the following code (well, my actual code is a bit more complex, but it doesn't matter).

import bpy

mesh = bpy.data.meshes.new("NewMesh")  # add the new mesh
obj = bpy.data.objects.new(mesh.name, mesh)
col = bpy.data.collections.get("Collection")
bpy.context.view_layer.objects.active = obj

verts = [(0, 0, 0),
(1,  1,  0),
(1, -1,  0),
(-1, -1,  0),
(-1, 1,  0),
]

edges = []

faces = [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1]]

face_values = [-1.5, 10, -5, 3]

mesh.from_pydata(verts, edges, faces)


With Python (I have 10000+ faces to colorize), how can I affect a separate color to each face depending on the corresponding value in face_values (based on a color map)?

I'd like to achieve something like that (except that all faces should have a uniform color).

Here is an example that I faked using texture painting:

with [-1.5, 10, -5, 3] corresponding to [red, blue, green, white].

• Have a look into vertex colors: blender.stackexchange.com/a/60730/31447 May 12 '20 at 16:51
• @brockmann Thanks for your comment. As far as I understand, with vertex colors, face colors won't be uniform on each face. Then, if I'm not mistaken, this is not what I'm looking for (I must admit that the image in my question does not properly show this requirement). Please correct me if I'm wrong. May 13 '20 at 8:02
• Sure. You can assign the same color to each vertex of a triangle/quad which makes it a "uniform color" per face component. Does that answer your q? May 13 '20 at 8:20
• So a given vertex can have multiple colors corresponding to the different faces it belongs to? May 13 '20 at 9:08
• Nope, only one value. However your can blend them of course, see blender.stackexchange.com/a/911/31447 May 13 '20 at 9:11