简体   繁体   中英

How do I view graphs created using NetworkX library without Anaconda/Spyder?

I am doing a Discrete Maths course. Students are supposed to use the NetworkX library for visualising graphs. The instructors and TAs are using Spyder and Anaconda. And I have no plans of using them. I am not being able to view graphs created by the NetworkX library. The rest of the code work perfectly. Here's a sample:

import networkx as nx
G = nx.Graph()
for i in range(1, 6):
    G.add_node(i)

G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 4)
G.add_edge(4, 5)
G.add_edge(1, 6)

print(G.nodes())
print(G.edges())

nx.draw(G)

And here's the output:

[1, 2, 3, 4, 5, 6]
[(1, 2), (1, 6), (2, 3), (3, 4), (4, 5)]


------------------
(program exited with code: 0)
Press return to continue

So the last line is not printing. Changing it to print(nx.draw(G)) just adds a None at the end of the output. I have tried using Geany, VS Code and the terminal (Bash), but cannot see the graph. What do I do?

How would I be able to view graphs without using Anaconda/Spyder?

You can use matplotlib, you just have to set the parameters on nx.draw to the axes of the matplotlib figure, for example:

import matplotlib.pyplot as plt

def draw_graph(nx_graph):
    fig, axes = plt.subplots(1,1,dpi=72)
    nx.draw(nx_graph, pos=nx.spring_layout(nx_graph), ax=axes, with_labels=True)
    plt.show()

The networkx docs recommend using more specific dedicated tools for graph visualization, but this works for the basics. See: https://networkx.github.io/documentation/stable/reference/drawing.html

This can be solved by viewing the graph as external images. When a graph is generated, it can be viewed as an image on a different window, or it can be saved to the current directory.

A submodule called pyplot from the package matplotlib is needed to be imported to do this.

Suppose a graph is drawn using nx.draw(graph-name) . In Spyder, it will output a graph automatically. But that doesn't happen in terminal.

We can view the generated graph using the command plt.show() . Where we have imported matplotlib.pyplot as plt .

plt.show() will display the graph in a different window, but it will not save a copy of the graph.

If you want to save a copy of the graph in the current directory, use plt.savefig('file-with-extension') . It will save a copy of the graph.

Here's an example:

>>> import networkx as nx
>>> import matplotlib.pyplot as plt
>>> G = nx.graph()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> nx.draw(G, with_labels=1)
>>> plt.show()

in the interpreter will give you this- 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM