matplotlib 我怎样才能创建一个像下面这幅图一样的自我网络呢?我只能做到这一步

ftf50wuq  于 2023-03-03  发布在  其他
关注(0)|答案(1)|浏览(131)
import networkx as nx
import matplotlib.pyplot as plt

user_input = list(map(int, input("Enter the edges you want to plot: ").split()))
print("The edges are: ", user_input)
G = nx.Graph()

for x in user_input:
    if (x<len(user_input)):
        G.add_edge(x, x+1)

ego = user_input[0]
pos = nx.spring_layout(G)
nx.draw(G, pos, node_color="lavender",
        arrows=True, arrowstyle='-|>',
        node_size=800, with_labels=True)

options = {"node_size": 1200, "node_color": "r"}
nx.draw_networkx_nodes(G, pos, nodelist=[ego], **options)
plt.show()

我想创建像图片一样的东西,但是我做不到。另外,边缘的数量是由用户给定的。This is what I want
我就变成这样了。This is what I am getting
我希望用户可以给予多个边缘,他们将像图像一样投影。

6ju8rftf

6ju8rftf1#

你的输入看起来只是一个节点列表,而不是哪些节点应该通过边连接,相反(基于,例如,this post and answers),你可以创建一个脚本(名为,例如,network.py),包含:

import networkx as nx
import matplotlib.pyplot as plt

# get pairs of nodes that define the edges
user_input = input("Enter pairs of joined nodes separated by commas, e.g., 1 2, 1 3, 1 4:\n").split(",")

G = nx.Graph()

# add nodes
nodes = []
for edge in user_input:
    for node in edge.split():
        if int(node) not in nodes:
            nodes.append(int(node))
            G.add_node(int(node))

# add edges
for edge in user_input:
    G.add_edge(*[int(e) for e in edge.split()])

pos = nx.spring_layout(G)
nx.draw(G, pos, node_color="lavender",
        arrows=True, arrowstyle='-|>',
        node_size=800, with_labels=True)

options = {"node_size": 1200, "node_color": "r"}
nx.draw_networkx_nodes(G, pos, nodelist=[nodes[0]], **options)
plt.show()

然后使用以下命令运行:

python network.py

并输入:
以生成所需的图形。

相关问题