在matplotlib/scipy/numpy中绘制log数组时出错

1 投票
3 回答
3463 浏览
提问于 2025-04-15 21:55

我有两个数组,然后我对它们取对数。当我这样做并尝试绘制它们的散点图时,出现了这个错误:

  File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/pyplot.py", line 2192, in scatter
    ret = ax.scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, faceted, verts, **kwargs)
  File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/axes.py", line 5384, in scatter
    self.add_collection(collection)
  File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/axes.py", line 1391, in add_collection
    self.update_datalim(collection.get_datalim(self.transData))
  File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/collections.py", line 153, in get_datalim
    offsets = transOffset.transform_non_affine(offsets)
  File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/transforms.py", line 1924, in transform_non_affine
    self._a.transform(points))
 File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/transforms.py", line 1420, in transform
    return affine_transform(points, mtx)
ValueError: Invalid vertices array.

代码其实很简单:

myarray_x = log(my_array[:, 0])
myarray_y = log(my_array[:, 1])
plt.scatter(myarray_x, myarray_y)

有没有人知道这可能是什么原因呢?谢谢。

3 个回答

4

这个在我这边运行得很成功。

>>> from numpy import log, array
>>> import matplotlib.pyplot as plt
>>> my_array = array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
>>> my_array
array([[ 1.,  2.],
       [ 3.,  4.],
       [ 5.,  6.]])
>>> myarray_x = log(my_array[:, 0])
>>> myarray_y = log(my_array[:, 1])
>>> plt.scatter(myarray_x, myarray_y)
<matplotlib.collections.CircleCollection object at 0x030C7A10>
>>> plt.show()

所以可能问题出在你没有告诉我们的某些地方。你能提供一段完整的示例代码,跟你运行时的一模一样,这样我们才能复现你的问题吗?

7

我之前也遇到过同样的问题,最近解决了:

对我来说,问题出在我的 X 和 Y(numpy)数组是用 128 位的浮点数构成的。

解决这个问题的方法是把这些数组转换成精度更低的浮点数,也就是:

array = numpy.float64(array)

希望这能帮到你 :~)

5

新答案:

从源代码来看,如果传入affine_transform的points数组维度不对或者是空的,就会出现这个错误。这里有相关的代码行:

if (!vertices ||
        (PyArray_NDIM(vertices) == 2 && PyArray_DIM(vertices, 1) != 2) ||
        (PyArray_NDIM(vertices) == 1 && PyArray_DIM(vertices, 0) != 2))
         throw Py::ValueError("Invalid vertices array.");

在继续之前,先检查一下你的myarray_x和myarray_y数组的维度吧。

旧答案:

我猜测你可能在对小于等于0的值取对数。这会导致你的数组中出现nan(不是一个数字)或者-无穷大(如果等于0的话),这些当然是无法绘图的。

(不过wiso说得对,这些点会被忽略)

撰写回答