Python利用networkx画图绘制Les Misérables人物关系

在这篇攻略中,我们将会学习如何使用networkx库来绘制Victor Hugo的小说《悲惨世界》(Les Misérables)中的人物关系图。

Python利用networkx画图绘制Les Misérables人物关系

在这篇攻略中,我们将会学习如何使用networkx库来绘制Victor Hugo的小说《悲惨世界》(Les Misérables)中的人物关系图。

准备数据

首先,我们需要准备数据来绘制人物关系图。我们使用的是维克多·雨果的小说《悲惨世界》中人物关系的数据集,该数据集可以在github上找到。

克隆数据集到你的本地,然后你可以使用下面的Python代码来读取数据:

import json

with open('les-miserables.json') as f:
    data = json.load(f)

创建图

使用networkx库,我们可以很容易地创建一个图。

import networkx as nx

G = nx.Graph()

添加节点

我们需要添加Les Misérables中的所有人物做为节点到我们的图中。

for node in data['nodes']:
    G.add_node(node['id'])

添加边

接下来,我们需要根据数据集中的边来添加边到我们的图中。

for edge in data['links']:
    G.add_edge(edge['source'], edge['target'], weight=edge['value'])

绘制图

使用networkx.draw函数可以将图绘制出来。你可以使用matplotlib提供的各种方式来美化它。

import matplotlib.pyplot as plt

nx.draw(G, with_labels=True, font_weight='bold')
plt.show()

示例1

以下代码绘制了不同世界神秘岛上的人物间的关系图。

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()

G.add_node('Teletubbies')
G.add_node('Bananas in Pyjamas')
G.add_node('Wonder Pets')

G.add_edge('Teletubbies', 'Bananas in Pyjamas', weight=1)
G.add_edge('Bananas in Pyjamas', 'Wonder Pets', weight=2)
G.add_edge('Wonder Pets', 'Teletubbies', weight=3)

nx.draw(G, with_labels=True, font_weight='bold')
plt.show()

输出图像如下:

示例2

接下来,我们绘制一张更复杂的图表:每个顶点都是平面上的随机点,边的权值是连接它们的距离。

import networkx as nx
import matplotlib.pyplot as plt
from random import randint

MAX_NODES = 12

G = nx.Graph()
for i in range(MAX_NODES):
    G.add_node(i, pos=(randint(0, 100), randint(0, 100)))

for u in G.nodes():
    pos_u = G.nodes[u]['pos']
    for v in G.nodes():
        if u != v:
            pos_v = G.nodes[v]['pos']
            distance = ((pos_u[0] - pos_v[0])**2 + (pos_u[1] - pos_v[1])**2)**0.5
            G.add_edge(u, v, weight=distance)

pos = nx.get_node_attributes(G,'pos')
nx.draw(G, pos, with_labels=True)
edge_labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
plt.show()

输出结果如下:

总结:

在本篇攻略中,我们学习了如何使用Python的networkx库和matplotlib库来绘制Les Misérables人物关系图。我们了解了如何从JSON文件中读取数据,创建图和添加节点和边。我们还看到了一些例子,其中包括使用RGB值带权关系的绘制和按距离带权的绘制。

本文标题为:Python利用networkx画图绘制Les Misérables人物关系

基础教程推荐