python - 使用坐标在图像上重叠图形

标签 python python-3.x networkx

我有两个坐标列表:第一个用于 x 坐标,第二个用于 y 坐标。我尝试将它们用作图表的节点。

import networkx as nx
list_of_coordinates_x = list(4.5 , 4, 67, 578, 68) #random numbers
list_of_coordinates_y = list(6.7, 3, 12, 45.555, 692)

G=nx.MultiGraph()
for i in range(len(list_of_coordinates_x)):
    G.add_node(i, x = list_of_coordinates_x[i], y = list_of_coordinates_y[i])
    if i > 0:
       G.add_edge(i-1,i)

nx.draw(G,node_size=10,with_labels=False)

但是我通过这种方式获得的所有图表看起来像是随机放置在平面上的节点集。如何通过图像上的坐标来固定它们?我怎样才能使用我自己的 1680x1050 .jpg 文件呢? 使用问题第一部分的答案后,我得到了这个图表:

I have this graph

但我想把它放在这样的图片上:

But I want to put it on a picture like this

最佳答案

为此,您需要将节点位置设置为属性,并仅使用占位符作为节点名称。因此一种方法可能就是 enumerate节点按照它们出现的顺序排列,并遵循与您相同的逻辑,但将压缩的坐标元素添加为 pos属性:

x = [4.5 , 420, 67, 620, 68]
y = [6.7, 68, 56, 231, 380]

G = nx.DiGraph()
coords = list(zip(x,y))
for node, coo in enumerate(coords, start=1):
    G.add_node(node, pos=coo)
    if node<len(coords):
        G.add_edge(node, node+1)

然后你可以创建一个字典 node:(x,y)这是 pos 的格式在nx.draw正在期待,并且节点以这种方式位于指定的坐标上:

nodes = G.nodes(data=True)
pos = {node:attr['pos'] for node, attr in nodes}
plt.figure(figsize=(12,5))
nx.draw(G,
        nodelist=nodelist,
        pos=pos,
        node_size=500,
        node_color='orange')

enter image description here

为了将图表重叠到现有图像上,您必须确保它们共享相同的 extent 。这很好解释了here :

When layering multiple images, the images need to have the same extent. This does not mean they need to have the same shape, but they both need to render to the same coordinate system determined by xmin, xmax, ymin, ymax

为此,您可以对图形坐标和图像强制执行一定程度的限制。该值取决于图像大小,因此您必须将图表和图像的范围调整为图像的实际大小。我将使用 klearn.datasets.load_sample_image 中的示例图像作为示例,但对于您自己的图像,您可以使用 matplotlib.image.imread('my_image.jpg') 加载它.

from sklearn.datasets import load_sample_image
img = load_sample_image('flower.jpg')

x = [4.5 , 420, 67, 620, 68]
y = [6.7, 68, 56, 231, 380]

y_lim, x_lim = img.shape[:-1]
extent = 0, x_lim, 0, y_lim

G = nx.DiGraph()
coords = list(zip(x,y))
for node, coo in enumerate(coords, start=1):
    G.add_node(node, pos=coo)
    if node<len(coords):
        G.add_edge(node, node+1)

fig = plt.figure(frameon=False, figsize=(10,19))

plt.imshow(img, extent=extent, interpolation='nearest')

nodes = G.nodes(data=True)
pos = {node:attr['pos'] for node, attr in nodes}
nx.draw(G,
        nodelist=nodelist,
        pos=pos,
        node_size=200,
        edge_color='w',
        width=4,
        extent=extent,
        node_color='orange',
       interpolation='nearest')
plt.show()

enter image description here

关于python - 使用坐标在图像上重叠图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61674222/

相关文章:

python - 尝试在Maya 2018 Python环境中导入cjson

python-3.x - Python 3 BeautifulSoup4 在源页面中搜索文本

Python摆脱字节b''

python - pandas - 根据列值将数据框 reshape 为边缘列表

python - 在 Python 中绘制 Networkx 图

Python findall 使用正则表达式抓取 HTML 标签内的数据

python - 将django模型连接到具有相同结构的不同表名

Python 名称未定义但计算结果为真。如何?

python-3.x - 修复将空列表分配给值 "DNA_Sequence"时出现的错误

python - 添加基于报告的层级