【问题标题】:TypeError: 'float' object is not iterable trying to annotate an arrow from a listTypeError:'float' 对象不可迭代,试图从列表中注释箭头
【发布时间】:2018-02-08 02:32:29
【问题描述】:

我正在尝试注释从列表列表的 XY 坐标派生的箭头。我可以让绘图在某个点显示注释,但是当我尝试在两个 XY 坐标之间添加箭头时得到Type Error:'float' object is not iterable

代码如下:

import csv
import matplotlib.pyplot as plt
import matplotlib.animation as animation

visuals = [[],[],[],[],[]]

with open('XY_Data.csv') as csvfile :
    readCSV = csv.reader(csvfile, delimiter=',')
    n=0
    for row in readCSV :
        if n == 0 :
            n+=1
            continue
        visuals[0].append(list(map(float, row[3:43][::2]))) #X-Coordinate of 21 subjects
        visuals[1].append(list(map(float, row[2:42][::2]))) #Y-Coordinate of 21 subjects
        visuals[3].append([float(row[44]),float(row[46])]) #X-Coordinate of the subject I want to display the arrow between
        visuals[4].append([float(row[45]),float(row[47])]) #Y-Coordinate of the subject I want to display the arrow between

fig, ax = plt.subplots(figsize = (8,8))
plt.grid(False)

scatter = ax.scatter(visuals[0][0], visuals[1][0], c=['blue'], alpha = 0.7, s = 20, edgecolor = 'black', zorder = 1) #Scatter plot (21 subjects)
scatterO = ax.scatter(visuals[3][0], visuals[4][0], c=['black'], marker = 'o', alpha = 0.7, s = 25, edgecolor = 'black', zorder = 2) #Scatter plot (intended subject)

annotation = ax.annotate('Player 1', xy=(visuals[0][0][0],visuals[1][0][0]), fontsize = 8) #This annotation is displayed at the XY coordinate of the subject in the first column of the dataset
arrow = ax.annotate('', xy = (visuals[3][0][0]), xytext = (visuals[4][0][0]), arrowprops = {'arrowstyle': "<->"}) #This function returns an error

我在做什么不同?

【问题讨论】:

  • 我真的不知道这个模块,但我猜你有一个额外的索引级别,你不应该,所以你将单个单元格传递给函数而不是一个列表。

标签: python matplotlib annotate


【解决方案1】:

您没有指出此错误发生的位置。但我猜它在最后一行:

arrow = ax.annotate('', xy = (visuals[3][0][0]), xytext = (visuals[4][0][0]), arrowprops = {'arrowstyle': "<->"}) #This function returns an error

来自docxy 参数是可迭代的,但在您的代码中,xy 只有 1 个浮点值,您应该尝试类似:

xy=(visuals[3][0][0],visuals[4][0][0]), xytext = (visuals[3][0][1], visuals[4][0][1])

而不是

xy = (visuals[3][0][0])

【讨论】:

    【解决方案2】:

    正如 Amarth 指出的那样,我只有一个浮点值是数据集中第一个主题的 xy 坐标。我需要添加第二个主题的 xy 坐标。

    以下代码有效:

    arrow = ax.annotate('', xy = (visuals[3][0][0], visuals[4][0][0]), xytext = (visuals[3][0][1],visuals[4][0][1]), arrowprops = {'arrowstyle': "&lt;-&gt;"})

    【讨论】:

      猜你喜欢
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-15
      • 2020-09-26
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多