我尝试使用Pandas捆绑数据并使用maplotlib绘制它,但出现错误。
如何解决这个错误?
TypeError: Cannot cast array data from dtype((numpy.record, [('x', '<i8'), ('y', '<i8')])) to dtype('float64')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
a = [
{'x': 1, 'y': 2},
{'x': 0, 'y': 1},
{'x': 1, 'y': 0},
{'x': 2, 'y': 1},
{'x': 3, 'y': 2},
{'x': 2, 'y': 1},
{'x': 3, 'y': 0},
{'x': 4, 'y': 1},
]
b = pd.DataFrame(a)
c = np.array(b[['x', 'y']].to_records(index=False))
fig, ax = plt.subplots(1, 1)
ax.add_collection(PolyCollection(c))
plt.show()
Traceback (most recent call last):
File "..\test.py", line 80, in <module>
ax.add_collection(PolyCollection(c))
^^^^^^^^^^^^^^^^^
File "..\Python\Python311\site-packages\matplotlib\collections.py", line 1200, in __init__
self.set_verts(verts, closed)
File "..\Python\Python311\site-packages\matplotlib\collections.py", line 1241, in set_verts
self._paths.append(mpath.Path._create_closed(xy))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "..\Python\Python311\site-packages\matplotlib\path.py", line 199, in _create_closed
v = _to_unmasked_float_array(vertices)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "..\Python\Python311\site-packages\matplotlib\cbook.py", line 1398, in _to_unmasked_float_array
return np.asarray(x, float)
^^^^^^^^^^^^^^^^^^^^
TypeError: Cannot cast array data from dtype((numpy.record, [('x', '<i8'), ('y', '<i8')])) to dtype('float64').
不清楚为什么在这里使用记录数组。这可以通过使用
DataFrame
方法直接将 pandas .to_numpy()
转换为 numpy 数组来完成。 b.to_numpy()
返回形状为 (8,2)
的数组。
您还需要注意,
PolyCollections
需要一个包含形状为(M,2)
的顶点的二维列表/数组的列表。因此,将 DataFrame
转换为数组后,我们必须将其放入列表中。
最后,添加集合不会触发轴限制的重新缩放,因此我添加了对
ax.autoscale_view()
的调用。
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
plt.close("all")
a = [
{'x': 1, 'y': 2},
{'x': 0, 'y': 1},
{'x': 1, 'y': 0},
{'x': 2, 'y': 1},
{'x': 3, 'y': 2},
{'x': 2, 'y': 1},
{'x': 3, 'y': 0},
{'x': 4, 'y': 1},
]
b = pd.DataFrame(a)
fig, ax = plt.subplots()
ax.add_collection(PolyCollection([b.to_numpy()])) # put the array into a list
ax.autoscale_view()
plt.show()
结果: