Drawing graphs with graph_draw()#
The main drawing function of the draw module,
graph_draw(), uses the
cairo vector graphics library to write a
drawing to a file in the PDF, SVG, PNG, or PostScript formats, to show it in
an interactive window, or to embed it in a Jupyter
notebook. The same drawings can also be placed in
matplotlib figures, together with other plots, as
described in the guide Integration with matplotlib. Here we explain how a
drawing is set up, and how the many options of this function can be combined,
with self-contained examples. The complete list of vertex and edge properties
that can be set, together with their default values, is given in the
documentation of graph_draw(), to which we refer for
the details that we omit, and they are summarized in Sec.
Overview of the vertex and edge properties at the end of this guide, with links to the
examples where each of them is used.
Positions, output, and view#
Note
Besides sfdp_layout() and
hfd_layout(), the draw module
provides fruchterman_reingold_layout(),
arf_layout(), radial_tree_layout()
for trees and hierarchies, planar_layout() for planar
graphs, and random_layout(). The graphs of the
Netzschleuder repository usually come with a
layout in the property map _pos, as in the quick start guide.
To draw a graph we need the positions of its vertices, given as a
vector-valued vertex property map with their \(x\) and \(y\) coordinates. The
positions can be arbitrary, but we typically obtain them with one of the
layout algorithms of the draw module, such as
sfdp_layout() or hfd_layout().
Many graphs
in the collection module already contain a layout in the
internal property map pos, as is the case for the network of American
college football games (football), which we can draw by calling
g = gt.collection.data["football"]
gt.graph_draw(g, pos=g.vp.pos, output="football.svg")
which yields the following figure, where all vertices and edges are drawn with the default sizes and colors.
Network of American college football games, drawn with the default options.#
If we omit the positions, they are computed with
hfd_layout() and returned by the function, so that we
can reuse them in subsequent drawings, as in
pos = gt.graph_draw(g)
Tip
In a Jupyter notebook, inline=False opens an interactive window instead of
embedding the drawing, and inline_scale (by default \(2\)) sets the
resolution of the embedded PNG image relative to output_size. Instead of a
file name, output can also be a file object, such as an
io.BytesIO, in which case the format must be given with fmt.
We choose where the drawing goes with the output parameter, to which we
can pass a file name whose extension determines the format, among .pdf,
.svg, .png, .ps, and .eps, optionally followed by .gz, .bz2, or
.zip for compressed output. We can also give the format via the fmt
parameter, as is required when output is a file object. If output is
omitted, the graph is shown in an interactive window (see Sec.
Interactive drawing and other interfaces), unless an inline matplotlib backend is active,
as is the default in Jupyter notebooks, in which case the drawing is embedded
in the notebook as a PNG image (or as an SVG image, if fmt="svg" is
passed). Finally, if we pass a matplotlib figure or axes as the mplfig
parameter, the graph is drawn as part of that figure, together with any other
plots it contains, as we describe in the guide on the integration with matplotlib.
The positions are given in arbitrary units, in a coordinate system where the
\(y\) axis points downward, as is usual in computer graphics. With the default
fit_view=True, the layout is translated and scaled so that it fits a canvas
of size output_size, by default \(600\times 600\) pixels for PNG images, or
points for the vector formats. Since adjust_aspect=True by
default, the width or the height of the canvas is then reduced to match the
aspect ratio of the layout, so that no empty margins remain. A numeric value
of fit_view scales the drawing by that factor, where a value below one
leaves room for labels near the border, and a tuple (x, y, w, h) selects the rectangle of
the layout that is shown, as we will use in Sec. Large graphs.
Note
For graphs with at most 1,000 vertices, graph_draw()
draws the graph twice when fit_view=True: first to measure the extent of
everything that is drawn, including labels and markers, and then to fit this
extent into the canvas. For larger graphs only the positions are used, which
can be changed with fit_view_ink.
In contrast to the positions, all sizes—of vertices, lines, markers and
fonts—are given in the units of the output, and therefore do not change
with the scale of the layout. If the vertex size is not given, it is chosen
as \(\sqrt{A/N}/3.5\) for a canvas of area \(A\) and a graph with \(N\) vertices,
and the line widths, marker sizes, and font sizes are derived from it, so that
the drawing of a graph of any size has reasonable proportions without further
adjustments. We can scale all these sizes together with the ink_scale
parameter. Finally, the background color is set with bg_color, and the
background is transparent if it is not given.
Note
Drawings placed in matplotlib figures (see the integration with matplotlib) always give the sizes in the units of the positions, i.e. in the data coordinates of the axes.
Alternatively, with size_units="layout", all sizes are given in the units
of the layout, like the positions, and are therefore scaled together with
them. In this case the default sizes are computed from the extent of the
layout instead of the size of the canvas, and in the interactive window the
sizes follow the zoom. The difference is seen when we zoom into a part of the
layout, which we do here by passing as fit_view a rectangle with half the
width of the layout:
g = gt.collection.data["football"]
x, y = g.vp.pos.get_2d_array()
w = np.ptp(x) / 2
view = (x.mean() - w / 2, y.mean() - w / 2, w, w)
for units in ["output", "layout"]:
gt.graph_draw(g, g.vp.pos, size_units=units, fit_view=view,
output_size=(300, 300), output=f"football-{units}.svg")
With the default size_units="output", the vertices and lines keep the size
they have in the drawing of the whole network, whereas with
size_units="layout" they are enlarged together with the layout.
|
|
The dash lengths (dash_style) and the displacements of labels
(text_offset) follow size_units like the other sizes, whereas the control
points of curved edges (control_points) are always given in the units of
the layout, and res always in the units of the output.
Vertex and edge properties#
We control the appearance of the vertices and edges with keyword arguments
of the form vertex_<name> and edge_<name>, where <name> is one of the
properties listed in graph_draw(), such as size,
fill_color, shape, or text for the vertices, and color, pen_width,
or end_marker for the edges. Each property accepts either a single value,
used for all vertices or edges alike, or a property map with one value for
each vertex or edge. We can also pass the same properties as dictionaries,
via the vprops and eprops parameters, with the names written without the
prefix, so that the following two calls are equivalent:
gt.graph_draw(g, pos, vertex_size=10, vertex_fill_color="white", edge_pen_width=2)
gt.graph_draw(g, pos, vprops=dict(size=10, fill_color="white"),
eprops=dict(pen_width=2))
Tip
Any colormap of matplotlib can be used, or a new one created from a
list of colors with matplotlib.colors.LinearSegmentedColormap.from_list()
or matplotlib.colors.ListedColormap, as we do below. Property maps
of colors can be computed from other property maps with the transformations
described in the quick start guide.
Colors are given either as names or hexadecimal strings understood by
matplotlib, such as "white" or "#a0c4e8", or as sequences of red,
green, blue, and alpha (i.e. opacity) values in the interval \([0, 1]\), so that
(1, 0, 0, .5) is a translucent red. Accordingly, a property map with
colors has values of type string or vector<double>. A color property can
also be given as a scalar property map (of type int, double, etc.),
whose values are then mapped to colors with a
colormap,
passed as vcmap for the vertices and ecmap for the edges, or as a tuple
(cmap, alpha) that also sets the opacity. Integer-valued property maps with
at most 40 distinct values are treated as categories, and receive distinct
colors from a categorical colormap by default, whereas all other values are
normalized linearly onto the range of the colormap. This normalization can be
replaced by a matplotlib.colors.Normalize object passed as vcnorm
or ecnorm, such as a matplotlib.colors.LogNorm for a
logarithmic scale.
Note
The function prop_to_size() returns a new property map
of type double, with values \(y_i = a + (b - a)\,[(x_i - x_{\min}) /
(x_{\max} - x_{\min})]^p\) for the interval \([a, b]\) and the exponent \(p\)
(power, by default \(1/2\)), so that the default already compresses large
values.
Sizes and widths can also be given as property maps, but the quantities we
want to visualize (degrees, centralities, weights, etc.) are seldom in a
range that is suitable for sizes. The function
prop_to_size() maps them into a given interval,
optionally after a power law or a logarithmic transformation, so that broad
distributions remain legible.
The choice of colors follows the kind of quantity they represent. Categories
are best shown with a few saturated and well-separated colors, whereas a
magnitude is best shown with a colormap of a single hue, from a light gray
for the smallest values to a saturated color for the largest ones, so that
larger values stand out more. In this guide we use the colors blue, red,
green, purple, and orange of the ColorBrewer
palette “Set1” for both purposes, where the colormaps are obtained with
matplotlib.colors.LinearSegmentedColormap.from_list(). The saturated
colors are used for the edges, which are thin lines, whereas the vertices,
which cover larger areas, are filled with pastel versions of them, obtained by
mixing them with white.
As an example combining these features, we consider the network of books about US politics sold by an online bookseller (polbooks), where the edges connect books that were frequently bought together. We color the books according to their political leaning, given as a string, and set their sizes according to their betweenness centrality, whereas the colors and widths of the edges are given by the edge betweenness:
from matplotlib.colors import LinearSegmentedColormap
# Colormaps of a single hue, from light gray to a color of the Set1 palette,
# which we use for magnitudes throughout this guide: for the edges with the
# saturated colors, and for the vertices with a pastel red (Set1 red mixed
# with 35% of white).
blues = LinearSegmentedColormap.from_list("blues", ["#d9d9d9", "#377eb8"])
purples = LinearSegmentedColormap.from_list("purples", ["#d9d9d9", "#984ea3"])
reds = LinearSegmentedColormap.from_list("reds", ["#d9d9d9", "#ed6a6b"])
g = gt.collection.data["polbooks"]
# The leaning is "l" (liberal), "c" (conservative) or "n" (neutral), shown
# with pastel blue, red and gray (the Set1 colors mixed with 50% of white).
colors = {"l": "#9bbedc", "c": "#f28c8e", "n": "#cccccc"}
leaning = g.new_vp("string", vals=[colors[x] for x in g.vp.value])
vb, eb = gt.betweenness(g)
gt.graph_draw(g, g.vp.pos,
vertex_fill_color=leaning,
vertex_size=gt.prop_to_size(vb, 5, 25),
edge_color=eb, ecmap=purples,
edge_pen_width=gt.prop_to_size(eb, .5, 5),
output="polbooks-props.svg")
The resulting drawing shows that the edges with the largest betweenness (in dark purple) connect the liberal books with the conservative and the neutral ones, and that the neutral books lie between the two main groups.
Network of books about US politics. The vertex colors indicate the political leaning (blue: liberal; red: conservative; gray: neutral), and the vertex sizes the betweenness centrality. The edge colors (from gray to purple) and widths indicate the edge betweenness.#
Vertices#
The shape property chooses the shape of the vertices among circles,
regular polygons, their “double” versions with an outer contour, pies, and
"none", in which case only the text of the vertex is drawn. The shapes can
be stretched horizontally with aspect and rotated (by an angle in radians)
with rotation, and their contour and interior are drawn with the colors
color and fill_color, respectively, where the width of the contour is
given by pen_width. In the following example we place one vertex of each
shape on a grid:
shapes = ["circle", "triangle", "square", "pentagon", "hexagon",
"heptagon", "octagon", "double_circle", "double_triangle",
"double_square", "double_pentagon", "double_hexagon",
"double_heptagon", "double_octagon", "pie", "none"]
g = gt.Graph(len(shapes))
pos = g.new_vp("vector<double>", vals=[(i % 4, .6 * (i // 4)) for i in g.iter_vertices()])
gt.graph_draw(g, pos,
vertex_shape=g.new_vp("string", vals=shapes),
vertex_text=g.new_vp("string", vals=shapes),
vertex_text_position=np.pi / 2, vertex_font_size=10,
vertex_size=30, vertex_pen_width=2,
output_size=(500, 350), output="shapes.svg")
The vertex shapes, each labeled with the corresponding value of shape.#
The anchor property determines where the edges end: at the border of the
vertex (anchor=1, the default), or at its center (anchor=0). We show
this, together with aspect and rotation, in the following example, where
the arrows point to vertices with these properties changed:
g = gt.Graph([(1, 0), (3, 2), (5, 4)])
pos = g.new_vp("vector<double>", vals=[(0, 0), (2, 0), (0, 1), (2, 1), (0, 2), (2, 2)])
gt.graph_draw(g, pos, vertex_shape="square", vertex_size=30,
vertex_aspect=g.new_vp("double", vals=[2, 1, 1, 1, 1, 1]),
vertex_rotation=g.new_vp("double", vals=[0, 0, np.pi / 4, 0, 0, 0]),
vertex_anchor=g.new_vp("int", vals=[1, 1, 1, 1, 0, 1]),
vertex_fill_color=(.216, .494, .722, .4), vertex_color="#377eb8",
vertex_pen_width=2,
edge_text=g.new_ep("string", vals=["aspect=2", "rotation=π/4", "anchor=0"]),
edge_font_size=12, edge_text_distance=10, edge_pen_width=2,
edge_marker_size=12, output_size=(300, 250),
output="vertex-geometry.svg")
Since the vertices are translucent, we can see that the arrow that points to
the vertex with anchor=0 ends at its center.
Square vertices with a translucent fill and a contour of color
vertex_color, where the targets of the edges have the values of aspect,
rotation, and anchor given by the edge labels.#
Tip
Pies are the usual way to show uncertain group memberships, e.g. the posterior marginal distributions of the partitions obtained with the stochastic block model, as described in Sec. Sampling from the posterior distribution of the inference guide.
With shape="pie", each vertex is drawn as a pie chart, with the sizes of the
slices given by pie_fractions and their colors by pie_colors. We can
use this to show a distribution on each vertex, such as the political leaning
of the neighbors of each book in the network considered above:
g = gt.collection.data["polbooks"]
kinds = ["l", "c", "n"]
frac = g.new_vp("vector<double>")
for v in g.vertices():
frac[v] = [len([u for u in v.all_neighbors() if g.vp.value[u] == k])
for k in kinds]
gt.graph_draw(g, g.vp.pos, vertex_shape="pie", vertex_pie_fractions=frac,
vertex_pie_colors=[colors[k] for k in kinds], vertex_size=15,
output="polbooks-pie.svg")
In the resulting figure we see that most books are bought together only with books of the same leaning, and that the books with mixed neighborhoods lie between the two groups.
Network of books about US politics, where each vertex shows the fractions of its neighbors with each political leaning (blue: liberal; red: conservative; gray: neutral).#
Note
An image given by a file name is loaded only once, even if the same name appears for many vertices. PNG files are read by cairo, and other formats (e.g. JPEG) via GdkPixbuf. The animations guide uses images to show the states of the vertices of a dynamical process.
The surface property replaces the shape by an image, given either as a
cairo.Surface or as the name of an image file, and scaled to the
size of the vertex. The halo property, on the other hand, draws a
translucent disk behind the vertex, with color halo_color and a size
relative to the vertex given by halo_size, and we can use it to highlight
a few vertices. In the following we use both with the network of friendships
between the members of a karate club (karate, in its subnetwork 78),
where the two members with the largest degree, who correspond to the
instructor and the administrator of the club, are drawn with a different
image and a halo:
g = gt.collection.data["karate"]
deg = g.degree_property_map("total")
hubs = g.new_vp("bool", vals=deg.a >= 15)
# Each image is loaded only once, even if its file name is repeated.
face = g.new_vp("string", vals=["../../animation/face-surprise.png" if h else
"../../animation/face-grin.png" for h in hubs])
gt.graph_draw(g, g.vp.pos, vertex_surface=face,
vertex_size=gt.prop_to_size(deg, 20, 40),
vertex_halo=hubs, vertex_halo_color="#ffbf80",
vertex_halo_size=1.4, output="karate-faces.svg")
Network of friendships in Zachary’s karate club, with images as vertices, and sizes proportional to the degrees. The two vertices with the largest degree are drawn with orange halos.#
Tip
Any property map can be used as the label, e.g. vertex_text=g.vertex_index
shows the index of every vertex, as in the quick start guide, and vertex_text=g.vp.label the names that many graphs of the
collection module carry. The labels of all or some
vertices can be omitted by giving them empty strings.
The text property attaches a label to each vertex, given as a string or as
a property map of any type, whose values are then converted to strings. The
placement of the label is determined by text_position in one of three ways.
A negative value places the text inside the vertex, where the default value
\(-1\) also enlarges the vertex so that the text fits, whereas any other
negative value keeps the vertex size. A non-negative value is an angle in
radians, measured clockwise from the \(x\) axis since the \(y\) axis points
downward, and places the text outside the vertex in that direction. Finally,
the value "centered" places the texts outside the vertices and rotates them
radially away from the center of the layout, as intended for circular
layouts. We can also displace the labels with text_offset, rotate them with text_rotation,
draw them with an outline of color text_out_color and width
text_out_width, and choose their font with font_family, font_size,
font_slant, and font_weight. We illustrate the first two cases in the
following example, where each vertex is labeled with its own value of
text_position:
labels = ["-1", "-2", "0", "π/2", "π", "3π/2"]
tpos = [-1, -2, 0, np.pi / 2, np.pi, 3 * np.pi / 2]
g = gt.Graph(len(labels))
pos = g.new_vp("vector<double>", vals=[(i, 0) for i in g.iter_vertices()])
gt.graph_draw(g, pos, vertex_size=18, vertex_font_size=14,
vertex_text=g.new_vp("string", vals=labels),
vertex_text_position=g.new_vp("double", vals=tpos),
output_size=(500, 100), fit_view=.8, output="text-position.svg")
Vertices labeled with their own values of text_position.#
Note that the first vertex has been enlarged to fit its label, whereas the label of the second one extends beyond its contour.
The fonts, colors, and outlines of the labels, as well as the options that only apply to the labels of the edges, are shown in the following example, where again each label describes its own settings. The edge labels are drawn with a white outline, which keeps them legible where they cross other lines:
import cairo
N, B = int(cairo.FONT_WEIGHT_NORMAL), int(cairo.FONT_WEIGHT_BOLD)
R, I = int(cairo.FONT_SLANT_NORMAL), int(cairo.FONT_SLANT_ITALIC)
g = gt.Graph([(0, 1), (1, 2), (2, 3), (3, 4)])
pos = g.new_vp("vector<double>", vals=[(i, .5 * (i % 2)) for i in range(5)])
# The labels are placed above the upper vertices and below the lower ones.
tpos = g.new_vp("double", vals=[3 * np.pi / 2 if i % 2 == 0 else np.pi / 2
for i in range(5)])
gt.graph_draw(g, pos, vertex_size=20, vertex_fill_color="#9bbedc",
vertex_text=g.new_vp("string", vals=["Times", "sans-serif bold",
"monospace italic",
"outline", "offset"]),
vertex_text_position=tpos, vertex_font_size=14,
vertex_font_family=g.new_vp("string", vals=["Times", "sans-serif",
"monospace", "Times",
"Times"]),
vertex_font_weight=g.new_vp("int", vals=[N, B, N, N, N]),
vertex_font_slant=g.new_vp("int", vals=[R, R, I, R, R]),
vertex_text_color=g.new_vp("string", vals=["black"] * 3 +
["white", "black"]),
vertex_text_out_color="black",
vertex_text_out_width=g.new_vp("double", vals=[0, 0, 0, 1, 0]),
vertex_text_offset=g.new_vp("vector<double>",
vals=[[0, 0]] * 4 + [[20, 0]]),
edge_text=g.new_ep("string", vals=["text_parallel=False",
"text_color",
"mid_marker_pos=.25",
"font_weight"]),
edge_text_parallel=g.new_ep("bool", vals=[False, True, True, True]),
edge_text_color=g.new_ep("string", vals=["black", "#e41a1c",
"black", "black"]),
edge_font_weight=g.new_ep("int", vals=[N, N, N, B]),
edge_mid_marker=g.new_ep("string", vals=["none", "none", "arrow",
"none"]),
edge_mid_marker_pos=.25, edge_font_slant=I, edge_font_size=12,
edge_text_out_color="white", edge_text_out_width=2,
output_size=(750, 260), output="text-styles.svg")
The font slant and weight are given by the constants of
cairo.FontSlant and cairo.FontWeight, which are integers,
and therefore can also be stored in property maps of type int. The outline
width text_out_width is the visible width of the outline outside the glyphs,
given like the other sizes in the units of the output (or of the layout, with
size_units="layout"), and the outline does not show through a translucent
text.
Vertex and edge labels with different fonts, colors, outlines, and offsets, each describing the options that differ from the other labels. All edge labels are italic and have a white outline.#
Note
The value "centered" is also used by
draw_hierarchy(), whose radial layouts place the
vertices on a circle (see Sec. Hierarchical layouts).
The default text color "auto", of both vertices and edges, chooses black
or white, whichever has the largest contrast with what lies behind the text.
For a text inside a vertex this is its fill color, drawn over the background
(so that a translucent fill is taken into account), or the average color of
the slices of a pie. For the texts outside the vertices, the texts of
vertices with shape="none" and those of the edges, it is the value of
bg_color, or white if it is not given. We can see this in
the following example, where the teams of the football network are placed on
a circle, grouped by their conference, and labeled with
text_position="centered" on a dark background:
g = gt.collection.data["football"]
# The vertices are ordered by conference (the property "value"), and then
# placed at equal angles on the unit circle.
order = sorted(g.vertices(), key=lambda v: (g.vp.value[v], int(v)))
theta = g.new_vp("double")
for i, v in enumerate(order):
theta[v] = 2 * np.pi * i / g.num_vertices()
pos = g.new_vp("vector<double>", vals=[(np.cos(theta[v]), np.sin(theta[v]))
for v in g.vertices()])
same = g.new_ep("bool",
vals=gt.edge_endpoint_property(g, g.vp.value, "source").a ==
gt.edge_endpoint_property(g, g.vp.value, "target").a)
gt.graph_draw(g, pos, vertex_fill_color=g.vp.value, vertex_size=8,
vertex_text=g.vp.label, vertex_text_position="centered",
vertex_font_size=8,
edge_color=g.new_ep("vector<double>",
vals=[(.9, .9, .9, .8) if s else (.216, .494, .722, .5)
for s in same]),
bg_color="#202030", fit_view=.75, output="football-circle.svg")
Since the background is dark, the labels are drawn in white, and since
value is an integer property map with twelve distinct values, the
conferences receive distinct colors from the categorical colormap.
Network of American college football games, with the teams placed on a circle and grouped by conference, which is indicated by the vertex colors. The games between teams of the same conference are drawn in white, and the others in translucent blue.#
Here the groups on the circle were given by the known conferences, and their order was chosen by hand. A layout of this kind is also obtained from a hierarchical partition inferred from the network itself, in which the groups and their order on the circle follow the hierarchy, and the edges are bundled along it, as we describe in Sec. Hierarchical layouts.
Edges#
Note
Whether an edge has an arrow is determined only by end_marker (and
start_marker), which defaults to "arrow" for directed graphs and to
"none" for undirected ones. A directed graph can therefore be drawn without
arrows with edge_end_marker="none", and an undirected graph can be drawn as
directed with a GraphView with directed=True (see
Sec. Graph views of the quick start guide).
The edges are drawn as lines with color color and width pen_width. Their
dash pattern is set by dash_style, as a list of the alternating lengths of
the drawn and the skipped parts of the line, followed by an offset into the
pattern. Instead of a single color, we can give a linear gradient along
the edge, as a list of groups of five values [o, r, g, b, a], where o
is the position along the edge, from \(0\) at the source to \(1\) at the target,
and the remaining values the color at that position. We can place markers at
the start (start_marker), at the end (end_marker), and in between
(mid_marker, at the relative position mid_marker_pos) of each edge,
choosing among the shapes "none", "arrow", "circle", "square",
"diamond", and "bar", with a size given by marker_size. For directed
graphs, end_marker is "arrow" by default, and if pen_width is given
without marker_size, the latter is set to \(2.75\) times the former. Finally,
the text property places a label beside each edge, at a distance
text_distance, and parallel to it if text_parallel=True, as is the
default. We show some of these options in the following example, where each
edge is labeled with its own settings:
styles = [dict(text="default"),
dict(text="start_marker='circle'", start_marker="circle"),
dict(text="mid_marker='bar'", mid_marker="bar"),
dict(text="end_marker='diamond'", end_marker="diamond"),
dict(text="dash_style=[10, 5, 0]", dash_style=[10, 5, 0]),
dict(text="gradient", gradient=[0, .216, .494, .722, 1,
1, .894, .102, .110, 1]),
dict(text="pen_width=3", pen_width=3, color="#984ea3")]
# Each style is set on one edge, via edge property maps with the
# corresponding value types.
g = gt.Graph()
pos = g.new_vp("vector<double>")
eprops = {k: g.new_ep("double" if k == "pen_width" else
"vector<double>" if k in ["dash_style", "gradient"] else
"string")
for k in set().union(*styles)}
for i, style in enumerate(styles):
u, v = g.add_vertex(), g.add_vertex()
pos[u], pos[v] = (0, i), (3, i)
e = g.add_edge(u, v)
style = dict(dict(pen_width=1.5, color="#333333", start_marker="none",
mid_marker="none", end_marker="arrow"), **style)
for k, x in style.items():
if k in eprops:
eprops[k][e] = x
gt.graph_draw(g, pos, vertex_size=12, eprops=eprops, edge_marker_size=12,
edge_font_size=12, edge_text_distance=8,
output_size=(400, 460), output="edge-styles.svg")
Edges drawn with different markers, dash patterns, gradients, and widths, each labeled with the options that differ from the default. The vertices are three layout units apart.#
Curved edges#
Note
The distance between parallel edges, and the direction of self-loops, can be
set with the parameters parallel_distance and loop_angle of
cairo_draw(), which graph_draw()
passes on. By default, self-loops point away from the center of the layout.
Edges are drawn as straight lines by default, except for parallel edges and
self-loops, which are automatically drawn as curves that do not overlap.
We can specify arbitrary curves with the control_points property, as a
sequence of cubic Bézier curves.
The sequence is given as a list of coordinates that contains the start
point, followed by three points for each segment, namely its two control
points and its end point, i.e. \(2 + 6k\) values for \(k\) segments. The points are
given in a coordinate system attached to the edge, where the source is at
\((0, 0)\) and the target at \((1, 0)\), so that the \(x\) coordinates are
relative to the length of the edge, whereas the \(y\) coordinates are given in
the units of the layout, perpendicular to the edge.
We illustrate this with an arc diagram of the network of co-occurrences of the characters in the novel Les Misérables (lesmis), where the vertices are placed on a line in the order of their indices, and the edges are drawn as arcs of a height proportional to their length. Since the \(y\) axis of the coordinate system of an edge points to its right, when seen from the source toward the target, the height is given the sign opposite to the horizontal extent of the edge, so that all arcs are drawn above the line:
g = gt.collection.data["lesmis"]
pos = g.new_vp("vector<double>", vals=[(i, 0) for i in g.iter_vertices()])
ctrl = g.new_ep("vector<double>")
for e in g.edges():
h = -(pos[e.target()][0] - pos[e.source()][0]) / 2
ctrl[e] = [0, 0, 0, h, 1, h, 1, 0]
w = g.ep.value # number of co-occurrences
deg = g.degree_property_map("total", weight=w)
gt.graph_draw(g, pos, vertex_size=gt.prop_to_size(deg, 3, 12),
vertex_fill_color=deg, vcmap=reds, vertex_text=g.vp.label,
vertex_text_position=0, vertex_text_rotation=np.pi / 2,
vertex_font_size=8,
edge_control_points=ctrl, edge_color=w,
ecmap=(blues, .8),
edge_pen_width=gt.prop_to_size(w, .5, 3), eorder=w,
output_size=(800, 400), output="lesmis-arcs.svg")
The labels are placed below the vertices with text_position=0 and
text_rotation=π/2, since the direction given by the position is rotated
together with the text. The edges are drawn in increasing order of their
weights, as given by eorder (see Sec. Drawing order), so that the
strongest co-occurrences, most of them involving Valjean, are drawn on top.
Arc diagram of the co-occurrences of the characters in Les Misérables, with the characters in the order of the vertex indices. The edge colors (from gray to blue) and widths indicate the number of co-occurrences, and the vertex colors (from gray to red) and sizes the weighted degrees.#
Control points that bundle the edges along a hierarchy are computed by
get_hierarchy_control_points(), and are used in this
way by draw_hierarchy() (see Sec.
Hierarchical layouts).
Clipping, trimming, and seamless edges#
Tip
For figures in vector formats that will be included in papers or slides,
edge_trim=True is usually the best choice, since it yields smaller files
that are faster to display. For opaque vertices and markers,
edge_sloppy=True gives the same picture at the lowest cost.
The parts of an edge that lie inside its source and target vertices, or below
its markers, would show through them if the vertices or the markers are
translucent, and therefore they are not drawn. By default they are removed by
clipping, i.e. the line is drawn through a clip region that excludes the
vertices and the markers, so that it ends exactly at their contours. However,
building and applying a clip region for every edge is slow, and in the vector
formats each edge is stored together with its clip path, so that the files
become large. For this reason, we can choose how the hidden parts are removed
for each edge, via three boolean properties. With sloppy=True, nothing is
removed, and the whole line is drawn between the centers of the vertices.
This is the fastest method, and gives the same result as the others if the
vertices and markers are opaque. With trim=True, the hidden parts are
instead cut off geometrically, i.e. only the visible pieces of the line are
drawn, which is considerably faster than clipping, and yields vector files
that are several times smaller. Since a cut is straight and across the line,
the result differs from clipping only at the scale of the line width, for
instance where the line meets the concave back of an arrow. Finally, with
seamless=True the line and its markers are drawn as a single shape, so that
their overlap is not visible with translucent colors. This is much slower
than the other methods when the hidden parts are clipped, but not when they
are trimmed. We can see the differences in the following example, where the vertices, the lines, and the markers are
translucent:
modes = [dict(text="sloppy", sloppy=True), dict(text="default"),
dict(text="trim", trim=True), dict(text="seamless", seamless=True),
dict(text="seamless + trim", seamless=True, trim=True)]
g = gt.Graph()
pos = g.new_vp("vector<double>")
eprops = dict(text=g.new_ep("string"), sloppy=g.new_ep("bool"),
trim=g.new_ep("bool"), seamless=g.new_ep("bool"))
for i, mode in enumerate(modes):
u, v = g.add_vertex(), g.add_vertex()
pos[u], pos[v] = (0, i), (2, i)
e = g.add_edge(u, v)
for k, x in mode.items():
eprops[k][e] = x
gt.graph_draw(g, pos, vertex_size=40, vertex_fill_color=(.216, .494, .722, .4),
vertex_pen_width=0, eprops=eprops, edge_pen_width=8,
edge_color=(.894, .102, .110, .5), edge_start_marker="circle",
edge_marker_size=24, edge_font_size=14, edge_text_distance=16,
output_size=(300, 500), output="edge-clipping.svg")
In the sloppy edge the line shows through the vertices and the markers,
whereas with clipping and trimming it ends at their contours, apart from a
small overlap at the back of the arrow in the trimmed edge. In the two edges
drawn with seamless=True, the line and the markers have a uniform
opacity.
Translucent edges with circle and arrow markers between translucent vertices, drawn with the different methods to remove the hidden parts of the lines.#
Drawing order#
Note
The option nodesfirst=True has the same effect as vertex_zorder=-1, since
the drawing order is sorted by zorder first, and ties keep the order given
by nodesfirst, vorder, and eorder.
By default, all edges are drawn first, and then all vertices on top of them,
whereas with nodesfirst=True this is reversed. We can set the relative order among
the vertices and among the edges with the scalar property maps vorder and
eorder, where the items with larger values are drawn later, and hence on
top, as we did for the arc diagram above. We can also interleave
vertices and edges, with the zorder property of both, in which case all vertices
and edges are drawn in increasing order of zorder (by default \(0\)), and the
ties are broken by the order described above. In addition,
the text_zorder property draws the labels separately from their vertices
or edges, at the given position in the drawing order, whereas by default
(nan) they are drawn together with them. In the following example, we
highlight the teams of the Big East conference in the football network, by
drawing their games above the other teams, the teams above their games, and
their names above everything else, with a white outline that keeps them
legible over the lines:
g = gt.collection.data["football"]
conf = g.new_vp("bool", vals=g.vp.value.a == 1) # the Big East conference
inner = g.new_ep("bool",
vals=gt.edge_endpoint_property(g, conf, "source").a &
gt.edge_endpoint_property(g, conf, "target").a)
vz = conf.copy("double")
vz.a *= 2
ez = inner.copy("double")
gt.graph_draw(g, g.vp.pos,
vertex_fill_color=g.new_vp("string", vals=["#f28c8e" if c else "#d9d9d9"
for c in conf]),
vertex_size=12, vertex_zorder=vz,
vertex_text=g.new_vp("string", vals=[g.vp.label[v] if conf[v] else ""
for v in g.vertices()]),
vertex_text_position=0, vertex_font_size=12,
vertex_text_zorder=3, vertex_text_out_color="white",
vertex_text_out_width=2,
edge_color=g.new_ep("string", vals=["#e41a1c" if x else "#cccccc"
for x in inner]),
edge_pen_width=g.new_ep("double", vals=4 * inner.a + 1),
edge_zorder=ez, fit_view=.8, output="football-zorder.svg")
Network of American college football games, where the teams of the Big East
conference and the games between them are drawn in red. These games have
edge_zorder=1, the teams vertex_zorder=2, and their names
vertex_text_zorder=3, whereas all other vertices and edges have the
default value \(0\). The names are drawn with a white outline.#
Layouts for large vertices and large graphs#
The positions are an input of the drawing, but the layout algorithms can take
into account how the graph will be drawn. We consider two such cases with
hfd_layout(), which in the first place makes room for
vertices of very different sizes, and in the second groups the vertices
according to a hierarchical partition.
Note
The function hfd_layout() offers further ways to keep
vertices apart: nmin_dist imposes a minimum distance between any two
vertices, and barrier_r gives every vertex a radius, and keeps the vertices
of the same group from overlapping. Unlike vweight, which changes the
forces between all vertices, these only act between vertices that come too
close to each other.
A force-directed layout places the vertices at distances that do not depend
on their sizes, so that large vertices overlap, often hiding the regions
where the important vertices are. The vweight parameter of
hfd_layout() multiplies the repulsion of every vertex
(but not the attraction along its edges), and hence a vertex with a larger
weight keeps the other vertices further away. Since a vertex occupies an area
that grows with the square of its size, we give it a weight proportional to
its squared size, as in the following example, where we draw the largest component of the network of hyperlinks between political
blogs (polblogs) with the vertex sizes given by the degrees:
g = gt.collection.data["polblogs"]
g = gt.extract_largest_component(g, directed=False, prune=True)
deg = g.degree_property_map("total")
size = gt.prop_to_size(deg, 2, 15)
# The leaning of the blogs is 0 (liberal) or 1 (conservative).
leaning = matplotlib.colors.ListedColormap(["#9bbedc", "#f28c8e"])
# The weights are normalized to an average of one.
w = size.copy()
w.fa = w.fa ** 2 / (w.fa ** 2).mean()
# The layout with the weights starts from the one without them, so that the
# two are aligned.
pos = None
for name, vweight in [("default", None), ("vweight", w)]:
pos = gt.hfd_layout(g, pos=pos, vweight=vweight)
gt.graph_draw(g, pos, vertex_size=size, vertex_fill_color=g.vp.value,
vcmap=leaning, vorder=deg, edge_color=(.2, .2, .2, .05),
edge_trim=True, output_size=(400, 400),
output=f"polblogs-{name}.svg")
Without the weights, the blogs with the largest degrees are piled on top of
each other at the centers of the two groups, whereas with them they are
spread apart, and the groups occupy more space. Since the weights only
change the forces, some of the vertices may still touch, which is avoided
completely only with the minimum distance nmin_dist.
Default layout |
Layout with |
Tip
For large networks, the fit of the nested stochastic block model can be
sped up as described in Sec. Dealing with large networks of the inference guide,
e.g. with simple_init=True, which is sufficient for the purpose of a
layout. Any other partition can be used as well, e.g. one given by metadata
of the vertices, as a single property map, or as a hierarchy in the format
returned by get_bs(). The
members of every group are kept together by springs, whose strength is set
by spring_G; smaller values leave more room between the vertices of a
group, at the expense of less distinct groups.
In the previous example, the polarization between liberal and conservative
blogs is already visible without any partition, but a force-directed layout
that only uses the edges does not show how these two groups are divided
further. However, hfd_layout() also accepts a
hierarchical partition of the vertices via the b parameter, in which case
the groups at every level of the hierarchy are laid out first and kept
together. A partition that reflects the structure of the network is obtained
by fitting the nested stochastic block model (see Inferring modular network structure),
which we do here for the same network, again without and with the weights:
state = gt.minimize_nested_blockmodel_dl(g)
pos = None
for name, vweight in [("sbm", None), ("sbm-vweight", w)]:
pos = gt.hfd_layout(g, pos=pos, b=state.get_bs(), vweight=vweight)
gt.graph_draw(g, pos, vertex_size=size, vertex_fill_color=g.vp.value,
vcmap=leaning, vorder=deg, edge_color=(.2, .2, .2, .05),
edge_trim=True, output_size=(400, 400),
output=f"polblogs-{name}.svg")
The groups of the partition now appear as separate clusters, arranged according to the hierarchy, with the liberal and conservative blogs in different branches. As before, the weights spread apart the vertices of large degree, which in our measurements reduced the number of overlapping pairs of vertices by a factor of about ten.
Layout with the hierarchical partition |
Layout with the partition and |
Hierarchical layouts#
The layouts of the previous section use a hierarchical partition only to keep
the groups of vertices together. The function
draw_hierarchy() instead draws the hierarchy itself,
given by a NestedBlockState, as a tree whose
leaves are the vertices of the graph and whose internal nodes are the groups
at each level. With the default layout="radial", the tree is laid out by
radial_tree_layout(), with the root at the center, the
groups of each level on a circle, and the vertices on the outermost circle,
where each group occupies an angle proportional to its number of vertices.
The vertices of a group are therefore placed next to each other, as in the
drawing of the football network above,
and the groups that are close in the hierarchy are also close on the circle.
The edges are drawn as splines whose control points follow the path between
their endpoints in the tree, so that the edges between the same branches of
the hierarchy are bundled together [1],
with a strength given by the parameter beta (between 0 and 1). For the
football network, we obtain the hierarchy by fitting the nested stochastic
block model, and draw it with the team names placed outside the circle via
text_position="centered", which rotates them radially:
g = gt.collection.data["football"]
state = gt.minimize_nested_blockmodel_dl(g)
state.draw(vertex_fill_color=g.vp.value, vertex_color=g.vp.value,
vertex_text=g.vp.label, vertex_text_position="centered",
vertex_font_size=7, output_size=(500, 500),
output="football-hierarchy.svg")
By default, the vertices are filled and outlined with the colors of their
groups at the lowest level of the hierarchy, and each edge is drawn with a
color gradient between the fill colors of its endpoints. Here we color the
vertices according to their conferences instead, so that the inferred groups,
whose vertices are adjacent on the circle, can be compared with them. Most
conferences occupy contiguous arcs, since they mostly coincide with the
inferred groups, and the edges between conferences are bundled along the
upper levels of the hierarchy. The positions of the
vertices and of the nodes of the hierarchy tree are returned by
draw_hierarchy(), and can be reused in other drawings.
Hierarchical partition of the network of American college football games,
inferred with the nested stochastic block model and drawn with
draw_hierarchy(). The vertex colors indicate the
conferences, as in the previous drawing,
and the edges are drawn with gradients between the colors of their
endpoints. The nodes of the hierarchy tree are drawn as blue squares.#
Other layouts of the tree are chosen with the parameter layout. For a
bipartite network, layout="bipartite" places the vertices of the two kinds
on two vertical lines, and the groups of the hierarchy of each kind between
them, at horizontal positions given by their levels. The edges then go from
the groups of one side directly to those of the other, and the order of the
groups and of the vertices is chosen to reduce the number of edge crossings.
The two kinds of vertices are kept in separate groups during the inference by
passing them as the pclabel parameter of the state, and bip_left chooses
which kind is drawn on the left. We illustrate this with the network of
animals and their attributes in the UCI zoo data set (uci_zoo), where
we fill the animals with the colors of their types, and the attributes in
gray:
g = gt.collection.ns["uci_zoo"]
state = gt.minimize_nested_blockmodel_dl(
g, state_args=dict(pclabel=g.vp.is_attribute.copy("int")))
# Pastel versions of the colors of the palette Set1, ordered by the number
# of animals of each type.
types = ["mammal", "bird", "fish", "invertebrate", "insect", "reptile",
"amphibian"]
colors = ["#9bbedc", "#f28c8e", "#a6d7a4", "#cca6d1", "#ffbf80", "#d2aa93",
"#ffff99"]
fill = g.new_vp("string", vals=["#cccccc" if g.vp.is_attribute[v] else
colors[types.index(g.vp.type_name[v])]
for v in g.vertices()])
state.draw(layout="bipartite", bip_left=1, bip_aspect=.5,
vertex_fill_color=fill, vertex_color=fill, vertex_text=g.vp.name,
vertex_text_position="centered", vertex_font_size=7,
output_size=(450, 900), output="zoo-hierarchy.svg")
Since pclabel must be an integer property map, the Boolean property
is_attribute is converted with copy(), and
its value 1 puts the attributes on the left. The inferred partition separates
the birds and most of the mammals into groups of their own, together with
the attributes that characterize them, such as feathers, airborne, and
legs=2 for the birds, whereas the remaining animals form a single group.
With bip_aspect=.5, the layout is twice as tall as it is wide, which leaves
room for the names of the animals.
Hierarchical partition of the network of animals (right) and their
attributes (left) in the UCI zoo data set, drawn with
layout="bipartite". The animals are filled with the colors of their types
(mammals in blue, birds in red, fish in green, invertebrates in purple,
insects in orange, reptiles in brown, and amphibians in yellow), and the
attributes in gray.#
Large graphs#
Tip
A part of a graph can also be drawn by filtering it with a
GraphView (see Sec. Graph filtering of the
quick start guide), e.g. keeping only the vertices with a degree above some
threshold, while keeping the positions of the full layout.
The time needed to draw a graph grows with its number of vertices and edges,
and with the cost of drawing each of them, where for large graphs the latter
is dominated by the clipping of the edges described above. However, when the
vertices are smaller than a pixel, the clipped parts of the lines are not
visible anyway. For this reason, if both endpoints of an edge are vertices
smaller than the value of the res parameter (in the units of the output),
the edge is drawn as if sloppy=True, and likewise seamless is ignored for
markers smaller than res. When drawing to a file, the default value is
res=2, which speeds up the drawing of large graphs with hardly any visible
difference, whereas res=0 restores the exact drawing of every edge. The
edges between larger vertices can be drawn faster with edge_trim=True. For a
triangulation with \(10^5\) vertices and \(3\times 10^5\) edges, drawn with
res=0, this reduced the size of an SVG file from 451 to 133 MB.
Note
The size of a file in a vector format (PDF, SVG, PostScript) grows with the number of vertices and edges, and such files can be slow to display. For graphs with many thousands of edges, PNG images are usually preferable.
As an example, we draw the network of mutual likes between Facebook pages
(facebook_pages, in its subnetwork musae), with \(N=22{,}470\)
vertices and \(E=171{,}002\) edges, using thin and translucent edges, so that
the regions where they concentrate remain visible, and small vertices, so
that they do not hide the edges. The pages belong to four categories, which
we draw in different colors (companies in blue, government in red,
politicians in green, and TV shows in purple):
g = gt.collection.ns["facebook_pages/musae"]
pos = gt.hfd_layout(g)
deg = g.degree_property_map("total")
# The categories are numbered in alphabetical order.
kinds = sorted(set(g.vp.page_type))
kind = g.new_vp("int", vals=[kinds.index(k) for k in g.vp.page_type])
kcmap = matplotlib.colors.ListedColormap(["#9bbedc", "#f28c8e", "#a6d7a4",
"#cca6d1"])
size = gt.prop_to_size(deg, .3, 4, log=True)
gt.graph_draw(g, pos, vertex_size=size, vertex_fill_color=kind, vcmap=kcmap,
vorder=deg, vertex_pen_width=.2, vertex_color=(.3, .3, .3, .6),
edge_color=(.2, .2, .2, .1), edge_pen_width=.3, edge_trim=True,
output_size=(800, 800), output="facebook-pages.png")
Although the layout only uses the edges, the four categories occupy distinct
regions, since 89% of the edges connect pages of the same category. However,
within these regions the vertices are spread out uniformly, and the finer
structure of the network is not visible. As in the previous section, a
hierarchical partition obtained with the nested stochastic block model
reveals it, when passed to hfd_layout():
state = gt.minimize_nested_blockmodel_dl(g)
pos_sbm = gt.hfd_layout(g, b=state.get_bs())
gt.graph_draw(g, pos_sbm, vertex_size=size, vertex_fill_color=kind,
vcmap=kcmap, vorder=deg, vertex_pen_width=.2,
vertex_color=(.3, .3, .3, .6), edge_color=(.2, .2, .2, .1),
edge_pen_width=.3, edge_trim=True, output_size=(800, 800),
output="facebook-pages-sbm.png")
The partition has several hundred groups at its lowest level, which appear as separate clusters of vertices, most of them of a single category, connected by bundles of edges.
Layout with |
Layout with the hierarchical partition |
|
|
We can show a part of a large graph by passing as fit_view a tuple
(x, y, w, h) with the rectangle of the layout that is drawn. The vertices
and edges that lie entirely outside of it are skipped, so that zooming into a
small part of a large graph is fast. Here we zoom into a square at the center
of the first layout above, with a side of a tenth of its width:
x, y = pos.get_2d_array()
w = np.ptp(x) / 10
x, y = x.mean() - w / 2, y.mean() - w / 2
gt.graph_draw(g, pos, vertex_size=gt.prop_to_size(deg, 2, 15, log=True),
vertex_fill_color=kind, vcmap=kcmap, vorder=deg,
edge_color=(.2, .2, .2, .3), edge_pen_width=.5, edge_trim=True,
fit_view=(x, y, w, w), output_size=(600, 600),
output="facebook-pages-zoom.png")
In the zoomed image we can distinguish the vertices of high degree, drawn on
top because of vorder=deg, together with their edges.
Central region of the network of mutual likes between Facebook pages, covering a tenth of the width of the layout obtained without the partition, with the same vertex colors as before, and the vertex sizes scaled up.#
Drawing on a cairo context#
Note
With the parameter max_render_time, cairo_draw()
returns an iterator that draws the graph in steps of at most this many
milliseconds, which is how the interactive window remains responsive while
large graphs are drawn.
The function graph_draw() creates a cairo surface and
context, fits the view, chooses the default sizes, and then calls
cairo_draw(), which performs the actual drawing on a
given cairo.Context. We can also use the latter function directly,
for instance to combine several graphs, or graphs and other elements, in the
same drawing. It accepts the same vertex and edge properties, but makes none
of the automatic adjustments. The positions are taken in the user coordinates
of the context, and can be transformed with the usual cairo methods, whereas
the sizes are in the units of the surface, with the fixed default values
listed in graph_draw(). In the following example, we
draw two graphs side by side, each with a title, namely the karate club
network used above and the network of associations between bottlenose
dolphins (dolphins):
import cairo
graphs = [gt.collection.data[name] for name in ["karate", "dolphins"]]
# The layouts are scaled to a width of 240 points, and the height of the
# surface is chosen to fit the tallest of them, below the titles.
xy = [g.vp.pos.get_2d_array() for g in graphs]
scales = [240 / np.ptp(x) for x, y in xy]
height = np.max([s * np.ptp(y) for (x, y), s in zip(xy, scales)])
surface = cairo.SVGSurface("two-graphs.svg", 600, height + 70)
cr = cairo.Context(surface)
# Pastel versions of the blue and red of the palette Set1.
colors = ["#9bbedc", "#f28c8e"]
for i, (name, g) in enumerate(zip(["karate", "dolphins"], graphs)):
(x, y), s = xy[i], scales[i]
# Each layout is placed at the left or the right half of the surface.
cr.save()
cr.translate(300 * i + 30, 55)
cr.scale(s, s)
cr.translate(-x.min(), -y.min())
gt.cairo_draw(g, g.vp.pos, cr, vertex_size=9,
vertex_fill_color=colors[i], vertex_color=colors[i],
edge_color=(.4, .4, .4, .7), edge_pen_width=1)
cr.restore()
# The title is centered above the layout.
cr.select_font_face("Times")
cr.set_font_size(18)
ext = cr.text_extents(name)
cr.move_to(300 * i + 150 - ext.x_bearing - ext.width / 2, 30)
cr.set_source_rgb(0, 0, 0)
cr.show_text(name)
surface.finish()
Networks of friendships in Zachary’s karate club (left) and of associations
between dolphins (right), drawn with cairo_draw() on
the same surface, with titles drawn directly with cairo.#
Interactive drawing and other interfaces#
If output is not given, graph_draw() shows the graph
with interactive_window(), which opens a
GTK window where the drawing can be panned, zoomed and
rotated, and where the user can select vertices and move them with the
mouse. If the positions are not given, the layout is computed while the
window is open, and its progress is shown. In the interactive window, the
value of res is five pixels, so that large graphs remain responsive. The
same functionality is provided by the classes
GraphWindow and
GraphWidget, and the latter can be embedded in
other GTK applications. The view and the selection of vertices are controlled
with the mouse and the keyboard, as summarized in the following table:
Control |
Action |
|---|---|
Scroll wheel |
Zoom around the pointer |
Shift + scroll wheel |
Zoom, and scale the sizes of vertices and edges with it |
Ctrl + scroll wheel |
Rotate the view around the pointer (in finer steps with Shift), or the selected group of vertices |
Middle button, or Ctrl + left button, dragged |
Pan the view |
Pinch |
Zoom around the center of the gesture, as with the scroll wheel |
Two-finger rotation |
Rotate the view around the center of the gesture |
One-finger drag (touchscreen) |
Pan the view |
Left button |
Enter the selection mode, picking the vertex closest to the pointer |
Left button dragged |
Move the selected vertex or group of vertices |
Shift + left button dragged |
Select the vertices inside a rectangle, adding them to the group (or removing them, if Ctrl is also held when the button is released) |
Right button |
Clear the group, or leave the selection mode |
|
Enter or leave the selection mode |
|
Fit the view to the selected group of vertices |
|
Fit the view to the whole graph |
|
Apply the current translation, zoom, and rotation to the positions |
|
Start the layout algorithm from the current positions, with a small random jitter that doubles at every press, and returns to its initial amplitude as the layout settles |
The view is a transformation of the drawing that leaves the positions
unchanged, unless they are moved or the transformation is applied with the
key a. In the selection mode, the vertex closest to the pointer is selected
as the pointer moves, and it is highlighted together with its neighbors and
its edges, so that the neighborhoods of the vertices can be inspected one at
a time. A group of vertices is selected by dragging rectangles with the Shift
key held, after which the selection no longer follows the pointer, and the
group can be moved and rotated as a whole, or zoomed into with the key z.
The vertices that are selected keep their positions while the layout
algorithm runs, so that the user can place some vertices by hand and let the
layout adapt the others to them. When the window is closed,
graph_draw() returns the positions, including
the changes made in the window, together with a Boolean vertex property map
that marks the selected vertices. Other actions can be bound to the keys and
to the changes of the layout via the key_press_callback and
layout_callback parameters of GraphWidget.
The drawing described in this guide is also used elsewhere in the library,
with the same vertex and edge properties. The function
draw_hierarchy() draws a hierarchical partition given
by a NestedBlockState (see Sec.
Hierarchical layouts), and is used together with
graph_draw() by the draw() methods of the inference
states (see Inferring modular network structure). The class
GraphArtist places the drawings in matplotlib
figures (see Integration with matplotlib), and animations are made by updating an
interactive window, or by drawing the frames to files (see
Animations with graph-tool).
Overview of the vertex and edge properties#
The following tables list all vertex and edge properties, which are passed as
vertex_<name> and edge_<name>, or via vprops and eprops, together with
the figures of this guide where they are used. Their accepted types and default
values are given in the documentation of graph_draw().
Vertex properties#
Property |
Controls |
Used in |
|---|---|---|
|
Shape of the vertex |
|
|
Color of the contour |
|
|
Color of the interior |
|
|
Size, in the units of the output, or of the layout with |
|
|
Width of the contour |
|
|
Horizontal stretch of the shape |
|
|
Rotation of the shape, in radians |
|
|
Edges end at the border ( |
|
|
Slices of the vertices with |
|
|
Image drawn in place of the shape |
|
|
Translucent disk behind the vertex |
|
|
Label |
|
|
Placement of the label, inside or outside the vertex |
|
|
Displacement of the label |
|
|
Rotation of the label, in radians |
|
|
Color of the label, or |
|
|
Outline of the label |
|
|
Font of the label |
|
|
Position in the drawing order of all vertices and edges |
|
|
Position of the label in the drawing order |
Edge properties#
Property |
Controls |
Used in |
|---|---|---|
|
Color of the line |
|
|
Width of the line |
|
|
Dash pattern, as lengths of the drawn and skipped parts and an offset |
|
|
Color gradient along the line |
|
|
Markers at the start, middle, and end |
|
|
Relative position of the middle marker |
|
|
Size of the markers |
|
|
Bézier curve of the line |
|
|
Removal of the hidden parts of the line |
|
|
Label |
|
|
Distance between the label and the line |
|
|
Label drawn parallel to the line or horizontally |
|
|
Color of the label, or |
|
|
Outline of the label |
|
|
Font of the label |
|
|
Position in the drawing order of all vertices and edges |
|
|
Position of the label in the drawing order |
Sec. Drawing order |
References#
D. Holten. Hierarchical Edge Bundles: Visualization of Adjacency Relations in Hierarchical Data. IEEE Transactions on Visualization and Computer Graphics, 12(5):741–748, 2006. doi:10.1109/TVCG.2006.147, [sci-hub].

