首页 > 解决方案 > 检索 AttributeError 的问题:“元组”对象在绘制 3d 图形时没有属性“ndim”

问题描述

我正在尝试从 csv 文件中绘制 3d 线框图。格式第一列 x 的数据是 CPU 百分比(范围从 10-90%),第二列 y 内存(范围从 10-80%),百分比和最后一列下降率百分比(范围从 10-70%)。样本数据

10,10,30
10,20,10
10,30,5
10,40,30
20,10,4
20,20,30
20,30,40
20,40,20
sample_data = np.genfromtxt("data.csv", delimiter=",", names=["x", "y","z"])
x, y, z = zip(*sample_data)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel('CPU')
ax.set_ylabel('Memory')
ax.set_zlabel('Rate')
ax.plot_wireframe(x,y,z, color='green')
plt.show()

我正在检索以下错误

   if Z.ndim != 2:
   AttributeError: 'tuple' object has no attribute 'ndim'

标签: pythonnumpymatplotlib

解决方案


问题是您对zip. zip是一个 Python 函数,它从可迭代对象中生成元组。Python 元组不是 numpy 数据结构,因此无法响应 ndim 请求。如果您想访问与 、 和 作为 ndarrays 关联的数据点xy那么z您需要执行以下示例:

from io import StringIO
import numpy as np

txt = """10,10,30
10,20,10
10,30,5
10,40,30
20,10,4
20,20,30
20,30,40
20,40,20
"""
s = StringIO(txt)
sample_data = np.genfromtxt(s, delimiter=",", names=["x", "y","z"])
sample_data["z"].ndim
1

推荐阅读