python - 如何在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'))
我的问题是,最后一行似乎没有任何效果。
解决方案
您的坐标在窗口之外。如果您运行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))
推荐阅读
- node.js - 在 Windows 10 上安装 expo-cli --global 时出错
- angular - 多个场景的 IE 11 中的 ngForm 崩溃
- typescript - 如何从当前选项卡导航回主网页,当前选项卡是单击“生成 pdf”时生成的 pdf 文件
- php - 在 URL 中传递数组值,http_build_query 没有给出所需的结果
- c# - 防止不可变对象重复
- kubernetes - Ingress-nginx 控制器无法在 AWS EC2 Kubernetes 集群中正确运行 ELB
- selenium - 双破折号 (--) 在 Selenium ChromeOptions 中意味着什么
- python - 将代码更改为 ODE Python 的边界值问题
- linux - 将 if 测试与 bash 中的 -o 选项结合使用
- python - 网页上带有滑块的网页抓取