Cara menggunakan undirected graph python

By definition, a is a collection of nodes (vertices) along with identified pairs of nodes (called edges, links, etc). In NetworkX, nodes can be any object e.g., a text string, an image, an XML object, another Graph, a customized node object, etc.

Note

Python’s

>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
1 object is not allowed to be used as a node. It determines whether optional function arguments have been assigned in many functions.

Nodes

The graph

>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
2 can be grown in several ways. NetworkX includes many graph generator functions and facilities to read and write graphs in many formats. To get started though we’ll look at simple manipulations. You can add one node at a time,

>>> G.add_node(1)

or add nodes from any container, such as a list

>>> G.add_nodes_from([2, 3])

You can also add nodes along with node attributes if your container yields 2-tuples of the form

>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
3:

>>> G.add_nodes_from([
...     (4, {"color": "red"}),
...     (5, {"color": "green"}),
... ])

Node attributes are discussed further .

Nodes from one graph can be incorporated into another:

>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)

>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
2 now contains the nodes of
>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
5 as nodes of
>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
2. In contrast, you could use the graph
>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
5 as a node in
>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
2.

>>> G.add_node(H)

The graph

>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
2 now contains
>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
5 as a node. This flexibility is very powerful as it allows graphs of graphs, graphs of files, graphs of functions and much more. It is worth thinking about how to structure your application so that the nodes are useful entities. Of course you can always use a unique identifier in
>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
2 and have a separate dictionary keyed by identifier to the node information if you prefer.

Note

You should not change the node object if the hash depends on its contents.

Edges

>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
2 can also be grown by adding one edge at a time,

>>> G.add_edge(1, 2)
>>> e = (2, 3)
>>> G.add_edge(*e)  # unpack edge tuple*

by adding a list of edges,

>>> G.add_edges_from([(1, 2), (1, 3)])

or by adding any of edges. An ebunch is any iterable container of edge-tuples. An edge-tuple can be a 2-tuple of nodes or a 3-tuple with 2 nodes followed by an edge attribute dictionary, e.g.,

>>> G.add_node(H)
3. Edge attributes are discussed further .

>>> G.add_edges_from(H.edges)

There are no complaints when adding existing nodes or edges. For example, after removing all nodes and edges,

>>> G.clear()

we add new nodes/edges and NetworkX quietly ignores any that are already present.

>>> G.add_node(1)
0

At this stage the graph

>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
2 consists of 8 nodes and 3 edges, as can be seen by:

>>> G.add_node(1)
1

Note

The order of adjacency reporting (e.g., , , ) is the order of edge addition. However, the order of G.edges is the order of the adjacencies which includes both the order of the nodes and each node’s adjacencies. See example below:

>>> G.add_node(1)
2

Examining elements of a graph

We can examine the nodes and edges. Four basic graph properties facilitate reporting:

>>> G.add_node(H)
8,
>>> G.add_node(H)
9,
>>> G.add_node(H)
5 and
>>> G.add_edge(1, 2)
>>> e = (2, 3)
>>> G.add_edge(*e)  # unpack edge tuple*
1. These are set-like views of the nodes, edges, neighbors (adjacencies), and degrees of nodes in a graph. They offer a continually updated read-only view into the graph structure. They are also dict-like in that you can look up node and edge data attributes via the views and iterate with data attributes using methods
>>> G.add_edge(1, 2)
>>> e = (2, 3)
>>> G.add_edge(*e)  # unpack edge tuple*
2,
>>> G.add_edge(1, 2)
>>> e = (2, 3)
>>> G.add_edge(*e)  # unpack edge tuple*
3. If you want a specific container type instead of a view, you can specify one. Here we use lists, though sets, dicts, tuples and other containers may be better in other contexts.

>>> G.add_node(1)
3

One can specify to report the edges and degree from a subset of all nodes using an . An nbunch is any of:

>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
1 (meaning all nodes), a node, or an iterable container of nodes that is not itself a node in the graph.

>>> G.add_node(1)
4

Removing elements from a graph

One can remove nodes and edges from the graph in a similar fashion to adding. Use methods , , and , e.g.

>>> G.add_node(1)
5

Using the graph constructors

Graph objects do not have to be built up incrementally - data specifying graph structure can be passed directly to the constructors of the various graph classes. When creating a graph structure by instantiating one of the graph classes you can specify data in several formats.

