graph_draw#
- graph_tool.draw.graph_draw(g, pos=None, vprops=None, eprops=None, vorder=None, eorder=None, nodesfirst=False, output_size=(600, 600), fit_view=True, fit_view_ink=None, adjust_aspect=True, ink_scale=1, inline=False, inline_scale=2, mplfig=None, yflip=True, output=None, fmt='auto', bg_color=None, antialias=None, raster_resolution=300, **kwargs)[git][source]#
Draw a graph to screen or to a file using cairo.
- Parameters:
- g
Graph Graph to be drawn.
- pos
VertexPropertyMap(optional, default:None) Vector-valued vertex property map containing the x and y coordinates of the vertices. If not given, it will be computed using
hfd_layout().- vpropsdict (optional, default:
None) Dictionary with the vertex properties. Individual properties may also be given via the
vertex_<prop-name>parameters, where<prop-name>is the name of the property.- epropsdict (optional, default:
None) Dictionary with the edge properties. Individual properties may also be given via the
edge_<prop-name>parameters, where<prop-name>is the name of the property.- vorder
VertexPropertyMap(optional, default:None) If provided, defines the relative order in which the vertices are drawn.
- eorder
EdgePropertyMap(optional, default:None) If provided, defines the relative order in which the edges are drawn.
- nodesfirstbool (optional, default:
False) If
True, the vertices are drawn first, otherwise the edges are.- output_sizetuple of scalars (optional, default:
(600,600)) Size of the drawing canvas. The units will depend on the output format (pixels for the screen, points for PDF, etc).
- fit_viewbool, float, or tuple (optional, default:
True) If
True, the layout will be scaled to fit the entire clip region. If a float value is given, it will be interpreted asTrue, and in addition the viewport will be scaled out by that factor. If a tuple value is given, it should have four values(x, y, w, h)that specify the view in user coordinates. This option is ignored ifmplfigis given, in which case the axis limits are set bymatplotlib’s autoscaling, or by callingfit_view()on the returned object.- fit_view_inkbool (optional, default:
None) If
True, andfit_view == Truethe drawing will be performed once to figure out the bounding box, before the actual drawing is made. Otherwise, only the vertex positions will be used for this purpose. If the value isNone, then it will be assumedTruefor networks of size 1,000 nodes or less, otherwise it will be assumedFalse.- adjust_aspectbool (optional, default:
True) If
True, andfit_view == Truethe output size will be decreased in the width or height to remove empty spaces.- ink_scalefloat (optional, default:
1.) Scale all sizes and widths by this factor.
- inlinebool (optional, default:
has_draw_inline) If
Trueand an IPython notebook is being used, an inline version of the drawing will be returned. By default, this isTrueonly if an inlinematplotlibbackend is active.- inline_scalefloat (optional, default:
2.) Resolution scaling factor for inline images.
- mplfig
matplotlibcontainer object (optional, default:None) The
mplfigobject needs to have anadd_artist()function. This can for example be amatplotlib.figure.Figureormatplotlib.axes.Axes. Only the cairo backend is supported; useswitch_backend('cairo'). If this option is used, aGraphArtistobject is returned.- yflipbool (optional, default:
True) If
Trueandmplfigis given, the y axis of thematplotlibaxes will be inverted (if it is not already), which reproduces the orientation of the output whenmplfig is None. The axis limits can then be set withfit_view(), which also sets the direction of the y axis.- outputstring or file object (optional, default:
None) Output file name (or object). If not given, the graph will be displayed via
interactive_window().- fmtstring (optional, default:
"auto") Output file format. Possible values are
"auto","ps","eps","pdf","svg", and"png". If the value is"auto", the format is guessed from theoutputparameter.- bg_colorstr or sequence (optional, default:
None) Background color. The default is transparent.
- antialias
cairo.Antialias(optional, default:None) If supplied, this will set the antialiasing mode of the cairo context.
- raster_resolutionfloat (optional, default:
300) Resolution, in pixels per inch, of the raster images embedded in vector output (PDF, PostScript, EPS, and SVG): the gradients along curved edges with
edge_gradient_render == "raster"(or"native"in SVG and PostScript), and the parts that cairo itself rasterizes. It is the fallback resolution of the cairo surface (seecairo.Surface.set_fallback_resolution()), whose default is the same. The images of the gradients are limited to 8192 pixels along each side, beyond which their resolution is reduced. Withmplfig, the fallback resolution of the surface of matplotlib is used instead.- resfloat (optional, default:
2.) If both endpoints of an edge are smaller than this size (in units of the output format, normally pixels or points), the edge is drawn as if
edge_sloppy == True; likewise,edge_seamlessis ignored for markers smaller than this size. This speeds up the drawing of large networks considerably, with hardly any visible difference. This default only applies whenoutputis given; for the interactive window, the value is5pixels.- size_units
"output"or"layout"(optional, default:"output") Units of the vertex and edge sizes (vertex and marker sizes, pen widths, font sizes, text distances and offsets, dash patterns). If
"output", they are in units of the output format (normally pixels or points), so that they do not depend on the extent of the layout or the zoom level. If"layout", they are in the same units as the positions, so that they scale with the drawing; in this case the default sizes are computed from the extent of the layout, rather than fromoutput_size, and in the interactive window the sizes follow the zoom. The value ofresis always in output units.- vertex_*
VertexPropertyMapor arbitrary types (optional, default:None) Parameters following the pattern
vertex_<prop-name>specify the vertex property with name<prop-name>, as an alternative to thevpropsparameter.- edge_*
EdgePropertyMapor arbitrary types (optional, default:None) Parameters following the pattern
edge_<prop-name>specify the edge property with name<prop-name>, as an alternative to theepropsparameter.- **kwargs
Any extra parameters are passed to
interactive_window(),GraphWindow,GraphWidget, andcairo_draw().
- g
- Returns:
- pos
VertexPropertyMap Vector vertex property map with the x and y coordinates of the vertices.
- selected
VertexPropertyMap(optional, only ifoutput is None) Boolean-valued vertex property map marking the vertices which were selected interactively.
- pos
See also
cairo_drawDraw a graph to a Cairo context
draw_hierarchyDraw a nested block model hierarchy
interactive_windowInteractive window for drawing a graph
sfdp_layoutMultilevel force-directed layout
Notes
List of vertex properties
Name
Description
Accepted types
Default Value
shape
The vertex shape. Can be one of the following strings: “circle”, “triangle”, “square”, “pentagon”, “hexagon”, “heptagon”, “octagon”, “double_circle”, “double_triangle”, “double_square”, “double_pentagon”, “double_hexagon”, “double_heptagon”, “double_octagon”, “pie”, “none”. Optionally, this might take a numeric value corresponding to position in the list above.
strorint"circle"color
Color used to stroke the lines of the vertex.
stror list offloats[0.6, 0.6, 0.6, 0.8]fill_color
Color used to fill the interior of the vertex.
stror list offloats[0.647, 0.059, 0.082, 0.8]size
The size of the vertex, in the default units of the output format (normally either pixels or points).
floatorint5aspect
The aspect ratio of the vertex.
floatorint1.0rotation
Angle (in radians) to rotate the vertex.
float0.anchor
Specifies how the edges anchor to the vertices. If 0, the anchor is at the center of the vertex, otherwise it is at the border.
int1pen_width
Width of the lines used to draw the vertex, in the default units of the output format (normally either pixels or points).
floatorint0.8halo
Whether to draw a circular halo around the vertex.
boolFalsehalo_color
Color used to draw the halo.
stror list offloats[0., 0., 1., 0.5]halo_size
Relative size of the halo.
float1.5text
Text to draw together with the vertex.
str""text_color
Color used to draw the text. If the value is
"auto", it will be black or white, whichever has the largest contrast with what is drawn behind the text: the fill color (or the pie colors) over the background for texts inside the vertex, otherwise the background (bg_color, or white if it is not given).stror list offloats"auto"text_position
Position of the text relative to the vertex. If the passed value is positive, it will correspond to an angle in radians, which will determine where the text will be placed outside the vertex. If the value is negative, the text will be placed inside the vertex. If the value is
-1, the vertex size will be automatically increased to accommodate the text. The special value"centered"positions the texts rotated radially around the center of mass.floatorintor
"centered"
-1text_offset
Text position offset, in the units given by
size_units.list of
float[0.0, 0.0]text_rotation
Angle of rotation (in radians) for the text. The center of rotation is the position of the vertex.
float0.0text_out_color
Color used to draw the text outline.
stror list offloats[0,0,0,0]text_out_width
Width of the text outline, which is drawn around the glyphs (only visible if
text_out_coloris not transparent).float1.font_family
Font family used to draw the text.
str"serif"font_slant
Font slant used to draw the text.
cairo.FONT_SLANT_*font_weight
Font weight used to draw the text.
cairo.FONT_WEIGHT_*font_size
Font size used to draw the text.
floatorint12surface
The cairo surface used to draw the vertex. If the value passed is a string, it is interpreted as an image file name to be loaded.
cairo.SurfaceorstrNonepie_fractions
Fractions of the pie sections for the vertices if
shape=="pie".list of
intorfloat[0.75, 0.25]pie_colors
Colors used in the pie sections if
shape=="pie".list of strings or
float.First 10 colors of
default_cmzorder
Order in which the vertex is drawn, relative to all vertices and edges: the ones with larger values are drawn on top. Ties are drawn in the order given by
nodesfirst,vorder, andeorder.float0text_zorder
If given, the text of the vertex is drawn separately from it, with this z-order (see
zorder). For instance, a large value draws it on top of all vertices and edges. Ifnan, the text is drawn together with the vertex.floatnanList of edge properties
Name
Description
Accepted types
Default Value
color
Color used to stroke the edge lines.
stror list of floats[0.179, 0.203, 0.210, 0.8]pen_width
Width of the line used to draw the edge, in the default units of the output format (normally either pixels or points).
floatorint1.0start_marker, mid_marker, end_marker
Edge markers. Can be one of “none”, “arrow”, “circle”, “square”, “diamond”, or “bar”. Optionally, this might take a numeric value corresponding to position in the list above.
strorintnonemid_marker_pos
Relative position of the middle marker.
float0.5marker_size
Size of edge markers, in units appropriate to the output format (normally either pixels or points).
floatorint4control_points
Control points of a Bézier spline used to draw the edge. Each spline segment requires 6 values corresponding to the (x,y) coordinates of the two intermediary control points and the final point.
sequence of
floats[]gradient
Stop points of a color gradient used to stroke the edge. Each group of 5 elements is interpreted as
[o, r, g, b, a]whereois the offset in the range [0, 1] and the remaining values specify the colors. The offsets go from the source to the target, and they are interpreted as given bygradient_type.sequence of
floats[]gradient_type
How the offsets of the gradient are interpreted: with
"path", they are fractions of the length along the edge, also for curved edges; with"linear", they are fractions of the distance between the end points, as in a linear gradient between them, which follows the path only for straight edges (for which both values are equivalent).strorint"path"gradient_render
How a
"path"gradient along a curved edge is rendered. It has no effect for straight edges and"linear"gradients, which are always drawn as a linear gradient, a vector pattern in every format (including SVG and PostScript, also with"native"). With"mesh", the gradient is a mesh pattern, which is exact and independent of the resolution, but makes PDF files larger (about 3 times for the edges ofdraw_hierarchy()); it is not supported in SVG output, which has no displayable mesh patterns (aValueErroris raised), and cairo renders translucent mesh patterns incorrectly in PostScript. With"raster", it is an image of the mesh at the resolution of the output (for vector formats, theraster_resolutionofgraph_draw(), 300 ppi by default), in every format. With"native", it is the mesh, except in SVG and PostScript output, where it is the image of"raster", for the reasons above. With"strips", it is made of strips with a linear gradient along each segment of the flattened curve, which is vector output also in SVG, at the cost of files 3 to 5 times larger than with linear gradients, and of a slower rendering of translucent gradients (about 20 times with librsvg). With"patches", it is made of pieces of solid color, short enough that consecutive pieces differ by at most one level of 8-bit color, as when Inkscape converts mesh patterns, which avoids gradients at the cost of even larger files. With"strips"and"patches", an opacity that varies along the edge may show faint seams between the pieces.strorint"native"dash_style
Dash pattern is specified by an array of positive values. Each value provides the length of alternate “on” and “off” portions of the stroke. The last value specifies an offset into the pattern at which the stroke begins. The lengths are in the units given by
size_units.sequence of
floats[]text
Text to draw next to the edges.
str""text_color
Color used to draw the text. If the value is
"auto", it will be black or white, whichever has the largest contrast with the background (bg_color, or white if it is not given).stror list offloats"auto"text_distance
Distance from the edge and its text.
floatorint5text_parallel
If
Truethe text will be drawn parallel to the edges.boolTruetext_out_color
Color used to draw the text outline.
stror list offloats[0,0,0,0]text_out_width
Width of the text outline, which is drawn around the glyphs (only visible if
text_out_coloris not transparent).float1.font_family
Font family used to draw the text.
str"serif"font_slant
Font slant used to draw the text.
cairo.FONT_SLANT_*font_weight
Font weight used to draw the text.
cairo.FONT_WEIGHT_*font_size
Font size used to draw the text.
floatorint12sloppy
If
False, the parts of the edge line that lie inside the source and target vertices, or below the edge markers, are clipped away, so that they do not show through translucent vertices and markers. IfTrue, the clipping is skipped, which is significantly faster. See also theresparameter.boolFalseseamless
If
True, the edge line and its markers are composed as a single shape with uniform opacity, without seams between them. This is significantly slower, unlesstrim == True.boolFalsetrim
If
True, the hidden parts of the edge line (seesloppy) are cut off geometrically, instead of being clipped, which is significantly faster, and yields smaller vector output. The result differs from clipping only at the scale of the line width, where the line is cut.boolFalsezorder
Order in which the edge is drawn, relative to all vertices and edges: the ones with larger values are drawn on top. Ties are drawn in the order given by
nodesfirst,vorder, andeorder.float0text_zorder
If given, the text of the edge is drawn separately from it, with this z-order (see
zorder). For instance, a large value draws it on top of all vertices and edges. Ifnan, the text is drawn together with the edge.floatnanWith the default
edge_gradient_render == "native", the edge gradients are rendered according to the shape of the edge,edge_gradient_type, and the output format, as follows:Edge
edge_gradient_typeOutput
Rendering
curved
"path"SVG, PostScript, and EPS
image as with
"raster", at the resolutionraster_resolutioncurved
"path"PDF, PNG, and other surfaces
mesh pattern
straight
any
any
linear gradient
curved
"linear"any
linear gradient
Examples
>>> g = gt.price_network(1500) >>> deg = g.degree_property_map("in") >>> deg.a = 4 * (sqrt(deg.a) * 0.5 + 0.4) >>> ebet = gt.betweenness(g)[1] >>> ebet.a /= ebet.a.max() / 10. >>> eorder = ebet.copy() >>> eorder.a *= -1 >>> pos = gt.hfd_layout(g) >>> control = g.new_edge_property("vector<double>") >>> for e in g.edges(): ... d = sqrt(sum((pos[e.source()].a - pos[e.target()].a) ** 2)) / 5 ... control[e] = [0.3, d, 0.7, d] >>> gt.graph_draw(g, pos=pos, vertex_size=deg, vertex_fill_color=deg, vorder=deg, ... edge_color=ebet, eorder=eorder, edge_pen_width=ebet, ... edge_control_points=control, # some curvy edges ... output="graph-draw.pdf") <...>
SFDP force-directed layout of a Price network with 1500 nodes. The vertex size and color indicate the degree, and the edge color and width the edge betweenness centrality.#
By default, all edges are drawn below all vertices. With
edge_zorderandvertex_zorderthey can be interleaved, and withvertex_text_zorderandedge_text_zorderthe texts can be drawn separately, e.g. on top of everything else:>>> g = gt.collection.data["football"] >>> vlist, elist = gt.shortest_path(g, g.vertex(9), g.vertex(110)) >>> ecolor = g.new_ep("string", val="#aaaaaa") >>> ewidth = g.new_ep("double", val=1) >>> ez = g.new_ep("double") >>> vtext = g.new_vp("string") >>> for e in elist: ... ecolor[e] = "#cc0000" ... ewidth[e] = 6 ... ez[e] = 1 >>> for v in vlist: ... vtext[v] = g.vp.label[v] >>> gt.graph_draw(g, g.vp.pos, vertex_text=vtext, vertex_text_zorder=2, ... vertex_text_position=0, vertex_font_size=12, ... edge_color=ecolor, edge_pen_width=ewidth, edge_zorder=ez, ... output="graph-draw-zorder.pdf") <...>
A shortest path in the network of American football games, drawn on top of all vertices (
edge_zorder=1), with the names of the teams on top of everything (vertex_text_zorder=2).#For large graphs with edge markers, or for vector output,
edge_trimdraws the same figure considerably faster, and with smaller files, than the default clipping of the edges:>>> g = gt.collection.data["polblogs"] >>> g = gt.extract_largest_component(g, directed=False, prune=True) >>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=g.vp.value, ... edge_marker_size=4, edge_pen_width=0.5, ... edge_color=[0, 0, 0, .3], edge_trim=True, ... output="graph-draw-trim.pdf") <...>
Network of hyperlinks between political blogs, drawn with
edge_trim=True. The PDF file is about three times smaller than with the default clipping.#