3
$\begingroup$

I'm trying to use GraphPlot to draw a Graph which is constructed from an adjacency matrix and am having trouble with the labels in the plot. I am doing (data is a silly example) the following:

data = Import["~/test.mtx", "MatrixMarket"]
verts = {"Aa", "Ba", "Ca", "Da", "Ea"}

g = WeightedAdjacencyGraph[verts, data, VertexLabels -> "Name"]

Which correctly results in a labelled Adjacency Graph:

Graph Representation

However, when I try and render the graph using a GraphPlot (or similar function...) I always get numbered labels instead. Eg:

GraphPlot[g, 
 VertexRenderingFunction -> ({White, EdgeForm[Black], Disk[#, .1], 
     Black, Text[#2, #1]} &)]

renders as:

GraphPlot rendering of g

My question is how can I get GraphPlot (and similar) to use the vertex names like Graph itself does? Alternatively, is there a better way of providing vertex names when using an Adjacency Matrix? (My real dataset has many thousands of vertices and edges).

$\endgroup$
6
$\begingroup$

You can modify your VertexRenderingFunction using Text[verts[[#2]], #1] instead of Text[#2, #1]:

verts = {"Aa", "Ba", "Ca", "Da", "Ea", "Fa"};

g1 = WeightedAdjacencyGraph[SparseArray[{{i_, j_} /; (i != j) -> 1}, {6, 6}, \[Infinity]], 
   VertexLabels -> Thread[Range[6] -> verts], ImagePadding -> 20, ImageSize -> 400];
g2 = GraphPlot[g1, ImageSize -> 400,  VertexRenderingFunction -> ({White, EdgeForm[Black],
   Disk[#, .1], Black, Text[verts[[#2]], #1]} &)];
Row[{g1, g2}, Spacer[10]]

enter image description here

or, using Text[#2 /. PropertyValue[g1, VertexLabels], #1]

g3 = GraphPlot[g1, ImageSize -> 400, VertexRenderingFunction ->
   ({White, EdgeForm[Black], Disk[#, .1], Black, 
      Text[#2 /. PropertyValue[g1, VertexLabels], #1]} &)]

enter image description here

Update: Unless you have special reasons to use GraphPlot, you can achieve the same results using Graph:

wam = SparseArray[{{i_, j_} /; (i != j) -> 1}, {6, 6}, \[Infinity]];
WeightedAdjacencyGraph[Labeled[#, Style[#, 24, "Panel", Background -> None], Center] & /@ verts, 
      wam, VertexSize -> Large]

or

WeightedAdjacencyGraph[wam, VertexSize -> Large,
 VertexLabels -> Thread[Range[6] -> 
   (Placed[Style[#, 24, "Panel", Background -> None], Center] & /@ verts)]]

gives

enter image description here

$\endgroup$
  • $\begingroup$ It feels to me as though GraphPlot (and similar) should just pick up the vertex names provided to the Graph and is therefore "buggy", but these are useful ways round it. Thanks. $\endgroup$ – Richard Dec 7 '14 at 19:18
  • $\begingroup$ @barns, thank you for the Accept. $\endgroup$ – kglr Dec 7 '14 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.