Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to export and then later import graphs with additional data added such as VertexLabels and EdgeLabels. When I export a graph, such as the following, and then import it, I find that some information has been lost.

g=Graph[{1->2,2->3,3->1},VertexLabels->"Name",VertexStyle->Purple,VertexShapeFunction->"Diamond"];
Export["graph.gml",g];
r=Import["graph.gml"]

This will maintain some of the options, e.g. VertexShapeFunction and VertexStyle, but will lose VertexLabels.

PropertyValue[r,VertexLabels]

The above returns {},showing that the data was not retained.

I have tried .graphml and .gxl formats as well, with the same issues.

Import["graph.gml",{{VertexLabels}}]

The above returns the following error:

Import::noelem: The Import element "VertexLabels" is not present when importing as Graphlet. >>

What is the best way to export and then import graphs while retaining all additional data?

share|improve this question
up vote 18 down vote accepted

I think it must be an oversight in the graph export code (it also happens when exporting to graph formats other than Graphlet). If you use explicit labels in Mathematica, it gets exported properly, just the implicit VertexLabels -> "Name" does not.

Note that since the export formats do not have an equivalent of VertexLabels -> "Name", you'd expect the export/import cycle to yield explicit VertexLabels.

So, I guess you should submit a bug report to Wolfram Research.

In the meantime, the work around of using explicit labels should not be too onerous; e.g.,

Graph[{1 -> 2, 2 -> 3, 3 -> 1}, VertexLabels -> Table[i -> i, {i, 3}],
  VertexStyle -> Purple, VertexShapeFunction -> "Diamond"]

This can be automated in Export by using something like

ExportGraph[file_String, g_Graph, opts___] :=
 If[Flatten[{PropertyValue[g, VertexLabels]}] === {"Name"},
  Export[file, SetProperty[g,
         VertexLabels -> Table[i -> i, {i, VertexList[g]}]], opts],
  Export[file, g, opts]]
share|improve this answer

If you don't want to import the graph into some other application, but simply save it for later use, I've found that just saving the graph in .m format preserves everything just fine:

Export["graph.m", graph]

This is the only approach I've found that preserves property lists, labels, everything.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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