简体   繁体   English

如何使用Networkx绘制线性图

[英]How to draw a linear graph using networkx

I have a graph in networkx, which I want to draw. 我在networkx中有一个要绘制的图形。 I want to plot something like this: 我想画这样的东西: 在此处输入图片说明

I followed the instruction in the networkx documentation to draw it using the following commands: 我按照networkx文档中的说明使用以下命令进行绘制:

nx.draw(G, with_labels=True)
plt.savefig("path.png").

But, I face two problems: 1. the nodes and edges are drawn randomly, 2. the size of the canvas is fixed and the graph doesn't fit in it. 但是,我面临两个问题:1.节点和边缘是随机绘制的; 2.画布的大小是固定的,图形不适合其中。

I appreciate any feedback on how I can plot this graph. 感谢您对如何绘制此图的任何反馈。

You can pass node positions to the draw_networkx as a dictionary of the form: {node:[x-coordinate,y-coordinate}. 您可以将节点位置作为字典形式传递给draw_networkx:{node:[x-coordinate,y-coordinate}。 You can set the size of the plot for the figure using plt.figure. 您可以使用plt.figure设置图形的大小。 Here is an example of a square: 这是一个正方形的示例:

import networkx as nx
import matplotlib.pyplot as plt

plt.figure(figsize=(8,8))
G=nx.Graph()
G.add_edges_from([(0,1),(1,2),(2,3),(3,0)])
positions = {0:[0,0],1:[1,0],2:[1,1],3:[0,1]}
nx.draw_networkx(G,pos=positions)
plt.savefig("path.png")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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