matplotlib.rst 2.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
Integration with matplotlib
===========================

The drawing capabilities of ``graph-tool`` (see :mod:`~graph_tool.draw`
module) can be integrated with `matplotlib <https://matplotlib.org>`_,
as we demonstrate in the following.

.. note::

   Since ``graph-tool`` uses `cairo <https://cairographics.org>`_ for
Tiago Peixoto's avatar
Tiago Peixoto committed
11
12
13
14
15
   drawing, it is necessary to one of matplotlib's cairo-based backend,
   otherwise integration is not possible. Currently, two backends can be
   chosen: ``cairo`` or ``GTK3Cairo``. The latter should be chosen for
   interactive GUI-based figures. The backend can be changed by calling
   :func:`matplotlib.pyplot.switch_backend`:
16
17
18

   .. code::

Tiago Peixoto's avatar
Tiago Peixoto committed
19
20
21
      import matplotlib.pyplot as plt

      plt.switch_backend("cairo")
22
23
24
25
26
27
28
29


Drawing with matplotlib is done by calling
:func:`~graph_tool.draw.graph_draw` and passing a container (e.g.
:class:`matplotlib.axes.Axes`) as the ``mplfig`` parameter. For example:

.. testsetup::

Tiago Peixoto's avatar
Tiago Peixoto committed
30
31
   import matplotlib
   backend = matplotlib.get_backend()
32
33
34
35
   gt.seed_rng(44)
   
.. testcode::

Tiago Peixoto's avatar
Tiago Peixoto committed
36
37
38
39
   import graph_tool.all as gt
   import matplotlib.pyplot as plt

   plt.switch_backend("cairo")
40

Tiago Peixoto's avatar
Tiago Peixoto committed
41
   fig, ax = plt.subplots(2, 2, figsize=(12, 11.5)) 
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

   g = gt.collection.data["polbooks"]

   gt.graph_draw(g, g.vp.pos, vertex_size=1.5, mplfig=ax[0,0])

   ax[0,0].set_xlabel("$x$ coordinate")
   ax[0,0].set_ylabel("$y$ coordinate")

   state = gt.minimize_nested_blockmodel_dl(g)

   state.draw(mplfig=ax[0,1])

   ax[0,1].set_xlabel("$x$ coordinate")
   ax[0,1].set_ylabel("$y$ coordinate")

   g = gt.collection.data["lesmis"]
   gt.graph_draw(g, g.vp.pos, vertex_size=1.5, mplfig=ax[1,0])

   ax[1,0].set_xlabel("$x$ coordinate")
   ax[1,0].set_ylabel("$y$ coordinate")

   state = gt.minimize_nested_blockmodel_dl(g)

   state.draw(mplfig=ax[1,1])

   ax[1,1].set_xlabel("$x$ coordinate")
   ax[1,1].set_ylabel("$y$ coordinate")

Tiago Peixoto's avatar
Tiago Peixoto committed
70
   plt.subplots_adjust(left=0.08, right=0.99, top=0.99, bottom=0.06)
71
72
73
74
   fig.savefig("gt-mpl.pdf")

.. testcleanup::

Tiago Peixoto's avatar
Tiago Peixoto committed
75
   plt.switch_backend(backend)
76
77
78
79
80
81
   conv_png("gt-mpl.pdf")

.. figure:: gt-mpl.png
   :width: 90%

   Four subplots showing networks drawn using graph-tool.