Python 列表中二维阵列元素的散布
我有一个包含数组元素的列表:Python 列表中二维阵列元素的散布,python,python-3.x,list,matplotlib,numpy-ndarray,Python,Python 3.x,List,Matplotlib,Numpy Ndarray,我有一个包含数组元素的列表: [array([2.40460915, 0.85513601]), array([1.80998096, 0.97406986]), array([2.14505475, 0.96109123]), array([2.12467111, 0.93991277])] 我想用mathplotlib绘制这个列表,这样我就可以迭代列表中的每个元素,然后用plt.scatter(x,y)绘制ith元素,其中x是数组在ith位置的第一个元素,与第二个元素类似 我不太熟悉如何
[array([2.40460915, 0.85513601]), array([1.80998096, 0.97406986]), array([2.14505475, 0.96109123]),
array([2.12467111, 0.93991277])]
我想用mathplotlib绘制这个列表,这样我就可以迭代列表中的每个元素,然后用plt.scatter(x,y)绘制ith
元素,其中x是数组在ith
位置的第一个元素,与第二个元素类似
我不太熟悉如何在python中建立索引,无论我如何尝试解决这个问题,我都无法得到一个图
for i in range(len(list)):
# plt.scatter(x,y) for x,y as described above
有人能告诉我一个简单的方法吗 尝试通过以下方式将数组转换为数据帧
from numpy import array
import matplotlib.pyplot as plt
a = [array([2.40460915, 0.85513601]), array([1.80998096, 0.97406986]), array([2.14505475, 0.96109123]),
array([2.12467111, 0.93991277])]
# *i unpacks i into a tuple (i[0], i[1]), which is interpreted as (x,y) by plt.scatter
for i in a:
plt.scatter(*i)
plt.show()
data=pd.DataFrame(data='''array''')
然后尝试绘制数据这样做:
导入matplotlib.pyplot作为plt
将numpy作为np导入
a=[np.数组([2.40460915,0.85513601]),
np.数组([1.809996,0.97406986]),
np.数组([2.14505475,0.96109123]),
np.数组([2.12467111,0.93991277])]
plt.scatter([i[0]表示a中的i],[i[1]表示a中的i])#这里只有这条线
plt.show()
您可以
zip
numpy数组a
的解包值
根据需要绘制一条直线:
plt.scatter(*zip(*a))
相当于x,y=zip(*a);plt.散射(x,y)
这个问题有很多解决方案。我写了两篇你很容易理解的文章:
解决方案1:许多散射体
for i in range(len(data)):
point = data[i] #the element ith in data
x = point[0] #the first coordenate of the point, x
y = point[1] #the second coordenate of the point, y
plt.scatter(x,y) #plot the point
plt.show()
解决方案2:一次分散(如果您不熟悉索引,我建议您分散)
@NicolasGervais的解决方案比其他解决方案要短,但是如果您不熟悉索引,那么一开始可能很难理解,也许您可以使用更好的名称并尽快解包:XYs=[…]
以及稍后的对于XYs中的x,y:plt.scatter(x,y)
请不要隐藏内置名称
for i in range(len(data)):
point = data[i] #the element ith in data
x = point[0] #the first coordenate of the point, x
y = point[1] #the second coordenate of the point, y
plt.scatter(x,y) #plot the point
plt.show()
x = []
y = []
for i in range(len(data)):
point = data[i]
x.append(point[0])
y.append(point[1])
plt.scatter(x,y)
plt.show()