简体   繁体   English

如何在networkx图的绘图中绘制矩形?

[英]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. 我读到正确的方法是使用add_patches方法。

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]. 如果运行plt.xlim() (或plt.ylim() ),则会看到轴的范围接近[-1,1],而您试图在坐标[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. 我不熟悉networkx的工作方式,所以我不知道是否有一种方法可以正确计算所需矩形的坐标。 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: 一种方法是在轴坐标中绘制矩形( 的左上角为0,0,右下角为1,1),而不是数据坐标:

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

在此处输入图片说明

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

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