【问题标题】:plt.scatter of 2-d array elements in a list列表中二维数组元素的 plt.scatter
【发布时间】:2020-05-03 09:13:11
【问题描述】:

我有一个包含数组元素的列表:

[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 处数组的第一个元素位置,和第二个元素的 y 类似。

我对如何在 python 中进行索引不是非常熟悉,无论我如何尝试解决这个问题,我都无法获得绘图。

for i in range(len(list)):
    # plt.scatter(x,y) for x,y as described above

谁能告诉我一个简单的方法来做到这一点?

【问题讨论】:

  • 请不要隐藏内置名称

标签: python python-3.x list matplotlib numpy-ndarray


【解决方案1】:
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()

【讨论】:

  • 也许您可以使用更好的名称并尽快解压:XYs = [...] 和以后的for x, y in XYs: plt.scatter(x, y)
【解决方案2】:

你可以zipnumpy数组aunpacked values

随心所欲地绘制一条线:

plt.scatter(*zip(*a))

相当于x,y=zip(*a); plt.scatter(x,y)


import numpy as np
import matplotlib.pyplot as plt

a=[np.array([2.40460915, 0.85513601]), np.array([1.80998096, 0.97406986]), np.array([2.14505475, 0.96109123]), np.array([2.12467111, 0.93991277])]
plt.scatter(*zip(*a)) #x,y=zip(*a)
plt.show()

【讨论】:

    【解决方案3】:

    这样就可以了:

    import matplotlib.pyplot as plt
    import numpy as np
    
    a= [np.array([2.40460915, 0.85513601]), 
        np.array([1.80998096, 0.97406986]),
        np.array([2.14505475, 0.96109123]),
        np.array([2.12467111, 0.93991277])]
    
    plt.scatter([i[0] for i in a], [i[1] for i in a])  # just this line here
    plt.show()
    

    【讨论】:

      【解决方案4】:

      这个问题有很多解决方案。我写了两个你会很容易理解的:

      解决方案 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:一个分散(如果您不熟悉索引,我推荐)

      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()
      

      【讨论】:

      • @NicolasGervais 的解决方案比其他的要短,但是如果你不熟悉索引,一开始可能很难理解
      【解决方案5】:

      尝试通过

      将数组转换为pandas Dataframe
      data=pd.DataFrame(data='''array''')
      

      并尝试绘制数据

      【讨论】:

        猜你喜欢
        • 2016-09-25
        • 2019-03-23
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 2017-04-25
        • 1970-01-01
        • 2021-02-03
        • 1970-01-01
        相关资源
        最近更新 更多