>>> G.add_node(1)
6

What to use as nodes and edges

You might notice that nodes and edges are not specified as NetworkX objects. This leaves you free to use meaningful items as nodes and edges. The most common choices are numbers or strings, but a node can be any hashable object (except

>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
1), and an edge can be associated with any object
>>> G.add_edges_from([(1, 2), (1, 3)])
0 using
>>> G.add_edges_from([(1, 2), (1, 3)])
1.

As an example,

>>> G.add_edges_from([(1, 2), (1, 3)])
2 and
>>> G.add_edges_from([(1, 2), (1, 3)])
3 could be protein objects from the RCSB Protein Data Bank, and
>>> G.add_edges_from([(1, 2), (1, 3)])
0 could refer to an XML record of publications detailing experimental observations of their interaction.

We have found this power quite useful, but its abuse can lead to surprising behavior unless one is familiar with Python. If in doubt, consider using to obtain a more traditional graph with integer labels.

Accessing edges and neighbors

In addition to the views , and , access to edges and neighbors is possible using subscript notation.

>>> G.add_node(1)
7

You can get/set the attributes of an edge using subscript notation if the edge already exists.

>>> G.add_node(1)
8

Fast examination of all (node, adjacency) pairs is achieved using

>>> G.add_edges_from([(1, 2), (1, 3)])
8, or
>>> G.add_edges_from([(1, 2), (1, 3)])
9. Note that for undirected graphs, adjacency iteration sees each edge twice.

>>> G.add_node(1)
9

Convenient access to all edges is achieved with the edges property.

>>> G.add_nodes_from([2, 3])
0

Adding attributes to graphs, nodes, and edges

Attributes such as weights, labels, colors, or whatever Python object you like, can be attached to graphs, nodes, or edges.

Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys must be hashable). By default these are empty, but attributes can be added or changed using

>>> G.add_edges_from(H.edges)
0,
>>> G.add_edges_from(H.edges)
1 or direct manipulation of the attribute dictionaries named
>>> G.add_edges_from(H.edges)
2,
>>> G.add_node(H)
8, and
>>> G.add_node(H)
9 for a graph
>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
2.

Graph attributes

Assign graph attributes when creating a new graph

>>> G.add_nodes_from([2, 3])
1

Or you can modify attributes later

>>> G.add_nodes_from([2, 3])
2

Node attributes

Add node attributes using

>>> G.add_edges_from(H.edges)
6,
>>> G.add_edges_from(H.edges)
7, or
>>> G.add_node(H)
8

>>> G.add_nodes_from([2, 3])
3

Note that adding a node to

>>> G.add_node(H)
8 does not add it to the graph, use
>>> G.clear()
0 to add new nodes. Similarly for edges.

Edge Attributes

Add/change edge attributes using

>>> G.clear()
1,
>>> G.clear()
2, or subscript notation.

>>> G.add_nodes_from([2, 3])
4

The special attribute

>>> G.clear()
3 should be numeric as it is used by algorithms requiring weighted edges.

Directed graphs

The class provides additional methods and properties specific to directed edges, e.g., , , , etc. To allow algorithms to work with both classes easily, the directed versions of is equivalent to while reports the sum of and even though that may feel inconsistent at times.

>>> G.add_nodes_from([2, 3])
5

Some algorithms work only for directed graphs and others are not well defined for directed graphs. Indeed the tendency to lump directed and undirected graphs together is dangerous. If you want to treat a directed graph as undirected for some measurement you should probably convert it using or with

>>> G.add_nodes_from([2, 3])
6

Multigraphs

NetworkX provides classes for graphs which allow multiple edges between any pair of nodes. The and classes allow you to add the same edge twice, possibly with different edge data. This can be powerful for some applications, but many algorithms are not well defined on such graphs. Where results are well defined, e.g., we provide the function. Otherwise you should convert to a standard graph in a way that makes the measurement well defined.

>>> G.add_nodes_from([2, 3])
7

Graph generators and graph operations

In addition to constructing graphs node-by-node or edge-by-edge, they can also be generated by

1. Applying classic graph operations, such as:

(G, nbunch)

Returns the subgraph induced on nodes in nbunch.

(G, H[, rename])

Combine graphs G and H.

(G, H)

Combine graphs G and H.

