简体   繁体   中英

How to draw rectangles in the plot of a networkx graph?

I have a graph which I want to plot and then add some customization to it. In particular, I want to draw boxes around some groups of nodes and I want to write text.

So far I could not make it work. I read that the right way to do it would be to use the add_patches method.

Here is my non-working code:

    import matplotlib.pyplot as plt   
    import networkx as nx
    from matplotlib.patches import Rectangle

    f = plt.figure(figsize=(16,10))

    G=nx.Graph()
    ndxs = [1,2,3,4]
    G.add_nodes_from(ndxs)
    G.add_weighted_edges_from( [(1,2,0), (1,3,1) , (1,4,-1) , (2,4,1) , (2,3,-1), (3,4,10) ] ) 
    nx.draw(G, nx.spring_layout(G, random_state=100))

    plt.gca().add_patch(Rectangle((50,100),40,30,linewidth=1,edgecolor='b',facecolor='none'))

My problem is, the last line does not seem to have any effect.

Your coordinates are way outside the window. If you run plt.xlim() (or plt.ylim() ) you'll see that the extent of the axes is close to [-1,1] whereas you're trying to day a Rectangle at coordinates [50,100].

import matplotlib.pyplot as plt   
import networkx as nx
from matplotlib.patches import Rectangle

f,ax = plt.subplots(1,1, figsize=(8,5))

G=nx.Graph()
ndxs = [1,2,3,4]
G.add_nodes_from(ndxs)
G.add_weighted_edges_from( [(1,2,0), (1,3,1) , (1,4,-1) , (2,4,1) , (2,3,-1), (3,4,10) ] ) 
nx.draw(G)

ax.add_patch(Rectangle((0,0),0.1,0.1,linewidth=1,edgecolor='b',facecolor='none'))

在此处输入图片说明

I'm not familiar with how networkx works, so I don't know if there's a way to correctly calculate the coordinates of the rectangle you need. One approach would be to draw the rectangle in axes coordinates (the top left of the axes is 0,0 and bottom-right is 1,1), instead of data coordinates:

import matplotlib.pyplot as plt   
import networkx as nx
from matplotlib.patches import Rectangle

f,ax = plt.subplots(1,1, figsize=(8,5))

G=nx.Graph()
ndxs = [1,2,3,4]
G.add_nodes_from(ndxs)
G.add_weighted_edges_from( [(1,2,0), (1,3,1) , (1,4,-1) , (2,4,1) , (2,3,-1), (3,4,10) ] ) 
nx.draw(G)

ax.add_patch(Rectangle((0.25,0.25),0.5,0.5,linewidth=1,edgecolor='b',facecolor='none', transform=ax.transAxes))

在此处输入图片说明

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