manim.mobject.graph.Graph

class Graph(vertices, edges, labels=False, label_fill_color='#000000', layout='spring', layout_scale=2, layout_config=None, vertex_type=<class 'manim.mobject.geometry.Dot'>, vertex_config=None, vertex_mobjects=None, edge_type=<class 'manim.mobject.geometry.Line'>, partitions=None, root_vertex=None, edge_config=None)[source]

Bases: manim.mobject.types.vectorized_mobject.VMobject

An undirected graph (that is, a collection of vertices connected with edges).

Graphs can be instantiated by passing both a list of (distinct, hashable) vertex names, together with list of edges (as tuples of vertex names). See the examples below for details.

Note

This implementation uses updaters to make the edges move with the vertices.

Parameters
  • vertices (List[Hashable]) – A list of vertices. Must be hashable elements.

  • edges (List[Tuple[Hashable, Hashable]]) – A list of edges, specified as tuples (u, v) where both u and v are vertices.

  • labels (bool) – Controls whether or not vertices are labeled. If False (the default), the vertices are not labeled; if True they are labeled using their names (as specified in vertices) via MathTex. Alternatively, custom labels can be specified by passing a dictionary whose keys are the vertices, and whose values are the corresponding vertex labels (rendered via, e.g., Text or Tex).

  • label_fill_color (str) – Sets the fill color of the default labels generated when labels is set to True. Has no effect for other values of labels.

  • layout (Union[str, dict]) – Either one of "spring" (the default), "circular", "kamada_kawai", "planar", "random", "shell", "spectral", "spiral", "tree", and "partite" for automatic vertex positioning using networkx (see their documentation for more details), or a dictionary specifying a coordinate (value) for each vertex (key) for manual positioning.

  • layout_scale (float) – The scale of automatically generated layouts: the vertices will be arranged such that the coordinates are located within the interval [-scale, scale]. Default: 2.

  • layout_config (Optional[dict]) – Only for automatically generated layouts. A dictionary whose entries are passed as keyword arguments to the automatic layout algorithm specified via layout of``networkx``.

  • vertex_type (Type[Mobject]) – The mobject class used for displaying vertices in the scene.

  • vertex_config (Optional[dict]) – Either a dictionary containing keyword arguments to be passed to the class specified via vertex_type, or a dictionary whose keys are the vertices, and whose values are dictionaries containing keyword arguments for the mobject related to the corresponding vertex.

  • vertex_mobjects (Optional[dict]) – A dictionary whose keys are the vertices, and whose values are mobjects to be used as vertices. Passing vertices here overrides all other configuration options for a vertex.

  • edge_type (Type[Mobject]) – The mobject class used for displaying edges in the scene.

  • edge_config (Optional[dict]) – Either a dictionary containing keyword arguments to be passed to the class specified via edge_type, or a dictionary whose keys are the edges, and whose values are dictionaries containing keyword arguments for the mobject related to the corresponding edge.

  • partitions (Optional[List[List[Hashable]]]) –

  • root_vertex (Optional[Hashable]) –

Return type

None

Examples

First, we create a small graph and demonstrate that the edges move together with the vertices.

Example: MovingVertices

from manim import *

class MovingVertices(Scene):
    def construct(self):
        vertices = [1, 2, 3, 4]
        edges = [(1, 2), (2, 3), (3, 4), (1, 3), (1, 4)]
        g = Graph(vertices, edges)
        self.play(Create(g))
        self.wait()
        self.play(g[1].animate.move_to([1, 1, 0]),
                  g[2].animate.move_to([-1, 1, 0]),
                  g[3].animate.move_to([1, -1, 0]),
                  g[4].animate.move_to([-1, -1, 0]))
        self.wait()

There are several automatic positioning algorithms to choose from:

Example: GraphAutoPosition

../_images/GraphAutoPosition-1.png
from manim import *

