Exporting a graph
Graphs can be exported to a number of different formats, including dot (used by GraphViz), Mermaid (a JavaScript-based graph visualization tool that can be used in Markdown documents), GraphML (an XML-based format for representing graphs), ELK (a graph layout engine), as well as various image formats (e.g., PNG, SVG, PDF).
See Visualization for rendering the graph using Matplotlib itself rather than exporting it.
Convert and save the graph in a graph export or image format |
|
Export graph as a GraphViz dot file |
Details
- Graph.export(filename=None, format=None, **options)[source]
Convert and save the graph in a graph export or image format
- Parameters:
filename (str, path-like or file object, optional) – destination path or open file, defaults to None
format (str, optional) –
"dot","mermaid","graphml","elk"or an image format"svg","pdf","png"…, inferred from the extension offilenameif not givenoptions (
Any) – format specific options, see below
- Raises:
ValueError – the format is unknown or cannot be inferred, or an image format is requested without a
filenameTypeError – an option is not valid for the format
RuntimeError – an image format is requested and GraphViz is not installed, or fails
- Returns:
the text if
filenameis None, otherwise None- Return type:
str or None
formatextensions
positions
options
"dot".dot.gvpos="x,y!"direction,color_components,costs"mermaid".mmd.mermaidno
direction,color_components,costs,fence"graphml".graphmlx,y,coordnone
"elk".elk.json.elkx,ysize,layout_options"svg""pdf""png"…the same
yes, via
neatoengine,direction,color_components,costsThe text formats need nothing beyond the standard library. The image formats run the GraphViz
dotorneatoexecutable.>>> from pgraph import UGraph >>> g = UGraph() >>> v1 = g.add_vertex(coord=[0,0], name='v1') >>> v2 = g.add_vertex(coord=[1,1], name='v2') >>> g.add_edge(v1, v2, cost=2) Edge{[v1] -- [v2], cost=2} >>> print(g.export(format="mermaid", direction="LR")) flowchart LR n0["v1"] n1["v2"] n0 ---|"2"| n1
Note
Output is reproducible: vertices are written in creation order and edges in the order of their vertices, not in set order.
A file object passed as
filenameis written but not closed. A path is opened, and closed even if writing fails.Names are escaped for each format, and Mermaid, GraphML and ELK use generated ids so any vertex name is valid.
For graphs with parallel edges or loops
Every edge is written, each with its own cost, so parallel edges give repeated lines (DOT, Mermaid) or distinct
idelements (GraphML, ELK). A self-loop is written once, as an edge from a vertex to itself.- Seealso:
- Graph.dotfile(filename=None, direction=None)[source]
Export graph as a GraphViz dot file
- Parameters:
- Return type:
g.dotfile()creates the specified file which contains the GraphViz code to represent the embedded graph. By default output is to the console.This is
export()withformat="dot"and edge costs left unlabelled, as it has always been. Useexport()for other formats or for edge labels.Note
The
graphvizformattersdotandneatocan be used to render the graph in various formats including PDF, PNG, JPG, GIF, SVG, etc. The formatters are similar, butdotis better suited for directed graphs whileneatois better suited for undirected graphs.>>> from pgraph import UGraph >>> g = UGraph() >>> v1 = g.add_vertex(coord=[0,0], name='v1') >>> v2 = g.add_vertex(coord=[1,1], name='v2') >>> g.add_edge(v1, v2) Edge{[v1] -- [v2], cost=1.414} >>> g.dotfile() graph { "v1" [pos="0,0!"] "v2" [pos="1,1!"] "v1" -- "v2" }
Note
Edge costs are not included in the output. Use
export()withcosts=Trueto include them.Note
If
filenameis a file object then the file will not be closed after the GraphViz model is written. Safe for use withsys.stdoutorsys.stderr.- Seealso:
The exporters
export() hands the work to the functions of
pgraph.exporters. The options of each format are the keyword arguments
of its function, which are passed through export(..., **options). The
module also provides the means to add a format of your own.
Export a graph as text (GraphViz DOT, Mermaid, GraphML, ELK JSON) or as a rendered image (via the GraphViz command line tools).
This module is reached through export(), which
dispatches on the format name or the file extension. Each text exporter is a
plain function f(graph, **options) -> str, registered with
register_exporter(), so a user can add a format without touching the
package:
from pgraph.exporters import register_exporter
@register_exporter("gexf", ".gexf")
def gexf(graph, *, version="1.3") -> str:
...
None of the text formats needs a dependency beyond the standard library. Only
the rendered formats (RENDER_FORMATS) need the GraphViz executables.
- ENGINES = ('dot', 'neato', 'fdp', 'sfdp', 'twopi', 'circo', 'osage', 'patchwork')
GraphViz layout programs that may be run to render an image
- RENDER_FORMATS: dict[str, bool] = {'gif': False, 'jpeg': False, 'jpg': False, 'pdf': False, 'png': False, 'ps': True, 'svg': True}
image formats produced by running the GraphViz
dot/neatoexecutable, mapped to whether the result is text (True) or binary (False)
- register_exporter(name, *extensions)[source]
Register a text exporter (decorator)
- Parameters:
- Return type:
- Returns:
the decorator
The decorated function is called as
f(graph, **options)and returns the text. Declare its options as keyword-only parameters so that an unknown option is aTypeError.
- get_exporter(name)[source]
Look up a text exporter by format name
- Parameters:
name (
str) – format name, eg."dot"- Return type:
- Returns:
the function
f(graph, **options) -> str- Raises:
ValueError – no text exporter has that name; the message lists those that do
- format_from_filename(filename)[source]
Infer an export format from a file name’s extension
- Parameters:
filename (
str|PathLike|IO|None) – path, or a file object with anameattribute- Returns:
the format name, or None if it cannot be decided
- Return type:
str or None
Compound extensions such as
.elk.jsonare tried before the plain suffix.
- mermaid(graph, *, direction='TB', color_components=False, costs=True, fence=False)[source]
Mermaid flowchart text
- Parameters:
- Return type:
Mermaid flowcharts are laid out automatically and cannot pin node positions, so vertex coordinates are not represented. Vertices are given generated ids (
n0,n1, …) with the real name as the label, since names are arbitrary strings but Mermaid ids are not.
- graphml(graph)[source]
GraphML XML text
Name, component, coordinate (
x,yand the fullcoordstring for higher dimensions) and edge cost are written as<data>elements with<key>declarations.edgedefaultfollows the graph kind. GraphML has no standard node position outside the proprietary yFiles extension, which is not used.- Return type:
- elk(graph, *, size=(60, 40), layout_options=None)[source]
Eclipse Layout Kernel (ELK) JSON graph text
- Parameters:
- Return type:
Unlike GraphML, ELK has native
xandynode fields. If any vertex has a coordinate thefixedalgorithm is selected so that a consumer keeps the positions; otherwiselayeredcomputes a layout.
- render(graph, fmt, *, engine=None, direction=None, color_components=False, costs=True)[source]
Render the graph to an image with the GraphViz executables
- Parameters:
fmt (
str) – one ofRENDER_FORMATSengine (
str|None) – GraphViz layout program, one ofENGINES. Defaults toneatoif any vertex has a coordinate, since it honours pinned positions, elsedot
- Returns:
the image
- Return type:
- Raises:
ValueError –
fmtorengineis not a known nameRuntimeError – the layout program is not installed, or failed
Both names are checked against fixed lists and the program is run with an argument list and no shell, so neither can carry a command.