# ListDensityPlot with discrete values and colors

I have a file with mesh points and a value that indicates the domain the point belongs to

https://www.dropbox.com/sh/ll9hb3oxxreufsg/AABvU7nufHhyHY3W4ausanJ6a?dl=0

I would like to plot using DensityPlot and showing the mesh in different colors (assuming two domains) according to the domain by using MeshShading

data = Import["https://www.dropbox.com/sh/ll9hb3oxxreufsg/AAA6hJL-suwY6MSslRtuSE7Fa/mesh_and_domain.txt?dl=1", "Table"];

n = Max[data[[;; , 3]]];
domidx = Range[n];
color = {RGBColor[1, 0, 0], RGBColor[0, 0, 1]};
dom = Table[Select[data, #[[3]] == idx &], {idx, domidx}];
Show @@
{Table[
ListDensityPlot[dom[[idx]], Mesh -> All, InterpolationOrder -> 1,
PlotRange -> {{0, 2}, {0, 1}}, AspectRatio -> 0.5}


However MeshShading is not accepted as an option for ListDensityPlot

Do you have some idea how to solve it?

Thanks for the suggestions

• Replace MeshShading with MeshStyle? Jan 19, 2016 at 11:52
• That changes the color of the mesh lines, I would like to control the color corresponding to the "density", I guess is the shading or at least a kind of piecewise colorfunction Jan 19, 2016 at 11:55
• So the density plot is just flat, since the third value of each element is the same. Do you want a black mesh on top of a solid color, which is different for the two domains? If that's the case, you could replace your MeshShading option with ColorFunction -> (color[[idx]] &) Jan 19, 2016 at 12:08
• Oh yeah, that is working! Jan 19, 2016 at 16:05

With just a slight modification to your code,

Show @@ {Table[
ListDensityPlot[dom[[idx]], Mesh -> All, InterpolationOrder -> 1,
ColorFunction -> (color[[idx]] &)], {idx, domidx}],
PlotRange -> {{0, 2}, {0, 1}}, AspectRatio -> 0.5}


Or you can use a custum color function

ListDensityPlot[data,
ColorFunction -> (Which[#1 == 1, Red, #1 == 2, Blue] &),
ColorFunctionScaling -> False, InterpolationOrder -> 1,
AspectRatio -> 0.5, Mesh -> All]


I like the plot better with InterpolationOrder -> 0, but then it draws the mesh differently (around the points rather than through them)

You can do it without generating all these variables.

data = Import["https://www.dropbox.com/sh/ll9hb3oxxreufsg/AAA6hJL-suwY6MSslRtuSE7Fa/mesh_and_domain.txt?dl=1", "Table"]


Separate using GatherBy[data, Last] (GatherBy).

Change colours using the index of MapIndexed,to RotateLeft the list {0,0,1} and use as argument for RGBColor

Show[
MapIndexed[
ListDensityPlot[#1
, Mesh -> All
, InterpolationOrder -> 1
, ColorFunction ->
Function[z, RGBColor[RotateLeft[{0, 0, 1}, Last[#2]]]]
] &,
GatherBy[data, Last]
], PlotRange -> {{0, 2}, {0, 1}}, AspectRatio -> 0.5]


If you have more than three colours, probably you could use Hue[#2/n] (Hue)