英文:
Unpack matrices in numpy file and plot them
问题
I need a code that reads a .npy file containing a set of arrays and creates a scatter plot using numpy and matplotlib. The first column need to be the x cordinates and the second column are the y cordinates.
import numpy as np
import matplotlib.pyplot as plt
# Load the .npy file
a = np.load("filename.npy")
# Extract x and y coordinates
x = a[:, :, 0]
y = a[:, :, 1]
# Create a scatter plot
plt.scatter(x, y)
plt.xlabel('X Coordinates')
plt.ylabel('Y Coordinates')
plt.show()
英文:
I need a code that reads a .npy file containing a set of arrays and creates a scatter plot using numpy and matplotlib. The first column need to be the x cordinates and the second column are the y cordinates
ex:
a = np.load("filename.npy")
a
([[[19.3, 117.88],
[20.77, 118.99],
[18.92, 117.66],
[16.23, 115.67]],
[[16.335, 113.789],
[17.876, 116.8],
[22.76, 115.34],
[23.33, 111.45]],
[[22.56, 113.76],
[21.6, 118.07],
[18.3, 116.60],
[21.739, 117.903]]])
答案1
得分: 1
只需切片“columns”(实际上是第三维度),然后将其传递给plt.scatter
。Matplotlib会在内部展平输入。
import matplotlib.pyplot as plt
plt.scatter(a[:, :, 0], a[:, :, 1])
巧妙的替代方法:
plt.scatter(*a.reshape(-1, 2).T)
输出:
英文:
Simply slice the "columns" (actually the third dimension) and pass it to plt.scatter
. Matplotlib will flatten the inputs internally.
import matplotlib.pyplot as plt
plt.scatter(a[:, :, 0], a[:, :, 1])
Hacky alternative:
plt.scatter(*a.reshape(-1, 2).T)
Output:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论