class GraphAutoPosition(Scene):
    def construct(self):
        vertices = [1, 2, 3, 4, 5, 6, 7, 8]
        edges = [(1, 7), (1, 8), (2, 3), (2, 4), (2, 5),
                 (2, 8), (3, 4), (6, 1), (6, 2),
                 (6, 3), (7, 2), (7, 4)]
        autolayouts = ["spring", "circular", "kamada_kawai",
                       "planar", "random", "shell",
                       "spectral", "spiral"]
        graphs = [Graph(vertices, edges, layout=lt).scale(0.5)
                  for lt in autolayouts]
        r1 = VGroup(*graphs[:3]).arrange()
        r2 = VGroup(*graphs[3:6]).arrange()
        r3 = VGroup(*graphs[6:]).arrange()
        self.add(VGroup(r1, r2, r3).arrange(direction=DOWN))

Vertices can also be positioned manually:

Example: GraphManualPosition

../_images/GraphManualPosition-1.png
from manim import *

class GraphManualPosition(Scene):
    def construct(self):
        vertices = [1, 2, 3, 4]
        edges = [(1, 2), (2, 3), (3, 4), (4, 1)]
        lt = {1: [0, 0, 0], 2: [1, 1, 0], 3: [1, -1, 0], 4: [-1, 0, 0]}
        G = Graph(vertices, edges, layout=lt)
        self.add(G)

The vertices in graphs can be labeled, and configurations for vertices and edges can be modified both by default and for specific vertices and edges.

Note

In edge_config, edges can be passed in both directions: if (u, v) is an edge in the graph, both (u, v) as well as (v, u) can be used as keys in the dictionary.

Example: LabeledModifiedGraph

../_images/LabeledModifiedGraph-1.png
from manim import *

class LabeledModifiedGraph(Scene):
    def construct(self):
        vertices = [1, 2, 3, 4, 5, 6, 7, 8]
        edges = [(1, 7), (1, 8), (2, 3), (2, 4), (2, 5),
                 (2, 8), (3, 4), (6, 1), (6, 2),
                 (6, 3), (7, 2), (7, 4)]
        g = Graph(vertices, edges, layout="circular", layout_scale=3,
                  labels=True, vertex_config={7: {"fill_color": RED}},
                  edge_config={(1, 7): {"stroke_color": RED},
                               (2, 7): {"stroke_color": RED},
                               (4, 7): {"stroke_color": RED}})
        self.add(g)

You can also lay out a partite graph on columns by specifying a list of the vertices on each side and choosing the partite layout.

Note

All vertices in your graph which are not listed in any of the partitions are collected in their own partition and rendered in the rightmost column.

Example: PartiteGraph

../_images/PartiteGraph-1.png
from manim import *

import networkx as nx

class PartiteGraph(Scene):
    def construct(self):
        G = nx.Graph()
        G.add_nodes_from([0, 1, 2, 3])
        G.add_edges_from([(0, 2), (0,3), (1, 2)])
        graph = Graph(list(G.nodes), list(G.edges), layout="partite", partitions=[[0, 1]])
        self.play(Create(graph))

The custom tree layout can be used to show the graph by distance from the root vertex. You must pass the root vertex of the tree.

Example: Tree

from manim import *

from manim import *
import networkx as nx

class Tree(Scene):
    def construct(self):
        G = nx.Graph()

        G.add_node("ROOT")

        for i in range(5):
            G.add_node("Child_%i" % i)
            G.add_node("Grandchild_%i" % i)
            G.add_node("Greatgrandchild_%i" % i)

            G.add_edge("ROOT", "Child_%i" % i)
            G.add_edge("Child_%i" % i, "Grandchild_%i" % i)
            G.add_edge("Grandchild_%i" % i, "Greatgrandchild_%i" % i)

        self.play(Create(
            Graph(list(G.nodes), list(G.edges), layout="tree", root_vertex="ROOT")))

Methods

add_edges

Add new edges to the graph.

add_vertices

Add a list of vertices to the graph.

change_layout

Change the layout of this graph.

from_networkx

Build a Graph from a given networkx graph.

remove_edges

Remove several edges from the graph.

remove_vertices

Remove several vertices from the graph.

Attributes

animate

Used to animate the application of a method.

depth

The depth of the mobject.

height

The height of the mobject.

width

The width of the mobject.

add_edges(*edges, edge_type=<class 'manim.mobject.geometry.Line'>, edge_config=None)[source]

Add new edges to the graph.

