Corey
Corey

Reputation: 121

How to draw a linear graph using networkx

I have a graph in networkx, which I want to draw. I want to plot something like this: enter image description here

I followed the instruction in the networkx documentation to draw it using the following commands:

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.

I appreciate any feedback on how I can plot this graph.

Upvotes: 0

Views: 2854

Answers (1)

Johannes Wachs
Johannes Wachs

Reputation: 1310

You can pass node positions to the draw_networkx as a dictionary of the form: {node:[x-coordinate,y-coordinate}. You can set the size of the plot for the figure using 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")

enter image description here

Upvotes: 1

Related Questions