(G, H)

Returns the Cartesian product of G and H.

(G, H)

Compose graph G with H by combining nodes and edges into a single graph.

(G)

Returns the graph complement of G.

(G[, with_data])

Returns a copy of the graph G with all of the edges removed.

(graph)

Returns an undirected view of the graph

>>> G.add_node(1)
16.

(graph)

Returns a directed view of the graph

>>> G.add_node(1)
16.

2. Using a call to one of the classic small graphs, e.g.,

([create_using])

Returns the Petersen graph.

([create_using])

Returns the Tutte graph.

([create_using])

Return a small maze with a cycle.

([create_using])

Returns the 3-regular Platonic Tetrahedral graph.

3. Using a (constructive) generator for a classic graph, e.g.,

(n[, create_using])

Return the complete graph

>>> G.add_node(1)
24 with n nodes.

(n1, n2[, create_using])

Returns the complete bipartite graph

>>> G.add_node(1)
26.

(m1, m2[, create_using])

Returns the Barbell Graph: two complete graphs connected by a path.

(m, n[, create_using])

Returns the Lollipop Graph;

>>> G.add_node(1)
29 connected to
>>> G.add_node(1)
30.

like so:

>>> G.add_nodes_from([2, 3])
8

4. Using a stochastic graph generator, e.g,

(n, p[, seed, directed])

Returns a \(G_{n,p}\) random graph, also known as an Erdős-Rényi graph or a binomial graph.

(n, k, p[, seed])

Returns a Watts–Strogatz small-world graph.

(n, m[, seed, ...])

Returns a random graph using Barabási–Albert preferential attachment

(n, p1, p2[, seed])

Returns a random lobster graph.

like so:

>>> G.add_nodes_from([2, 3])
9

5. Reading a graph stored in a file using common graph formats

NetworkX supports many popular formats, such as edge lists, adjacency lists, GML, GraphML, LEDA and others.

>>> G.add_nodes_from([
...     (4, {"color": "red"}),
...     (5, {"color": "green"}),
... ])
0

For details on graph formats see Reading and writing graphs and for graph generator functions see Graph generators

Analyzing graphs

The structure of

>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
2 can be analyzed using various graph-theoretic functions such as:

>>> G.add_nodes_from([
...     (4, {"color": "red"}),
...     (5, {"color": "green"}),
... ])
1

Some functions with large output iterate over (node, value) 2-tuples. These are easily stored in a structure if you desire.

>>> G.add_nodes_from([
...     (4, {"color": "red"}),
...     (5, {"color": "green"}),
... ])
2

See Algorithms for details on graph algorithms supported.

Drawing graphs

NetworkX is not primarily a graph drawing package but basic drawing with Matplotlib as well as an interface to use the open source Graphviz software package are included. These are part of the networkx.drawing module and will be imported if possible.

First import Matplotlib’s plot interface (pylab works too)

>>> G.add_nodes_from([
...     (4, {"color": "red"}),
...     (5, {"color": "green"}),
... ])
3

To test if the import of was successful draw

>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
2 using one of

>>> G.add_nodes_from([
...     (4, {"color": "red"}),
...     (5, {"color": "green"}),
... ])
4

(png, hires.png, pdf)

Cara menggunakan undirected graph python

when drawing to an interactive display. Note that you may need to issue a Matplotlib

>>> G.add_nodes_from([
...     (4, {"color": "red"}),
...     (5, {"color": "green"}),
... ])
5

command if you are not using matplotlib in interactive mode.

>>> G.add_nodes_from([
...     (4, {"color": "red"}),
...     (5, {"color": "green"}),
... ])
6

(png, hires.png, pdf)

Cara menggunakan undirected graph python

You can find additional options via and layouts via the . You can use multiple shells with .

>>> G.add_nodes_from([
...     (4, {"color": "red"}),
...     (5, {"color": "green"}),
... ])
7

(png, hires.png, pdf)

Cara menggunakan undirected graph python

To save drawings to a file, use, for example

>>> G.add_nodes_from([
...     (4, {"color": "red"}),
...     (5, {"color": "green"}),
... ])
8

This function writes to the file

>>> G.add_node(1)
42 in the local directory. If Graphviz and PyGraphviz or pydot, are available on your system, you can also use or to get the node positions, or write the graph in dot format for further processing.