Parameters
  • edges (List[Tuple[Hashable, Hashable]]) – The edge (as a tuple of vertex identifiers) to be added. If a non-existing vertex is passed, a new vertex with default settings will be created. Create new vertices yourself beforehand to customize them.

  • edge_type (Type[Mobject]) – The mobject class used for displaying edges in the scene.

  • edge_config (Optional[dict]) – A dictionary either containing keyword arguments to be passed to the class specified via edge_type, or a dictionary whose keys are the edge tuples, and whose values are dictionaries containing keyword arguments to be passed for the construction of the corresponding edge.

Returns

A group containing all newly added vertices and edges.

Return type

Group

add_vertices(*vertices, positions=None, labels=False, label_fill_color='#000000', vertex_type=<class 'manim.mobject.geometry.Dot'>, vertex_config=None, vertex_mobjects=None)[source]

Add a list of vertices to the graph.

Parameters
  • vertices (List[Hashable]) – A list of hashable vertex identifiers.

  • positions (Optional[dict]) – A dictionary specifying the coordinates where the new vertices should be added. If None, all vertices are created at the center of the graph.

  • labels (bool) – Controls whether or not the vertex is labeled. If False (the default), the vertex is not labeled; if True it is labeled using its names (as specified in vertex) via MathTex. Alternatively, any Mobject can be passed to be used as the label.

  • label_fill_color (str) – Sets the fill color of the default labels generated when labels is set to True. Has no effect for other values of labels.

  • vertex_type (Type[Mobject]) – The mobject class used for displaying vertices in the scene.

  • vertex_config (Optional[dict]) – A dictionary containing keyword arguments to be passed to the class specified via vertex_type.

  • vertex_mobjects (Optional[dict]) – A dictionary whose keys are the vertex identifiers, and whose values are mobjects that should be used as vertices. Overrides all other vertex customization options.

  • self (manim.mobject.graph.Graph) –

change_layout(layout='spring', layout_scale=2, layout_config=None, partitions=None, root_vertex=None)[source]

Change the layout of this graph.

See the documentation of Graph for details about the keyword arguments.

Examples

Example: ChangeGraphLayout

from manim import *

class ChangeGraphLayout(Scene):
    def construct(self):
        G = Graph([1, 2, 3, 4, 5], [(1, 2), (2, 3), (3, 4), (4, 5)],
                  layout={1: [-2, 0, 0], 2: [-1, 0, 0], 3: [0, 0, 0],
                          4: [1, 0, 0], 5: [2, 0, 0]}
                  )
        self.play(Create(G))
        self.play(G.animate.change_layout("circular"))
        self.wait()
Parameters
  • layout (Union[str, dict]) –

  • layout_scale (float) –

  • layout_config (Optional[dict]) –

  • partitions (Optional[List[List[Hashable]]]) –

  • root_vertex (Optional[Hashable]) –

Return type

manim.mobject.graph.Graph

static from_networkx(nxgraph, **kwargs)[source]

Build a Graph from a given networkx graph.

Parameters
  • nxgraph (networkx.classes.graph.Graph) – A networkx graph.

  • **kwargs – Keywords to be passed to the constructor of Graph.

Return type

manim.mobject.graph.Graph

Examples

Example: ImportNetworkxGraph

from manim import *

import networkx as nx

nxgraph = nx.erdos_renyi_graph(14, 0.5)

class ImportNetworkxGraph(Scene):
    def construct(self):
        G = Graph.from_networkx(nxgraph, layout="spring", layout_scale=3.5)
        self.play(Create(G))
        self.play(*[G[v].animate.move_to(5*RIGHT*np.cos(ind/7 * PI) +
                                         3*UP*np.sin(ind/7 * PI))
                    for ind, v in enumerate(G.vertices)])
        self.play(Uncreate(G))
remove_edges(*edges)[source]

Remove several edges from the graph.

Parameters

edges (List[Tuple[Hashable]]) – A list of edges to be removed from the graph.

Returns

A group containing all removed edges.

Return type

Group

remove_vertices(*vertices)[source]

Remove several vertices from the graph.

Parameters

vertices – A list of vertices to be removed from the graph.

Examples

>>> G = Graph([1, 2, 3], [(1, 2), (2, 3)])
>>> removed = G.remove_vertices(2, 3); removed
Group
>>> removed.submobjects
[Line, Line, Dot, Dot]
>>> G
Graph on 1 vertices and 0 edges