graph_draw

Contents

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:
gGraph

Graph to be drawn.

posVertexPropertyMap (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.

vorderVertexPropertyMap (optional, default: None)

If provided, defines the relative order in which the vertices are drawn.

eorderEdgePropertyMap (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 as True, 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 if mplfig is given, in which case the axis limits are set by matplotlib’s autoscaling, or by calling fit_view() on the returned object.

fit_view_inkbool (optional, default: None)

If True, and fit_view == True the 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 is None, then it will be assumed True for networks of size 1,000 nodes or less, otherwise it will be assumed False.

adjust_aspectbool (optional, default: True)

If True, and fit_view == True the 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 True and an IPython notebook is being used, an inline version of the drawing will be returned. By default, this is True only if an inline matplotlib backend is active.

inline_scalefloat (optional, default: 2.)

Resolution scaling factor for inline images.

mplfigmatplotlib container object (optional, default: None)

The mplfig object needs to have an add_artist() function. This can for example be a matplotlib.figure.Figure or matplotlib.axes.Axes. Only the cairo backend is supported; use switch_backend('cairo'). If this option is used, a GraphArtist object is returned.

yflipbool (optional, default: True)

If True and mplfig is given, the y axis of the matplotlib axes will be inverted (if it is not already), which reproduces the orientation of the output when mplfig is None. The axis limits can then be set with fit_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 the output parameter.

bg_colorstr or sequence (optional, default: None)

Background color. The default is transparent.

antialiascairo.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 (see cairo.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. With mplfig, 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_seamless is 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 when output is given; for the interactive window, the value is 5 pixels.

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 from output_size, and in the interactive window the sizes follow the zoom. The value of res is always in output units.

vertex_*VertexPropertyMap or arbitrary types (optional, default: None)

Parameters following the pattern vertex_<prop-name> specify the vertex property with name <prop-name>, as an alternative to the vprops parameter.

edge_*EdgePropertyMap or arbitrary types (optional, default: None)

Parameters following the pattern edge_<prop-name> specify the edge property with name <prop-name>, as an alternative to the eprops parameter.

**kwargs

Any extra parameters are passed to interactive_window(), GraphWindow, GraphWidget, and cairo_draw().

Returns:
posVertexPropertyMap

Vector vertex property map with the x and y coordinates of the vertices.

selectedVertexPropertyMap (optional, only if output is None)

Boolean-valued vertex property map marking the vertices which were selected interactively.

See also

cairo_draw

Draw a graph to a Cairo context

draw_hierarchy

Draw a nested block model hierarchy

interactive_window

Interactive window for drawing a graph

sfdp_layout

Multilevel 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.

str or int

"circle"

color

Color used to stroke the lines of the vertex.

str or list of floats

[0.6, 0.6, 0.6, 0.8]

fill_color

Color used to fill the interior of the vertex.

str or list of floats

[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).

float or int

5

aspect

The aspect ratio of the vertex.

float or int

1.0

rotation

Angle (in radians) to rotate the vertex.

float

0.

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.

int

1

pen_width

Width of the lines used to draw the vertex, in the default units of the output format (normally either pixels or points).

float or int

0.8

halo

Whether to draw a circular halo around the vertex.

bool

False

halo_color

Color used to draw the halo.

str or list of floats

[0., 0., 1., 0.5]

halo_size

Relative size of the halo.

float

1.5

text

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).

str or list of floats

"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.

float or int

or "centered"

-1

text_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.

float

0.0

text_out_color

Color used to draw the text outline.

str or list of floats

[0,0,0,0]

text_out_width

Width of the text outline, which is drawn around the glyphs (only visible if text_out_color is not transparent).

float

1.

font_family

Font family used to draw the text.

str

"serif"

font_slant

Font slant used to draw the text.

cairo.FONT_SLANT_*

cairo.FONT_SLANT_NORMAL

font_weight

Font weight used to draw the text.

cairo.FONT_WEIGHT_*

cairo.FONT_WEIGHT_NORMAL

font_size

Font size used to draw the text.

float or int

12

surface

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.Surface or str

None

pie_fractions

Fractions of the pie sections for the vertices if shape=="pie".

list of int or float

[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_cm

zorder

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, and eorder.

float

0

text_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. If nan, the text is drawn together with the vertex.

float

nan

List of edge properties

Name

Description

Accepted types

Default Value

color

Color used to stroke the edge lines.

str or 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).

float or int

1.0

start_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.

str or int

none

mid_marker_pos

Relative position of the middle marker.

float

0.5

marker_size

Size of edge markers, in units appropriate to the output format (normally either pixels or points).

float or int

4

control_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] where o is 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 by gradient_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).

str or int

"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 of draw_hierarchy()); it is not supported in SVG output, which has no displayable mesh patterns (a ValueError is 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, the raster_resolution of graph_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.

str or int

"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).

str or list of floats

"auto"

text_distance

Distance from the edge and its text.

float or int

5

text_parallel

If True the text will be drawn parallel to the edges.

bool

True

text_out_color

Color used to draw the text outline.

str or list of floats

[0,0,0,0]

text_out_width

Width of the text outline, which is drawn around the glyphs (only visible if text_out_color is not transparent).

float

1.

font_family

Font family used to draw the text.

str

"serif"

font_slant

Font slant used to draw the text.

cairo.FONT_SLANT_*

cairo.FONT_SLANT_NORMAL

font_weight

Font weight used to draw the text.

cairo.FONT_WEIGHT_*

cairo.FONT_WEIGHT_NORMAL

font_size

Font size used to draw the text.

float or int

12

sloppy

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. If True, the clipping is skipped, which is significantly faster. See also the res parameter.

bool

False

seamless

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, unless trim == True.

bool

False

trim

If True, the hidden parts of the edge line (see sloppy) 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.

bool

False

zorder

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, and eorder.

float

0

text_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. If nan, the text is drawn together with the edge.

float

nan

With 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_type

Output

Rendering

curved

"path"

SVG, PostScript, and EPS

image as with "raster", at the resolution raster_resolution

curved

"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")
<...>
../_images/graph-draw.png

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_zorder and vertex_zorder they can be interleaved, and with vertex_text_zorder and edge_text_zorder the 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")
<...>
../_images/graph-draw-zorder.png

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_trim draws 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")
<...>
../_images/graph-draw-trim.png

Network of hyperlinks between political blogs, drawn with edge_trim=True. The PDF file is about three times smaller than with the default clipping.#