Renders SVG from graphs described in the DOT language using the @hpcc-js/wasm port of Graphviz and does animated transitions between graphs.
- Rendering of SVG graphs from DOT source
- Animated transition of one graph into another
- Edge path tweening
- Node shape tweening
- Fade-in and fade-out of entering and exiting nodes and edges
- Animated growth of entering edges
- Panning & zooming of the generated graph
Graphviz methods typically return the Graphviz renderer instance, allowing the concise application of multiple operations on a given graph renderer instance via method chaining.
To render a graph, select an element, call selection.graphviz, and then render from a DOT source string. For example:
d3.select("#graph")
.graphviz()
.renderDot('digraph {a -> b}');
It is also possible to call d3.graphviz with a selector as the argument like so:
d3.graphviz("#graph")
.renderDot('digraph {a -> b}');
This basic example can also be seen here.
A more colorful demo can be seen here.
The easiest way to use the library in your own application is to install it with NPM:
npm install d3-graphviz
If you don't use npm, you can download the latest release.
You normally don't need to do this, but if you prefer, you can clone from github and build your own copy of the library with:
git clone https://github.com/magjac/d3-graphviz.git
cd d3-graphviz
npm install
npm run build
The built library will then be in build/d3-graphviz.js
Uses @hpcc-js/wasm to do a layout of a graph specified in the DOT language and generates an SVG text representation, which is analyzed and converted into a data representation. Then D3 is used to join this data with a selected DOM element, render the SVG graph on that element and to animate transitioning of one graph into another.
- API Reference
- Examples
- Building Applications with d3-graphviz
- Data Format
- Performance
- Requirements
- Support
- Development
- Credits
- Defining the @hpcc-js/wasm Script Tag
- Creating a Graphviz Renderer
- Setting and Getting Options
- Getting the Graphviz version
- Rendering
- Images
- Creating Transitions
- Control Flow
- Controlling Fade-In & Fade-Out
- Controlling Animated Growth of Entering Edges
- Controlling Path Tweening
- Controlling Shape Tweening
- Maintaining Object Constancy
- Customizing Graph Attributes
- Accessing Elements of the Generated Graph
- Accessing the Extracted Data
- Modifying an Existing Graph and Animating the Changes
- Destroying the Graphviz Renderer
The "@hpcc-js/wasm" script provides functions to do Graphviz layouts. If a web worker is used, these functions are called from the web worker which then loads and compiles the "@hpcc-js/wasm" script explicitly. In this case, it's unnecessary to let the browser also load and compile the script. This is accomplished by using the script tag "javascript/worker" which the browser does not identify to be Javascript and therefore does not compile. However, there are two d3-graphviz functions, drawNode and drawEdge that calls the layout functions directly and if they are going to be used, the script type must be "application/javascript" or "text/javascript".
Examples:
<script src="https://unpkg.com/@hpcc-js/wasm/dist/graphviz.umd.js" type="application/javascript/"></script>
This will always work, but will not be optimal if the script is used in a web worker only.
<script src="https://unpkg.com/@hpcc-js/wasm/dist/graphviz.umd.js" type="javascript/worker"></script>
This will work if a web worker is used and the drawNode and drawEdge functions are not used and will give shorter page load time.
The following table summarizes the recommended script type:
useWorker = true (default) or useSharedWorker = true |
useWorker = false and useSharedWorker = false |
|
---|---|---|
drawNode()/drawEdge() is not used | javascript/worker | application/javascript |
drawNode()/drawEdge() is used | application/javascript | application/javascript |
# selection.graphviz([options]) <>
Returns a new graphviz renderer instance on the first element in the given selection. If a graphviz renderer instance already exists on that element, instead returns the existing graphviz renderer instance. If options is specified and is an object, its properties are taken to be options to the graphviz renderer. All options except the useWorker and useSharedWorker options can also be changed later, using individual methods or the graphviz.options method, see below.
Option | Default value |
---|---|
convertEqualSidedPolygons | true |
engine | 'dot' |
fade | true |
fit | false |
growEnteringEdges | true |
height | null |
keyMode | 'title' |
scale | 1 |
tweenPaths | true |
tweenPrecision | 1 |
tweenShapes | true |
useWorker¹ | true |
useSharedWorker¹ | false |
width | null |
zoom | true |
zoomScaleExtent | [0.1, 10] |
zoomTranslateExtent | [[-∞, -∞], [+∞, +∞]] |
¹ Only has effect when the graphviz renderer instance is created.
All options are described below. Only the specified options will be changed. The others will keep their current values. If options is a boolean it is taken to be the useWorker option (for backwards compatibility).
If the useSharedWorker option is truthy, a shared web worker will be used for the layout stage. Otherwise, if useWorker is truthy, a dedicated web worker will be used. If both are falsey, no web worker will be used.
# d3.graphviz(selector[, options]) <>
Creates a new graphviz renderer instance on the first element matching the given selector string. If the selector is not a string, instead creates a new graphviz renderer instance on the specified node. If a graphviz renderer instance already exists on that element, instead returns the existing graphviz renderer instance. See selection.graphviz for a description of the options argument.
# graphviz.options([options]) <>
If options is specified it is taken to be an object whose properties are used to set options to the graphviz renderer. See selection.graphviz for a list of supported options. Most options can also be changed by individual methods which are described separately. If options is not specified, a copy of the currently set options are returned as an object.
# graphviz.graphvizVersion() <>
Returns the Graphviz version.
# graphviz.renderDot(dotSrc[, callback]) <>
Starts rendering of an SVG graph from the specified dotSrc string and appends it to the selection the Graphviz renderer instance was generated on. graphviz.renderDot returns "immediately", while the rendering is performed in the background. The layout stage is performed by a web worker (unless the use of a web worker was disabled when the renderer instance was created).
It is also possible to do the Graphviz layout in a first separate stage and do the actual rendering of the SVG as a second step like so:
d3.select("#graph")
.graphviz()
.dot('digraph {a -> b}')
.render();
This enables doing the computational intensive layout stages for multiple graphs before doing the potentially synchronized rendering of all the graphs simultaneously.
# graphviz.dot(dotSrc[, callback]) <>
Starts computation of the layout of a graph from the specified dotSrc string and saves the data for rendering the SVG with graphviz.render at a later stage. graphviz.dot returns "immediately", while the layout is performed by a web worker in the backrgound. If callback is specified and not null, it is called with the this
context as the graphviz instance, when the layout, data extraction and data processing has been finished.
# graphviz.render([callback]) <>
Starts rendering of an SVG graph from data saved by graphviz.dot and appends it to the selection the Graphviz renderer instance was generated on. graphviz.render returns "immediately", while the rendering is performed in the backrgound. If computation of a layout, started with the graphviz.dot method has not yet finished, the rendering task is placed in a queue and will commence when the layout is ready. If callback is specified and not null, it is called with the this
context as the graphviz instance, when the graphviz renderer has finished all actions.
Sets the Graphviz layout engine name to the specified engine string. In order to have effect, the engine must be set before calling graphviz.dot or graphviz.renderDot. Supports all engines that @hpcc-js/wasm supports. Currently these are:
- circo
- dot (default)
- fdp
- sfdp
- neato
- osage
- patchwork
- twopi
# graphviz.onerror(callback) <>
If callback is specified and not null, it is called with the this
context as the graphviz instance and the error message as the first argument, if the layout computation encounters an error. If callback is null, removes any previously registered callback.
# graphviz.addImage(path,width,height) <>
Add image references as dictated by viz.js, must be done before renderDot() or dot(). addImage can be called multiple times.
path may be a filename ("example.png"), relative or absolute path ("/images/example.png"), or a URL ("http://example.com/image.png") Dimensions(width,height) may be specified with units: in, px, pc, pt, cm, or mm. If no units are given or dimensions are given as numbers, points (pt) are used.
Graphviz does not actually load image data when this option is used — images are referenced with the dimensions given, e.g. in SVG by an <image> element with width and height attributes.
d3.graphviz("#graph")
.addImage("images/first.png", "400px", "300px")
.addImage("images/second.png", "400px", "300px")
.renderDot('digraph { a[image="images/first.png"]; b[image="images/second.png"]; a -> b }');
# graphviz.transition([name]) <>
Applies the specified transition name to subsequent SVG rendering. Accepts the same arguments as selection.transition or a function, but returns the graph renderer instance, not the transition. If name is a function, it is taken to be a transition factory. A transition factory is a function that returns a transition; when the rendering starts, the factory is evaluated once, with the this
context as the graphviz instance. To attach a preconfigured transition, first create a transition instance with d3.transition, configure it and attach it with graphviz.transition like so:
var t = d3.transition()
.duration(750)
.ease(d3.easeLinear);
d3.select("#graph").graphviz()
.transition(t)
.renderDot('digraph {a -> b}');
A transition is scheduled when it is created. The above example will schedule the transition before the layout is computed, i.e. synchronously. But if, instead, a transition factory is used, the transition will be scheduled after the layout is computed, i.e. asynchronously.
NOTE: Transitions should be named if zooming is enabled. Transitions using the null name will be interrupted by the zoom behavior, causing the graph to be rendered incorrectly.
Returns the active transition on the generated graph's top level svg with the specified name, if any. If no name is specified, null is used. Returns null if there is no such active transition on the top level svg node. This method is useful for creating chained transitions.
The SVG size determines the area in which the graph can be panned and zoomed, while the graph size determines the area that the graph occupies before it is panned or zoomed. The default is that these two areas are the same.
The size of the graph is determined in three optional steps:
- The SVG size can be set with graphviz.width and/or graphviz.height.
- The graph can be scaled to fit the SVG size with graphviz.fit or maintain its original size.
- The graph can be additionally scaled with a scaling factor with graphviz.scale.
The SVG width attribute is set to width pixels.
The SVG height attribute is set to height pixels.
If fit is falsey (default), the viewBox attribute of the SVG is set so that the graph size (before scaling with graphviz.scale) is its orignal size, i.e. unaffected by a possible SVG size change with graphviz.width or graphviz.height. If fit is truthy, the viewBox attribute of the SVG is unchanged, which causes the graph size (before scaling with graphviz.scale) to fit the SVG size. Note that unless the SVG size has been changed, this options has no effect.
The viewBox attribute of the SVG is set so that the graph size (after a possible fit to the SVG size with graphviz.fit) is scaled with scale. For example: If scale is 0.5, then if fit is truthy, the graph width and height is half the width and height of the SVG, while if fit is falsey, the graph width and height is half of its original width and height.
For advanced usage, the Graphviz renderer provides methods for custom control flow.
# graphviz.on(typenames[, listener]) <>
Adds or removes a listener to the Graphviz renderer instance for the specified event typenames. The typenames is one of the following string event types:
initEnd
- when the Graphviz renderer has finished initialization.start
- when analysis of the DOT source starts.layoutStart
- when the layout of the DOT source starts.layoutEnd
- when the layout of the DOT source ends.dataExtractEnd
- when the extraction of data from the SVG text representation ends.dataProcessPass1End
- when the first pass of the processing of the extracted data ends.dataProcessPass2End
- when the second pass of the processing of the extracted data ends.dataProcessEnd
- when the processing of the extracted data ends.renderStart
- when the rendering preparation starts, which is just before an eventual transition factory is called.renderEnd
- when the rendering preparation ends.transitionStart
- when the animated transition starts.transitionEnd
- when the animated transition ends.restoreEnd
- when possibly converted paths and shapes have been restored after the transition.end
- when the Graphviz renderer has finished all actions.zoom
- when the layout has been zoomed.
Note that these are not native DOM events as implemented by selection.on and selection.dispatch, but Graphviz events!
The type may be optionally followed by a period (.
) and a name; the optional name allows multiple callbacks to be registered to receive events of the same type, such as start.foo
and start.bar
. To specify multiple typenames, separate typenames with spaces, such as interrupt end
or start.foo start.bar
.
When a specified Graphviz event is dispatched, the specified listener will be invoked with the this
context as the graphviz instance.
If an event listener was previously registered for the same typename on a selected element, the old listener is removed before the new listener is added. To remove a listener, pass null as the listener. To remove all listeners for a given name, pass null as the listener and .foo
as the typename, where foo
is the name; to remove all listeners with no name, specify .
as the typename.
# graphviz.logEvents(enable) <>
If enable is true (default), adds event listeners, using the name "log", for all available events. When invoked, each listener will print a one-line summary containing the event number and type, the time since the previous event and the time since the "start" event to the console log. For some events, additionally calculated times are printed. This method can be used for debugging or for tuning transition delay and duration. If enable is false, removes all event listeners named "log".
If enable is true (default), enables fade-in and fade-out of nodes and shapes, else disables fade-in and fade-out.
# graphviz.growEnteringEdges(enable) <>
If enable is true (default), enables animated growth of entering edges, else disables animated growth of entering edges.
Note: Growing edges with style tapered
is not supported.
A demo of animated growth of entering edges can be seen here
# graphviz.tweenPaths(enable) <>
If enable is true (default), enables path tweening, else disables path tweening.
# graphviz.tweenPrecision(precision) <>
If precision is a number, sets the precision used during path tweening to precision points. The precision is the length of each path segment during tweening. If instead precision is a string containing '%', sets the relative precision. When using a relative precision, the absolute precision is calculated as the length of the object being tweened multiplied with the relative precision, i.e. the number of line segments during tweening will be the inverse of the relative precision. For example, a relative precision of 5% will give 20 line segments. For a path which is 200 points long, this will give a precision of 10 points. Default is an absolute precision of 1 point.
# graphviz.tweenShapes(enable) <>
If enable is true (default), enables shape tweening during transitions, else disables shape tweening. If enable is true, also enables path tweening since shape tweening currently is performed by converting SVG ellipses and polygons to SVG paths and do path tweening on them. At the end of the transition the original SVG shape element is restored.
# graphviz.convertEqualSidedPolygons(enable) <>
If enable is true (default), enables conversion of polygons with equal number of sides during shape tweening, else disables conversion. Not applicable when shape tweening is disabled. At the end of the transition the original SVG shape element is restored.
A demo of shape tweening can be seen here.
If enable is true (default), enables panning and zooming, else disables panning and zooming. The zoom behavior is applied to the graph's top level svg element.
Returns the zoom behavior if zooming is enabled and a graph has been rendered, else returns null.
Returns the selection to which the zoom behavior has been applied if zooming is enabled and a graph has been rendered, else returns null.
# graphviz.zoomScaleExtent([extent]) <>
Sets the scale extent to the specified array of numbers [k0, k1] where k0 is the minimum allowed scale factor and k1 is the maximum allowed scale factor. The scale extent restricts zooming in and out. For details see zoom.scaleExtent.
# graphviz.zoomTranslateExtent([extent]) <>
Sets the translate extent to the specified array of points [[x0, y0], [x1, y1]], where [x0, y0] is the top-left corner of the world and [x1, y1] is the bottom-right corner of the world. The translate extent restricts panning, and may cause translation on zoom out. For details see zoom.translateExtent.
# graphviz.resetZoom([transition]) <>
Restores the original graph by resetting the transformation made by panning and zooming. If transition is specified and not null, it is taken to be a transition instance which is applied during zoom reset.
Maintaining Object Constancy
In order to achieve meaningful transitions, the D3 default join-by-index key function is not sufficient. Four different key modes are available that may be useful in different situations:
- title (default) - Uses the text of the SVG title element for each node and edge g element as generated by Graphviz. For nodes, this is "node_id" (not to be confused with the node attribute id) and for edges it is "node_id edgeop node_id", e.g. "a -> b". For node and edge sub-elements, the tag-index key mode is used, see below.
- id - Uses the id attribute of the node and edge SVG g elements as generated by Graphviz. Note that unless the graph author specifies id attributes for nodes and edges, Graphviz generates a unique internal id that is unpredictable by the graph writer, making the id key mode not very useful. For node and edge sub-elements, the tag-index key mode is used, see below.
- tag-index - Uses a key composed of the SVG element tag, followed by a dash (-) and the relative index of that element within all sibling elements with the same tag. For example: ellipse-0. Normally not very useful for other than static graphs, since all nodes and edges are siblings and are generated as SVG g elements.
- index - Uses the D3 default join-by-index key function. Not useful for other than static graphs.
Sets the key mode to the specified mode string. If mode is not one of the defined key modes above, an error is thrown. The key mode must be set before attaching the DOT source. If it is changed after this, an error is thrown.
# graphviz.attributer(function) <>
If the function is a function, it is evaluated for each SVG element, before applying attributes and transitions, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). If function is null, removes the attributer. For example, to set the fill color of ellipses to yellow and fade to red during transition:
var t = d3.transition()
.duration(2000)
.ease(d3.easeLinear);
d3.select("#graph").graphviz()
.transition(t)
.attributer(function(d) {
if (d.tag == "ellipse") {
d3.select(this)
.attr("fill", "yellow");
d.attributes.fill = "red";
}
})
.renderDot('digraph {a -> b}');
# selection.selectWithoutDataPropagation() <>
For each selected element, selects the first descendant element that matches the specified selector string in the same ways as selection.select, but does not propagate any associated data from the current element to the corresponding selected element.
Returns the data extracted by graphviz.dot or null if no such data exists.
This API provides methods draw nodes and edges and inserting them into the graph data. The application can then animate the changes made by providing and updated DOT source and render a new layout. The API also supports removing nodes and edge from the graph and the graph data.
# graphviz.drawEdge(x1, y1, x2, y2[, attributes][, options]) <>
Draws a straight edge from (x1, y1) to (x2, y2) using coordinates relative to top level G container element of the graph. Typically these coordinates are obtained with d3.mouse. If attributes is specified, it is taken to be an object containing DOT attributes as properties to be used when drawing the node. If not specified, the default values of those attributes are used. If options is specified, it is taken to be an object containing properties which are used as options when drawing the edge. The currently supported options are:
- shortening - The number of points by which to draw the edge shorter than given by the coordinates. This is useful to avoid that the currently drawn edge is prohibiting mouse events on elements beneath the current mouse position. A typical such value is 2. The default value is 0.
# graphviz.updateDrawnEdge(x1, y1, x2, y2[, attributes][, options]) <>
Updates properties and attributes of the edge currently drawn with graphviz.drawEdge, using the same arguments. This method cannot be used after the edge has been inserted into the graph data with graphviz.insertDrawnEdge.
# graphviz.moveDrawnEdgeEndPoint( x2, y2[, options]) <>
Updates the end point of the edge currently drawn with graphviz.drawEdge, accepting the same options argument. This method cannot be used after the edge has been inserted into the graph data with graphviz.insertDrawnEdge.
# graphviz.insertDrawnEdge(name) <>
Inserts the edge into the graph data, making it available for an animated transition into a subsequent new layout perfomed with graphviz.render or graphviz.renderDot. name is typically node_id edgeop node_id according to the DOT language, e.g. "a -> b".
# graphviz.removeDrawnEdge() <>
Removes the edge currently drawn with graphviz.drawEdge. This method cannot be used after the edge has been inserted into the graph data with graphviz.insertDrawnEdge.
# graphviz.drawNode(x, y, nodeId[, attributes]) <>
Draws a node with the upper left corner of its bounding box at (x, y), using coordinates relative to the top level G container element of the graph. Typically these coordinates are obtained with d3.mouse. nodeId is the node_id according to the DOT language. If attributes is specified, it is taken to be an object containing DOT attributes as properties to be used when drawing the node. If not specified, the default values of those attributes are used.
NOTE: User-defined shapes are not supported.
# graphviz.updateDrawnNode(x, y, nodeId[, attributes]) <>
Updates properties and attributes of the node currently drawn with graphviz.drawNode, using the same arguments. This method cannot be used after the node has been inserted into the graph data with graphviz.insertDrawnNode.
# graphviz.moveDrawnNode( x, y[, options]) <>
Updates the position of the upper left corner of the node currently drawn with graphviz.drawNode, accepting the same options argument. This method cannot be used after the node has been inserted into the graph data with graphviz.insertDrawnNode.
# graphviz.insertDrawnNode(nodeId) <>
Inserts the node into the graph data, making it available for an animated transition into a subsequent new layout performed with graphviz.render or graphviz.renderDot. nodeId is the node_id according to the DOT language.
# graphviz.removeDrawnNode() <>
Removes the node currently drawn with graphviz.drawNode. This method cannot be used after the node has been inserted into the graph data with graphviz.insertDrawnNode.
# graphviz.drawnNodeSelection() <>
Returns a selection containing the node currently being drawn. The selection is empty if no node has been drawn or the last drawn node has been inserted into the graph data with graphviz.insertDrawnNode.
Removes the Graphviz renderer from the element it was created on, terminates any active dedicated web worker and closes any port connected to a shared web worker.
There are plenty of examples in the examples folder. To see them in action you must build the library and start a web server. You cannot just open them through file:
in your browser. Here is one way to do it:
git clone https://github.com/magjac/d3-graphviz.git
cd d3-graphviz
npm install
npm run build
npm install http-server
node_modules/.bin/http-server .
There are also a few examples directly available online:
- Basic Example
- Demo
- Shape Tweening Demo
- Delete Nodes and Edge Demo Application
- Animated Growth of Entering Edges Demo
Building Applications with d3-graphviz
The generated SVG graph has exactly the same structure as the SVG generated by @hpcc-js/wasm, so applications utilizing knowledge about this structure should be able to use d3-graphviz without adaptations. If path tweening or shape tweening is used, some SVG elements may be converted during transitions, but they are restored to the original shape after the transition.
See this example application.
NOTE: avoid selection.select
When selecting elements within the graph, selection.select must not be used if additional rendering is going to be performed on the same graph renderer instance. This is due to the fact that selection.select propagates data from the elements in the selection to the corresponding selected elements, causing already bound data to be overwritten with incorrect data and subsequent errors. Use the selection.selectWithoutDataPropagation() (a d3-graphviz extension of d3-selection) or selection.selectAll, which do not propagate data or selection.node and querySelector. For example, to select the first g element within the first svg element within a specified div element:
var div = d3.select("#graph");
var svg = d3.select(div.node().querySelector("svg"));
var g = d3.select(svg.node().querySelector("g"));
For more, read this issue and this Stack Overflow post.
The data bound to each DOM node is an object containing the following fields:
- tag - The DOM node tag.
- attributes - An object containing attributes as properties.
- children - An array of data for the node's children.
- key - The key used when binding data to nodes with the key function. See graphviz.keyMode for more.
- text - Contains the text if the DOM node is a Text node. A text node has the tag "#text", not to be confused with the tag "text", which is an SVG 'text' element.
- comment - Contains the comment if the DOM node is a Comment node. A comment node has the tag "#comment".
Other fields are used internally, but may be subject to change between releases and should not be used by an external application.
To inspect data:
d3.select("#graph").graphviz()
.renderDot('digraph {a -> b}');
console.log(JSON.stringify(d3.select("svg").datum(), null, 4));
The shape- and path-tweening operations are quite computational intensive and can be disabled with graphviz.tweenShapes and graphviz.tweenPaths to improve performance if they are not needed. Even if enabled, performance gains can be made by turning off conversion of equally sided polygons with graphviz.convertEqualSidedPolygons or by reducing tween precision by setting a larger value with graphviz.tweenPrecision.
In order for animated transitions to be smooth, special considerations has been made to do the computational intensive operations before transitions start.
d3-graphviz transpiles the production build to ES5 before publishing it on npm, so it should be possible to use it with most build tools and browsers.
When asking for help, please include a link to a live example that demonstrates the issue, preferably on JSFiddle. It is often impossible to debug from code snippets alone. Isolate the issue and reduce your code as much as possible before asking for help. The less code you post, the easier it is for someone to debug, and the more likely you are to get a helpful response.
By clicking the Watch button, you will stay tuned for updates to the library.
-
For specific questions, please use Stack Overflow tags d3.js & graphviz.
-
For general discussions regarding d3-graphviz, please use the Graphviz forum.
If you think you have found a bug in d3-graphviz itself, please file an issue.
In order to run the tests you need Node.js 14.x or later. Version 18.8.0 was used during development.
- Gordon Smith for @hpcc-js/wasm.
- Mike Bostock for the Path Tween code and Stroke Dash Interpolation code.
- Aaron Bycoffe for the Element rotation with point-along-path interpolation code.
- Marcin Stefaniuk for inspiration and learning through graph-viz-d3-js.
- Ueyama Satoshi for inspiring growing edges through livizjs.