gpt4 book ai didi

python - 在python中将0/1矩阵转换为二维网格图

转载 作者:行者123 更新时间:2023-12-04 09:34:14 26 4
gpt4 key购买 nike

给定一个包含 0/1 矩阵的 .txt 文件,在 python 中实现网格图。我应该为该矩阵创建一个网格图,但问题是我应该在那些有 0 的部分创建网格,在有 1 的部分创建块.
所以我的txt文件包含这个:

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1
0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 1
0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 1
1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
我应该根据上面的矩阵创建波纹管网格,但不知道如何:
enter image description here

最佳答案

我们可以用 nx.grid_2d_graph 定义一个网格图,并且只保留矩阵中值为 0 的那些节点.然后我们可以使用网格图中的坐标来定位节点:

from matplotlib import pyplot as plt
import numpy as np
import networkx as nx

# lines to 2d array
with open('myfile.txt') as f:
a = np.array([list(map(int,i.split())) for i in f.readlines()])

# define grid graph according to the shape of a
G = nx.grid_2d_graph(*a.shape)

# remove those nodes where the corresponding value is != 0
for val,node in zip(a.ravel(), sorted(G.nodes())):
if val!=0:
G.remove_node(node)

plt.figure(figsize=(9,9))
# coordinate rotation
pos = {(x,y):(y,-x) for x,y in G.nodes()}
nx.draw(G, pos=pos,
node_color='grey',
width = 4,
node_size=400)
enter image description here

关于python - 在python中将0/1矩阵转换为二维网格图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62671695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com