春江暮客

春江暮客的个人学习分享网站

Drawing NetworkX Network Graphs in python3

2019-01-12 Technology
Drawing NetworkX Network Graphs in python3

NetworkX is a Python library for working with graph structures and network relationships. It is useful for creating graphs, analyzing graph structure, and quickly drawing connection diagrams from tabular data.

With NetworkX, you can import graph data from multiple formats, generate classic graph structures, and combine it with matplotlib for practical visualizations.

This article focuses on three practical tasks:

  1. Draw a basic node-edge graph
  2. Style edges by weight and importance
  3. Change the figure background for presentation-friendly output

1. Drawing the Most Basic Network Graph

A network graph consists of nodes and edges. In NetworkX, each row of a pandas DataFrame represents the points in a connection, and a connection is generated at the corresponding position. In the example, a connection is generated between each corresponding position of ‘from’ and ’to’.

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

df = pd.DataFrame({
    'from': ['A', 'B', 'C', 'A'],
    'to': ['D', 'A', 'E', 'C']
})

basic_net = nx.from_pandas_edgelist(df, 'from', 'to')
fig = plt.figure()
nx.draw(basic_net, with_labels=True)
plt.show()

Drawing NetworkX Network Graphs in python3

Drawing a network graph using NetworkX only requires the simple steps above.

1. Importing Data

basic_net = nx.from_pandas_edgelist(df, 'from', 'to'). NetworkX supports multiple graph input formats, and the official convert documentation is the best place to explore alternatives such as adjacency-matrix import.

2. Drawing the Graph

nx.draw(basic_net, with_labels=True)

3. Display

plt.show()


2. Differentiating Connection Colors and Sizes Between Nodes

Since the importance of connections between different nodes varies, using line segments or colors of different sizes for connections becomes extremely important. NetworkX conveniently provides this function; you just need to specify edge_color during the drawing process.

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

df = pd.DataFrame({
    'from': ['A', 'B', 'C', 'A'],
    'to': ['D', 'A', 'E', 'C'],
    'value': [1, 10, 5, 5]
})

color_net = nx.from_pandas_edgelist(df, 'from', 'to', create_using=nx.Graph())
fig = plt.figure()
nx.draw(
    color_net,
    with_labels=True,
    node_color='skyblue',
    node_size=1500,
    edge_color=df['value'],
    width=10.0
)
plt.show()

Drawing NetworkX Network Graphs in python3 color_net


3. Setting Network Graph Background Color

In NetworkX, you can set the background color simply by using set_facecolor.

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

df = pd.DataFrame({
    'from': ['A', 'B', 'C', 'A'],
    'to': ['D', 'A', 'E', 'C'],
    'value': [1, 10, 5, 5]
})

color_net = nx.from_pandas_edgelist(df, 'from', 'to', create_using=nx.Graph())
fig = plt.figure()
nx.draw(
    color_net,
    with_labels=True,
    node_color='skyblue',
    node_size=1500,
    edge_color=df['value'],
    width=10.0
)
fig.set_facecolor("#AAAA00")
plt.show()

Drawing NetworkX Network Graphs in python3 color_back_net

Two quick practical tips

  1. If the graph has many nodes, adjust the layout first before tuning colors and sizes, otherwise the plot becomes hard to read.
  2. If edge weights vary a lot, bind both width and edge_color to the weights so important relationships stand out immediately.

Useful layout functions include:

nx.spring_layout(color_net)
nx.circular_layout(color_net)
nx.shell_layout(color_net)

Summary

This article covered the basics of drawing network graphs with NetworkX, including basic edges, weighted edge styling, and simple visual polish. If you are starting with relationship-data visualization in Python, NetworkX is still one of the fastest tools to get working results. For more detail, see the NetworkX Official Documentation.

友情链接

其它