python - 属性错误 : 'numpy.ndarray' object has no attribute 'plot'

标签 python matplotlib

为什么这个 matplotlib 代码给我一个奇怪的异常?我要去两排地 block 。顶行应该显示 true 与 pred,底行应该显示百分比误差。

yy = func(*X)

fig, axes = plt.subplots(1, len(X))
for ax,_x in zip(axes,X):
    ax.plot(_x, y, 'b.')
    ax.plot(_x, yy, 'r.')

fig, axes = plt.subplots(2, len(X))
for ax,_x in zip(axes,X):
    ax.plot(_x, yy/y-1, 'r.')

plt.show()

回溯:

   File "pysr.py", line 235, in main
     ax.plot(_x, yy/y-1, 'r.')
AttributeError: 'numpy.ndarray' object has no attribute 'plot'

最佳答案

如果 len(X) >1,axes 将是 AxesSubplot 实例的二维数组。因此,当您遍历 axes 时,您实际上会沿 axes 数组的一个维度获得一个切片。

要克服这个问题,您可以使用 axes.flat:

for ax,_x in zip(axes.flat,X):

此外,如果您尝试将所有这些绘制在一个图形上,则无需调用 plt.subplots 两次,因为这将创建两个图形。

像这样索引 axes 数组可能更容易:

yy = func(*X)

fig, axes = plt.subplots(2, len(X))

for i,_x in enumerate(X):
    axes[0, i].plot(_x, y, 'b.')
    axes[0, i].plot(_x, yy, 'r.')

    axes[1, i].plot(_x, yy/y-1, 'r.')

plt.show()

关于python - 属性错误 : 'numpy.ndarray' object has no attribute 'plot' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38111724/

相关文章:

python - matplotlib 在 Windows 上的 Python 2.7.3 中中断 str( )

python - Seaborn 散点图颜色不正确 'hue'

python - 使用子图绘制水平线 Matplotlib

python - matplotlib hist() 自动裁剪范围

python - 如何使用 eclipse 调试或运行 pytest 脚本?

python - 使用 Numpy 和 Numba 将值数组合并到离散集中最接近的值

python - 如何在一台机器上设置两个dask分布式调度器?

python - 我可以检查 sqlalchemy 查询对象以查找已连接的表吗?

python - Pandas,如果包含 Nan,整数变量将变为 float

python - 在 Jupyter iPython Notebook 中使用 matplotlib 绘制图形