首页 > 解决方案 > 如何在networkx图的图中绘制矩形?

问题描述

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

到目前为止,我无法让它工作。我读到正确的方法是使用 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'))

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

标签: pythonmatplotlibnetworkx

解决方案


您的坐标在窗口之外。如果您运行plt.xlim()(或plt.ylim()),您会看到轴的范围接近 [-1,1],而您正在尝试在坐标 [50,100] 处绘制一个 Rectangle。

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

在此处输入图像描述

我不熟悉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))

在此处输入图像描述


推荐阅读