How to export and import Graphs with additional data?



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.


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


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

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


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?


Posted 2012-01-18T22:21:28.147

Reputation: 405



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]]


Posted 2012-01-18T22:21:28.147

Reputation: 9 867


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.

Van Parunak

Posted 2012-01-18T22:21:28.147

Reputation: 31