You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Matplotlib PolyCollection绘图时遇到numpy.record转float64类型转换错误的解决求助

Matplotlib PolyCollection绘图时遇到numpy.record转float64类型转换错误的解决求助

我尝试用Pandas整理数据,再用Matplotlib绘制图形,但运行时遇到了类型转换错误,有没有大佬能帮我看看怎么解决?

具体错误提示如下:
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').

备注:内容来源于stack exchange,提问作者user28311778

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 17:53:01