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

问题描述 投票:0回答:1

我有一个图表,我想绘制,然后添加一些自定义。特别是,我想在一些节点组周围绘制框,我想写文本。

到目前为止,我无法使其发挥作用。我读到正确的方法是使用add_patches方法。

这是我的非工作代码:

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

我的问题是,最后一行似乎没有任何影响。

python matplotlib networkx
1个回答
1
投票

你的坐标在窗外。如果运行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'))

enter image description here

我不熟悉networkx的工作原理,所以我不知道是否有办法正确计算你需要的矩形坐标。一种方法是在轴坐标中绘制矩形(轴的左上角是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))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.