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.

export

Convert and save the graph in a graph export or image format

dotfile

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 of filename if not given

  • options (Any) – format specific options, see below

Raises:
  • ValueError – the format is unknown or cannot be inferred, or an image format is requested without a filename

  • TypeError – 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 filename is None, otherwise None

Return type:

str or None

format

extensions

positions

options

"dot"

.dot .gv

pos="x,y!"

direction, color_components, costs

"mermaid"

.mmd .mermaid

no

direction, color_components, costs, fence

"graphml"

.graphml

x, y, coord

none

"elk"

.elk.json .elk

x, y

size, layout_options

"svg" "pdf" "png" …

the same

yes, via neato

engine, direction, color_components, costs

The text formats need nothing beyond the standard library. The image formats run the GraphViz dot or neato executable.

>>> 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 filename is 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 id elements (GraphML, ELK). A self-loop is written once, as an edge from a vertex to itself.

Seealso:

dotfile() showgraph() pgraph.exporters

Graph.dotfile(filename=None, direction=None)[source]

Export graph as a GraphViz dot file

Parameters:
  • filename (str, path-like or file object, optional) – filename to save graph to, defaults to None

  • direction (str, optional) – layout direction, eg. "LR", defaults to None

Return type:

None

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() with format="dot" and edge costs left unlabelled, as it has always been. Use export() for other formats or for edge labels.

Note

  • The graph is undirected if it is a UGraph

  • The graph is directed if it is a DGraph

Note

The graphviz formatters dot and neato can be used to render the graph in various formats including PDF, PNG, JPG, GIF, SVG, etc. The formatters are similar, but dot is better suited for directed graphs while neato is 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() with costs=True to include them.

Note

If filename is a file object then the file will not be closed after the GraphViz model is written. Safe for use with sys.stdout or sys.stderr.

Seealso:

export() showgraph()

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/neato executable, mapped to whether the result is text (True) or binary (False)

register_exporter(name, *extensions)[source]

Register a text exporter (decorator)

Parameters:
  • name (str) – format name used as export(format=name)

  • extensions (str) – file extensions, with the leading dot, that select this format when format is not given

Return type:

Callable[[Callable[..., str]], Callable[..., str]]

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 a TypeError.

get_exporter(name)[source]

Look up a text exporter by format name

Parameters:

name (str) – format name, eg. "dot"

Return type:

Callable[..., str]

Returns:

the function f(graph, **options) -> str

Raises:

ValueError – no text exporter has that name; the message lists those that do

formats()[source]

Names of all supported export formats

Returns:

text formats followed by rendered image formats

Return type:

list of str

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 a name attribute

Returns:

the format name, or None if it cannot be decided

Return type:

str or None

Compound extensions such as .elk.json are tried before the plain suffix.

dot(graph, *, direction=None, color_components=False, costs=True)[source]

GraphViz DOT text

Parameters:
  • direction (str | None) – layout direction, rankdir in DOT, eg. "LR"

  • color_components (bool) – fill vertices by connected component

  • costs (bool) – label edges with their cost

Return type:

str

mermaid(graph, *, direction='TB', color_components=False, costs=True, fence=False)[source]

Mermaid flowchart text

Parameters:
  • direction (str) – "TB", "BT", "LR" or "RL"

  • color_components (bool) – fill vertices by connected component

  • costs (bool) – label edges with their cost

  • fence (bool) – wrap in a Markdown code fence, three backticks followed by mermaid

Return type:

str

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, y and the full coord string for higher dimensions) and edge cost are written as <data> elements with <key> declarations. edgedefault follows the graph kind. GraphML has no standard node position outside the proprietary yFiles extension, which is not used.

Return type:

str

elk(graph, *, size=(60, 40), layout_options=None)[source]

Eclipse Layout Kernel (ELK) JSON graph text

Parameters:
  • size (tuple[float, float]) – width and height given to every node, which ELK requires

  • layout_options (dict[str, str] | None) – ELK layout options, merged over the defaults

Return type:

str

Unlike GraphML, ELK has native x and y node fields. If any vertex has a coordinate the fixed algorithm is selected so that a consumer keeps the positions; otherwise layered computes 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 of RENDER_FORMATS

  • engine (str | None) – GraphViz layout program, one of ENGINES. Defaults to neato if any vertex has a coordinate, since it honours pinned positions, else dot

Returns:

the image

Return type:

bytes

Raises:
  • ValueError – fmt or engine is not a known name

  • RuntimeError – 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.