基于《哈利波特与魔法石》这部电影中的主要角色构建一张关系图
用python的networkx包画出关系图。
-
首先需要安装
networkx
和matplotlib
库(如果没有安装的话):- 在命令行中执行
pip install networkx matplotlib
。
- 在命令行中执行
-
以下是使用
networkx
和matplotlib
绘制《哈利·波特与魔法石》主要角色关系图的
这段代码首先创建了一个有向图G
,然后添加了主要角色作为节点,接着根据角色之间的关系添加了边,最后使用spring_layout
布局算法来确定节点位置,并绘制出关系图。
import networkx as nx
import matplotlib.pyplot as plt
# 创建有向图
G = nx.DiGraph()
# 添加角色节点
characters = ["Harry Potter", "Ron Weasley", "Hermione Granger", "Albus Dumbledore", "Rubeus Hagrid",
"Voldemort", "Professor Quirrell", "Fred and George Weasley", "Ginny Weasley",
"Molly and Arthur Weasley", "Neville Longbottom", "Minerva McGonagall", "Severus Snape"]
for character in characters:
G.add_node(character)
# 添加边(关系)
# 朋友关系用双向箭头
G.add_edge("Harry Potter", "Ron Weasley")
G.add_edge("Ron Weasley", "Harry Potter")
G.add_edge("Harry Potter", "Hermione Granger")
G.add_edge("Hermione Granger", "Harry Potter")
# 非朋友关系用单向箭头
G.add_edge("Harry Potter", "Albus Dumbledore")
G.add_edge("Harry Potter", "Rubeus Hagrid")
G.add_edge("Voldemort", "Harry Potter")
G.add_edge("Voldemort", "Professor Quirrell")
G.add_edge("Ron Weasley", "Fred and George Weasley")
G.add_edge("Ron Weasley", "Ginny Weasley")
G.add_edge("Ron Weasley", "Molly and Arthur Weasley")
G.add_edge("Hermione Granger", "Neville Longbottom")
G.add_edge("Harry Potter", "Minerva McGonagall")
G.add_edge("Harry Potter", "Severus Snape")
# 绘制图形
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_size = 1000, node_color = "skyblue", font_size = 8)
plt.title("Characters Relationship in Harry Potter and the Sorcerer's Stone")
plt.show()
- 代码解释:
- 对于朋友关系(如哈利和罗恩、哈利和赫敏),通过添加双向边来表示。
- 对于其他如导师、亲属、敌人等关系,保持单向边的添加方式。
- 最后按照相同的方式绘制图形。
计算一下Harry Potter这个节点的centrality betweenness是多少
- 首先需要导入
networkx
库来计算介数中心性(Betweenness Centrality)。以下是在之前代码基础上添加计算介数中心性的步骤: