GraphViz(3)
π GraphViz(3) π
okay so this is the GraphViz(3) page from User Contributed Perl Documentation β vintage Perl manual energy, but make it bestie-friendly. π«Ά
πΈ NAME πΈ
GraphViz β interface to AT&T's GraphViz. Deprecated. See GraphViz2.
β¨ SYNOPSIS β¨
use GraphViz;
my $g = GraphViz->new();
$g->add_node('London');
$g->add_node('Paris', label => 'City of\nlurve');
$g->add_node('New York');
$g->add_edge('London' => 'Paris');
$g->add_edge('London' => 'New York', label => 'Far');
$g->add_edge('Paris' => 'London');
print $g->as_png;
π DESCRIPTION π
This module provides an interface to layout and image generation of directed and undirected graphs in a variety of formats (PostScript, PNG, etc.) using the "dot", "neato", "twopi", "circo" and "fdp" programs from the Graphviz project (http://www.graphviz.org/ or http://www.research.att.com/sw/tools/graphviz/). β¨
π¨ Deprecated alert: GraphViz is deprecated in favour of GraphViz2. no cap, that's the whole vibe check.
π οΈ Installation π οΈ
Of course you need to install AT&T's Graphviz before using this module. See <http://www.graphviz.org/Download.php>. π
You are strongly advised to download the stable version of Graphviz, because the development snapshots (click on 'Source code'), are sometimes non-functional. π
Install GraphViz as you would for any Perl module:
Run:
cpanm GraphViz
Note:cpanmships inApp::cpanminus. See alsoApp::perlbrew.
or run:
sudo cpan GraphViz
or unpack the distro, and then either:
perl Build.PL
./Build
./Build test
sudo ./Build install
or:
perl Makefile.PL
make (or dmake or nmake)
make test
make install
π«Ά Overview π«Ά
π Modules in this distro π
GraphVizGraphViz::NoGraphViz::SmallGraphViz::RegexGraphViz::XMLGraphViz::Data::GrapherGraphViz::Parse::RecDescentGraphViz::Parse::YaccGraphViz::Parse::Yapp
π§ What is a graph? π§
A (undirected) graph is a collection of nodes linked together with edges. π¦
A directed graph is the same as a graph, but the edges have a direction. β‘οΈ
πͺ What is GraphViz? πͺ
This module is an interface to the GraphViz toolset (http://www.graphviz.org/). The GraphViz tools provide automatic graph layout and drawing. This module simplifies the creation of graphs and hides some of the complexity of the GraphViz module. β¨
Laying out graphs in an aesthetically-pleasing way is a hard problem - there may be multiple ways to lay out the same graph, each with their own quirks. GraphViz luckily takes part of this hard problem and does a pretty good job in a couple of seconds for most graphs. π
π‘ Why should I use this module? π‘
Observation aids comprehension. That is a fancy way of expressing that popular faux-Chinese proverb: "a picture is worth a thousand words". πΌοΈ
Text is not always the best way to represent anything and everything to do with a computer programs. Pictures and images are easier to assimilate than text. The ability to show a particular thing graphically can aid a great deal in comprehending what that thing really represents. π
Diagrams are computationally efficient, because information can be indexed by location; they group related information in the same area. They also allow relations to be expressed between elements without labeling the elements. π₯
A friend of mine used this to his advantage when trying to remember important dates in computer history. Instead of sitting down and trying to remember everything, he printed over a hundred posters (each with a date and event) and plastered these throughout his house. His spatial memory is still so good that asked last week (more than a year since the experiment) when Lisp was invented, he replied that it was upstairs, around the corner from the toilet, so must have been around 1958. π
Spreadsheets are also a wonderfully simple graphical representation of computational models. π
π¨ Applications π¨
Bundled with this module are several modules to help graph data structures (GraphViz::Data::Dumper), XML (GraphViz::XML), and Parse::RecDescent, Parse::Yapp, and yacc grammars (GraphViz::Parse::RecDescent, GraphViz::Parse::Yapp, and GraphViz::Parse::Yacc). π«Ά
Note that Marcel Grunauer has released some modules on CPAN to graph various other structures. See GraphViz::DBI and GraphViz::ISA for example. π
brian d foy has written an article about Devel::GraphVizProf for Dr. Dobb's Journal: http://www.ddj.com/columns/perl/2001/0104pl002/0104pl002.htm. π
π Award winning! π
I presented a paper and talk on "Graphing Perl" using GraphViz at the 3rd German Perl Workshop and received the "Best Knowledge Transfer" prize. π₯
- Talk:
http://www.astray.com/graphing_perl/graphing_perl.pdf - Slides:
http://www.astray.com/graphing_perl/
π METHODS π
π new π
This is the constructor. It accepts several attributes. β¨
my $g = GraphViz->new();
my $g = GraphViz->new(directed => 0);
my $g = GraphViz->new(layout => 'neato', ratio => 'compress');
my $g = GraphViz->new(rankdir => 'BT');
my $g = GraphViz->new(width => 8.5, height => 11);
my $g = GraphViz->new(width => 30, height => 20,
pagewidth => 8.5, pageheight => 11);
The two most important attributes are 'layout' and 'directed'. π
π§ layout π§
The 'layout' attribute determines which layout algorithm GraphViz.pm will use. Possible values are:
dotβ the default GraphViz layout for directed graph layouts.neatoβ for undirected graph layouts β spring model.twopiβ for undirected graph layouts β radial.circoβ for undirected graph layouts β circular.fdpβ for undirected graph layouts β force directed spring model.
π― directed π―
The 'directed' attribute, which defaults to 1 (true), specifies directed (edges have arrows) graphs. Setting this to zero produces undirected graphs (edges do not have arrows). β‘οΈ
π§ rankdir π§
Another attribute 'rankdir' controls the direction in which the nodes are linked together. The default is 'TB' (arrows from top to bottom). Other legal values are 'BT' (bottom->top), 'LR' (left->right) and 'RL' (right->left). π
π width, height π
The 'width' and 'height' attributes control the size of the bounding box of the drawing in inches. This is more useful for PostScript output as for raster graphic (such as PNG) the pixel dimensions can not be set, although there are generally 96 pixels per inch. πΌοΈ
π pagewidth, pageheight π
The 'pagewidth' and 'pageheight' attributes set the PostScript pagination size in inches. That is, if the image is larger than the page then the resulting PostScript image is a sequence of pages that can be tiled or assembled into a mosaic of the full image. (This only works for PostScript output). π§©
πͺοΈ concentrate πͺοΈ
The 'concentrate' attribute controls an edge merging technique to reduce clutter in dense layouts of directed graphs. The default is not to merge edges. π
π orientation π
This option controls the angle, in degrees, used to rotate polygon node shapes. π
π² random_start π²
For undirected graphs, the 'random_start' attribute requests an initial random placement for the graph, which may give a better result. The default is not random. π²
ποΈ epsilon ποΈ
For undirected graphs, the 'epsilon' attribute decides how long the graph solver tries before finding a graph layout. Lower numbers allow the solver to run longer and potentially give a better layout. Larger values can decrease the running time but with a reduction in layout quality. The default is 0.1. β³
π«§ overlap π«§
The 'overlap' option allows you to set layout behavior for graph nodes that overlap. (From GraphViz documentation:) β¨
Determines if and how node overlaps should be removed. π«Ά
trueβ (the default) overlaps are retained.scaleβ overlaps are removed by uniformly scaling in x and y.falseβ If the value converts to "false", node overlaps are removed by a Voronoi-based technique.scalexyβ x and y are separately scaled to remove overlaps.orthoxy,orthxyβ If the value is "orthoxy" or "orthoyx", overlaps are moved by optimizing two constraint problems, one for the x axis and one for the y. The suffix indicates which axis is processed first.
β οΈ NOTE: The methods related to "orthoxy" and "orthoyx" are still evolving. The semantics of these may change, or these methods may disappear altogether. π
compressβ If the value is "compress", the layout will be scaled down as much as possible without introducing any overlaps.
Except for the Voronoi method, all of these transforms preserve the orthogonal ordering of the original layout. That is, if the x coordinates of two nodes are originally the same, they will remain the same, and if the x coordinate of one node is originally less than the x coordinate of another, this relation will still hold in the transformed layout. The similar properties hold for the y coordinates. π§
π« no_overlap π«
The 'no_overlap' overlap option, if set, tells the graph solver to not overlap the nodes. Deprecated, Use 'overlap' => 'false'. π¨
π ratio π
The 'ratio' option sets the aspect ratio (drawing height/drawing width) for the drawing. Note that this is adjusted before the size attribute constraints are enforced. Default value is "fill". π
- numeric β If ratio is numeric, it is taken as the desired aspect ratio. Then, if the actual aspect ratio is less than the desired ratio, the drawing height is scaled up to achieve the desired ratio; if the actual ratio is greater than that desired ratio, the drawing width is scaled up.
fillβ If ratio ="fill"and the size attribute is set, node positions are scaled, separately in both x and y, so that the final drawing exactly fills the specified size.compressβ If ratio ="compress"and the size attribute is set, dot attempts to compress the initial layout to fit in the given size. This achieves a tighter packing of nodes but reduces the balance and symmetry. This feature only works in dot.expandβ If ratio ="expand"the size attribute is set, and both the width and the height of the graph are less than the value in size, node positions are scaled uniformly until at least one dimension fits size exactly. Note that this is distinct from using size as the desired size, as here the drawing is expanded before edges are generated and all node and text sizes remain unchanged.autoβ ok so ifratio = "auto", the page attribute is set, and the graph can't be drawn on a single page, thensizegets set to an "ideal" value π specifically, the size in a given dimension is the smallest integral multiple of the page size in that dimension that's at least half the current size β¨ and then the two dimensions get scaled independently to that new size. Heads up tho: this feature only works indotπbgcolorβ sets the background colour π a colour value can be"h,s,v"(hue, saturation, brightness) floating point numbers between 0 and 1, or an X11 color name like'white','black','red','green','blue','yellow','magenta','cyan', or'burlywood'π¨nameβ sets the name of the graph. useful in like, a few situations β client side image map generation, for example, seecmapxπ by default'test'is used.node,edge,graphβ these let you specify global node, edge and graph attributes (on top of the ones controlled by the special attributes we just covered, iykyk). the value should be a hash reference holding the corresponding key-value pairs π for example, to make all nodes box-shaped (unless explicitly given another shape):
my $g = GraphViz->new(node => {shape => 'box'});
β¨ add_node β¨
a graph consists of at least one node π«Ά all nodes have a name attached that uniquely represents that node.
the add_node method creates a new node and optionally assigns it attributes β¨
the simplest form hits when no attributes are required β the string is literally the name of the node:
$g->add_node('Paris');
attributes, bestie π
various attributes are possible: "label" gives the node a label (the label defaults to the name if none is specified) π·οΈ the label can contain embedded newlines with '\n', plus '\c', '\l', '\r' for center, left, and right justified lines:
$g->add_node('Paris', label => 'City of\nlurve');
and the way that attributes don't all have to be specified in one line is so iconic β successive declarations of the same node have a cumulative effect, like, any later attributes just get added to the existing ones πΈ for example, these two lines are equivalent to the one above:
$g->add_node('Paris');
$g->add_node('Paris', label => 'City of\nlurve');
note that multiple attributes can be specified π₯ other attributes include:
height,widthβ sets the minimum height or width πshapeβ sets the node shape. can be one of:'record','plaintext','ellipse','circle','egg','triangle','box','diamond','trapezium','parallelogram','house','hexagon','octagon'π·fontsizeβ sets the label size in points π€fontnameβ sets the label font family name βοΈcolorβ sets the outline colour, and the default fill colour if the'style'is'filled'and'fillcolor'is not specified π¨ a colour value can be"h,s,v"(hue, saturation, brightness) floating point numbers between 0 and 1, or an X11 color name such as'white','black','red','green','blue','yellow','magenta','cyan', or'burlywood'fillcolorβ sets the fill colour when the style is'filled'. if not specified, the'fillcolor'when the'style'is'filled'defaults to being the same as the outline color πstyleβ sets the style of the node. can be one of:'filled','solid','dashed','dotted','bold','invis'β¨URLβ sets the url for the node in image map and PostScript files. the string'\N'value gets replaced by the node name π in PostScript files, URL info is embedded in such a way that Acrobat Distiller creates PDF files with active hyperlinks π
anonymous nodes π
if you wanna add an anonymous node β meaning a node you don't wanna generate a name for β you can use the following form, where the GraphViz module generates a name and returns it to you π«Ά then you can use that name later to refer to this node:
my $nodename = $g->add_node('label' => 'Roman city');
clusters π
nodes can be clustered together with the "cluster" attribute, which is drawn by having a labelled rectangle around all the nodes in a cluster πΈ an empty string means not clustered.
$g->add_node('London', cluster => 'Europe');
$g->add_node('Amsterdam', cluster => 'Europe');
clusters can also take a hashref so you can set attributes π
my $eurocluster = {
name =>'Europe',
style =>'filled',
fillcolor =>'lightgray',
fontname =>'arial',
fontsize =>'12',
};
$g->add_node('London', cluster => $eurocluster, @default_attrs);
ranks π
nodes can be located in the same rank (so, at the same level in the graph) with the "rank" attribute π nodes with the same rank value get ranked together.
$g->add_node('Paris', rank => 'top');
$g->add_node('Boston', rank => 'top');
ports π¦
also, nodes can consist of multiple parts (known as ports) β¨ this is implemented by passing an array reference as the label, and the parts get displayed as a label. GraphViz has a much more complete port system β this is just a simple interface to it π«Ά see the 'from_port' and 'to_port' attributes of add_edge:
$g->add_node('London', label => ['Heathrow', 'Gatwick']);
β¨ add_edge β¨
edges are directed (or undirected) links between nodes π this method creates a new edge between two nodes and optionally assigns it attributes.
the simplest form is when no attributes are required, in which case you just specify the nodes the edge should go from and to π₯ this works so well visually in the program code:
$g->add_edge('London' => 'Paris');
attributes such as 'label' can also be used β this specifies a label for the edge π·οΈ the label can contain embedded newlines with '\n', plus '\c', '\l', '\r' for center, left, and right justified lines.
$g->add_edge('London' => 'New York', label => 'Far');
note that multiple attributes can be specified β¨ other attributes include:
minlenβ sets an integer factor that applies to the edge length (ranks for normal edges, or minimum node separation for flat edges) πweightβ sets the integer cost of the edge. values greater than 1 tend to shorten the edge. weight 0 flat edges are ignored for ordering nodes βοΈfontsizeβ sets the label type size in points π€fontnameβ sets the label font family name βοΈfontcolorβ sets the label text colour π¨colorβ sets the line colour for the edge π a colour value can be"h,s,v"(hue, saturation, brightness) floating point numbers between 0 and 1, or an X11 color name such as'white','black','red','green','blue','yellow','magenta','cyan', or'burlywood'styleβ sets the style of the node. can be one of:'filled','solid','dashed','dotted','bold','invis'β¨dirβ sets the arrow direction. can be one of:'forward','back','both','none'πΉtailclip,headclipβ when set to false, disables endpoint shape clipping βοΈarrowhead,arrowtailβ sets the type for the arrow head or tail. can be one of:'none','normal','inv','dot','odot','invdot','invodot.'π―arrowsizeβ sets the arrow size:(norm_length=10,norm_width=5, inv_length=6,inv_width=7,dot_radius=2)πheadlabel,taillabelβ sets the text for port labels. note thatlabelfontcolor,labelfontname,labelfontsizeare also allowed π¬labeldistance,port_label_distanceβ sets the distance from the edge / port to the label. alsolabelangleπdecorateβ if set, draws a line from the edge to the label ποΈsamehead,sametailβ if set, aim edges having the same value to the same port, using the average landing point π―constraintβ if set to false, causes an edge to be ignored for rank assignment π«
additionally, adding edges between ports of a node is done via the 'from_port' and 'to_port' parameters, which currently take in the offset of the port (ie 0, 1, 2...) π«Ά
$g->add_edge('London' => 'Paris', from_port => 0);
β¨ as_canon, as_text, as_gif etc. methods β¨
there are a number of methods that generate input for dot / neato / twopi / circo / fdp, or output the graph in a variety of formats π₯
so here's the vibe check on how output goes π if you pass a filename, the data is written to that filename. if you pass a filehandle, the data gets streamed to the filehandle. if you pass a scalar reference, then the data gets stored in that scalar. if you pass it a code reference, then it's called with the data (heads up: the coderef may be called multiple times if the image is large π). otherwise, the data is returned:
my $png_image = $g->as_png;
# or
$g->as_png("pretty.png"); # save image
# or
$g->as_png(\*STDOUT); # stream image to a filehandle
# or
#g->as_png(\$text); # save data in a scalar
# or
$g->as_png(sub { $png_image .= shift });
π Win32 note: you will probably want to binmode any filehandles you write the output to, if you want your application to be portable to Win32 π
as_debugβ theas_debugmethod returns the dot file which we pass to GraphViz. it does not lay out the graph. mostly useful for debugging π
print $g->as_debug;
as_canonβ theas_canonmethod returns the canonicaldot/neato/twopi/circo/fdpfile which corresponds to the graph. it does not layout the graph β every otheras_*method does πΈ
print $g->as_canon;
# prints out something like:
digraph test {
node [ label = "\N" ];
London [label=London];
Paris [label="City of\nlurve"];
New_York [label="New York"];
London -> Paris;
London -> New_York [label=Far];
Paris -> London;
}
as_textβ theas_textmethod returns text which is a layed-outdot/neato/twopi/circo/fdpformat file β¨
print $g->as_text;
# prints out something like:
digraph test {
node [ label = "\N" ];
graph [bb= "0,0,162,134"];
London [label=London, pos="33,116", width="0.89", height="0.50"];
Paris [label="City of\nlurve", pos="33,23", width="0.92", height="0.62"];
New_York [label="New York", pos="123,23", width="1.08", height="0.50"];
London -> Paris [pos="e,27,45 28,98 26,86 26,70 27,55"];
London -> New_York [label=Far, pos="e,107,40 49,100 63,85 84,63 101,46", lp="99,72"];
Paris -> London [pos="s,38,98 39,92 40,78 40,60 39,45"];
}
as_psβ returns a string containing a layed-out PostScript-format file π
print $g->as_ps;
as_hpgl
okay so this one hands you back a string with a layed-out HP pen plotter-format file inside. plotter girlies rise π¨οΈβ¨
print $g->as_hpgl;
as_pcl
returns a string holding a layed-out Laserjet printer-format file. printer moment fr fr π¨οΈπ
print $g->as_pcl;
as_mif
gives you a string with a layed-out FrameMaker graphics-format file in it. vintage graphics behavior π
print $g->as_mif;
as_pic
string o'clock, and inside is a layed-out PIC-format file. cute little diagram format, no cap β¨
print $g->as_pic;
as_gd
returns a string containing a layed-out GD-format file. very demure, very graphics-library π
print $g->as_gd;
as_gd2
same energy but the file inside the string is layed-out GD2-format. she upgraded π
print $g->as_gd2;
as_gif
hands back a string with a layed-out GIF-format file inside. animated icon behavior π
print $g->as_gif;
as_jpeg
string with a layed-out JPEG-format file. jpeg bestie is here πΈ
print $g->as_jpeg;
as_png
returns a string with a layed-out PNG-format file inside β and yes, you can also pass a filename to save the image. png slay π
print $g->as_png;
$g->as_png("pretty.png"); # save image
as_wbmp
gives you a string with a layed-out Windows BMP-format file in it. windows graphic realness πͺ
print $g->as_wbmp;
as_cmap β deprecated π
this one is deprecated, so it's giving legacy energy. it returns a string containing a layed-out HTML client-side image map format file. use as_cmapx instead, bestie.
print $g->as_cmap;
as_cmapx
returns a string with a layed-out HTML HTML/X client-side image map format file. yes, the double βHTMLβ is in the original π. the Name and id attributes of the map element are set to the name of the graph. iconic map behavior β¨
print $g->as_cmapx;
as_ismap β deprecated π
deprecated alert! it returns a string with a layed-out old-style server-side image map format file. use as_imap instead. periodt.
print $g->as_ismap;
as_imap
returns a string containing a layed-out HTML new-style server-side image map format file. server-side map girlie π
print $g->as_imap;
as_vdx
gives you a string with a VDX-format (Microsoft Visio) file inside. visio vibe check π
print $g->as_vdx;
as_vrml
returns a string with a layed-out VRML-format file inside. 3D-ish energy, lowkey iconic π¦
print $g->as_vrml;
as_vtx
hands back a string containing a layed-out VTX (Visual Thought) format file. visual thought moment π§
print $g->as_vtx;
as_mp
returns a string with a layed-out MetaPost-format file inside. metapost bestie π
print $g->as_mp;
as_fig
gives you a string containing a layed-out FIG-format file. fig format, not the fruit, but still cute π
print $g->as_fig;
as_svg
returns a string with a layed-out SVG-format file inside. vector icon behavior β¨
print $g->as_svg;
as_svgz
returns a string with a layed-out SVG-format file that is compressed. tiny zipped vector cutie π
print $g->as_svgz;
as_plain
hands back a string with a layed-out simple-format file inside. plain but never boring, iykyk π
print $g->as_plain;
π¦ FAQ π¦
Why do I get error messages like the following?
Error: <stdin>:1: syntax error near line 1
context: digraph >>> Graph <<< {
Graphviz reserves some words as keywords, meaning they can't be used as an ID β like for the name of the graph. so don't do this, bestie:
strict graph graph{...}
strict graph Graph{...}
strict graph strict{...}
etc...
Likewise for non-strict graphs, and digraphs. you can however add double-quotes around such reserved words:
strict graph "graph"{...}
Even better, use a more meaningful name for your graph...
The keywords are: node, edge, graph, digraph, subgraph and strict. Compass points are not keywords.
See keywords http://www.graphviz.org/content/dot-language in the discussion of the syntax of DOT for details.
How do you handle XXE within XML?
Due to security risks with XXE in XML, Graphviz does not support XML that contains XXE. Thus it automatically prevents external entities being parsed by using the no_xxe option in XML::Twig when calling XML::Twig -> new(). And for this reason also the pre-reqs in Makefile.PL specify XML::Twig V 3.52.
See https://metacpan.org/pod/release/MIROD/XML-Twig-3.52/Twig.pm#no_xxe
πΈ NOTES πΈ
Older versions of GraphViz used a slightly different syntax for node and edge adding (with hash references). The new format is slightly clearer, although for the moment we support both. Use the new, clear syntax, please. bestie please ππ
π SEE ALSO π
GraphViz is deprecated in favour of GraphViz2. keep that in mind, bestie π«Ά
π Machine-Readable Change Log π
The file Changes was converted into Changelog.ini by Module::Metadata::Changes.
π Repository π
https://github.com/ronsavage/GraphViz
π AUTHOR π
Leon Brocard: <acme@astray.com>.
Current maintainer: Ron Savage <ron@savage.net.au>.
My homepage: <http://savage.net.au/>.
π COPYRIGHT π
Copyright (C) 2000-4, Leon Brocard
π LICENSE π
This module is free software; you can redistribute it or modify it under the Perl License, a copy of which is available at <http://dev.perl.org/licenses/>.
π
and that's the whole GraphViz(3) page, bestie β source/version perl v5.42.0, dated 2023-03-04. periodt. πβ¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-GraphViz 2.26-bp160.1.11 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms