我有两个坐标列表:第一个用于 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 文件呢? 使用问题第一部分的答案后,我得到了这个图表:
但我想把它放在这样的图片上:
最佳答案
为此,您需要将节点位置设置为属性,并仅使用占位符作为节点名称。因此一种方法可能就是 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')
为了将图表重叠到现有图像上,您必须确保它们共享相同的 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()
关于python - 使用坐标在图像上重叠图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61674222/