0
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()

I want to create like the picture but I can not do it. And also, the numbers of edges is given by the user. This is what I want

and I am getting like this. This is what I am getting

I am hoping the user can give multiple edges and they will be projected like the image.

  • 1
    Please, please, don't post the same question twice. Please [edit](https://stackoverflow.com/posts/75588086/edit) your previous question and add missing information, including a concrete list as input for testing. – JohanC Feb 28 '23 at 09:47

1 Answers1

1

Your input essentially just seems to be getting a list of the nodes rather than which nodes should be joined by edges. Instead (based on, e.g., this post and answers). You could create a script (called, e.g., network.py) containing:

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()

Then run this with:

python network.py

and input:

1 2, 1 3, 1 4, 2 3, 3 4, 3 6, 4 5, 6 5

to produce the graph you want.

enter image description here

Matt Pitkin
  • 3,989
  • 1
  • 18
  • 32