A graph is a structure that represents data in terms of vertices and edges. A graph is represented as aGraph = (?, ?), where ? represents a set of vertices and ? represents a set of edges. Note that aGraph has |?| vertices and |?| edges.
A vertex, ? ∈ ?, represents a real-world object, such as a person, a computer, or an activity. An edge, ? ∈ ?, connects two vertices in a network:
e(?1, ?2) | e ∈ ? & ?i ∈ ?
The preceding equation indicates that in a graph, all edges belong to a set, ?, and all vertices belong to a set, ?.
An edge connects two vertices and so represents a relationship between them. For example, it can represent the following relationships:
- Friendships between people
- A person connected to a friend on LinkedIn
- A physical connection of two nodes in a cluster
- A person attending a research conference
In this chapter, we will be using the networkx Python package to represent graphs. Let's try to create a simple graph using the networtx package in Python. To begin with, let's try to create an empty graph, aGraph, with no vertex or node:
import networkx as nx
G = nx.Graph()
Let's add a single vertex:
G.add_node("Mike")
We can also add a bunch of vertices using a list:
G.add_nodes_from(["Amine", "Wassim", "Nick"])
We can also add one edge between the existing vertices, as shown:
G.add_edge("Mike", "Amine")
Let's now print the edges and vertices:
Please note that if we are adding an edge, this also leads to adding the associated vertices, if they do not already exist, as shown here:
G.add_edge("Amine","Imran")
If we print the list of nodes, the following is the output that we observe:
Note that the request to add a vertex that already exists is silently ignored. The request is ignored or entertained based on the type of graph we have created.