Search code examples
wolfram-mathematicamathematica-8

How plot a 2D Density graph from a set of 2D points and displaying also a network connecting those vertices


My problem is the following.

The aim

Plotting a set of 2D points on the plane having a function used to give intensity for every point.

fun(x,y):=x+y

Plus, I have a graph connecting these points. I need to display the graph on the density plot, this is definitely necessary.

The problem

Got no clue how to do it. I searched a little the Mathematica documentation but I could not find much.

Some notes

Whenever someone finds a solution to this, I have also a question. How is it piossible to use the graph functionality on the density plot diagram? For example, if I wanted to show the labels on vertices, is it possible to have some sort of parametrized solution. Maybe I am requiring too much, this is only a little note, skip it if it takes too much time.

Final notes

I am requiring a 2D graph. Not a 3D one. Just a 2D is fine.


Solution

  • Graph has an option VertexCoordinates with which you can specify the coordinates of the vertices, so you could plot a ListDensityPlot and a Graph on top of each other. For example, suppose your data is something like

    f[x_, y_] := x + y
    pts = RandomReal[1, {40, 2}];  (* xy coordinates *)
    edges = Flatten[Table[{i -> Position[pts, #][[1, 1]]} & /@ 
       Rest[Nearest[pts, pts[[i]], 4]], {i, Length[pts]}]];
    edges = Union[edges, SameTest -> (SameQ[#1, #2] || SameQ[#1, Reverse[#2]] &)];
    

    Then you could do something like

    densPlot = ListDensityPlot[{##, f[##]} & @@@ pts];
    graph = Graph[Range[Length[pts]], edges,
       VertexCoordinates -> pts, 
       VertexShapeFunction -> "Square", 
       VertexSize -> 1.5, VertexLabels -> "Name", 
       EdgeStyle -> Directive[Opacity[1], White]];
    
    Show[densPlot, graph]
    

    Mathematica graphics