# Using ListPlot3D with custom colours

I would like to use ListPlot3D to make a 3D plot using a file containing the following information (4 columns):

 x,  y,  f(x,y),  w(x,y).


Here x and y are the coordinates in the Cartesian framework, f(x,y) is some function that depends on x and y, and w(x,y) is another function that represents weights of the function f. So for each data point in f(x,y) we have the corresponding weight w(x,y).

To plot the function f(x,y) I do the following:

f = Import["file.dat", "Table"];
ListPlot3D[f]


and that is fine.

Now I want to have this plot but with colours determined by the weights, i.e. for each point in "f" I would like to have the colour determined by the value of "w". Suppose "w" takes values from 0 to 1, I want that 0 corresponds to "blue" and 1 corresponds to "red", and all values in-between is the gradient between "blue" and "red". For example, if I have a row in "file.dat": 0, 1, 10, 0.5, I would like a 3D plot where at (x,y)=(0,1) the value of the function is f=10 and the colour of this point is 50% blue and 50% red. Can you suggest please how to do this in Mathematica?

• ColorFunction and Blend are the two functions you want to look into. Jan 22, 2021 at 4:38

You can achieve this using the option ColorFunctionof ListPlot3D.

We first create test some data, then define the color function and finally make the plot:

dat = Flatten[
Table[{x, y, Sin[x y], Sin[x ]^2 Sin[y ]^2}, {x, 0, Pi, Pi/20}, {y,
0, Pi, Pi/20}], 1];

col = Interpolation[dat[[All, {1, 2, 4}]]];
colfunction := Function[{x, y, z}, RGBColor[col[x, y], 0, 1 - col[x, y]]];

ListPlot3D[dat[[All, 1 ;; 3]], ColorFunction -> colfunction,
ColorFunctionScaling -> False] • Thank you! A follow up question regarding your example: how to use opacity in such a way that it is applied selectively to different colours. More specifically, I would like to have red colour with opacity 1.0 and blue colour with opacity 0.1. What is the best to do this? Feb 1, 2021 at 16:44

To achieve: " red colour with opacity 1.0 and blue colour with opacity 0.1" use the following:

dat = Flatten[
Table[{x, y, Sin[x y], Sin[x]^2 Sin[y]^2}, {x, 0, Pi, Pi/20}, {y,
0, Pi, Pi/20}], 1];

col = Interpolation[dat[[All, {1, 2, 4}]]];
colfunction :=
Function[{x, y, z}, {Opacity[0.1 (1 - col[x, y]) + col[x, y]],
RGBColor[col[x, y], 0, 1 - col[x, y]]}];

ListPlot3D[dat[[All, 1 ;; 3]], ColorFunction -> colfunction,
ColorFunctionScaling -> False] 