title: Pyplot truth value of an array with more than one element is ambiguous
body: <p>I am trying to implement a knn 1D estimate:</p>
  
  <pre><code># nearest neighbors estimate
  def nearest_n(x, k, data):
      # Order dataset
      #data = np.sort(data, kind='mergesort')
      nnb = []
      # iterate over all data and get k nearest neighbours around x
      for n in data:
          if nnb.__len__()&lt;k:
              nnb.append(n)
          else:
              for nb in np.arange(0,k):
                  if np.abs(x-n) &lt; np.abs(x-nnb[nb]):
                      nnb[nb] = n
                      break
  
      nnb = np.array(nnb)
      # get volume(distance) v of k nearest neighbours around x
      v = nnb.max() - nnb.min()
      v = k/(data.__len__()*v)
  
      return v
  
  interval = np.arange(-4.0, 8.0, 0.1)
  plt.figure()
  for k in (2,8,35):
      plt.plot(interval, nearest_n(interval, k,train_data), label=str(o))
  plt.legend()
  plt.show()
  </code></pre>
  
  <p>Which throws:</p>
  
  <pre><code>  File "x", line 55, in nearest_n
      if np.abs(x-n) &lt; np.abs(x-nnb[nb]):
  ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
  </code></pre>
  
  <p>I know the error comes from the array input in plot(), but I am not sure how to avoid this in a function with operators >/==/&lt;</p>
  
  <p>'data' comes from a 1D txt file containing floats.</p>
  
  <p>I tried using vectorize:</p>
  
  <pre><code>nearest_n = np.vectorize(nearest_n)
  </code></pre>
  
  <p>which results in:</p>
  
  <pre><code>line 50, in nearest_n
      for n in data:
  TypeError: 'numpy.float64' object is not iterable
  </code></pre>
  
  <p>Here is an example, let's say:</p>
  
  <pre><code>data = [0.5,1.7,2.3,1.2,0.2,2.2]
  k = 2
  </code></pre>
  
  <p>nearest_n(1.5) should then lead to </p>
  
  <pre><code>nbb=[1.2,1.7]
  v = 0.5 
  </code></pre>
  
  <p>and return 2/(6*0.5) = 2/3 </p>
  
  <p>The function runs for example neares_n(2.0,4,data) and gives 0.0741586011463</p>