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

Jupyter Notebook执行matplotlib绘图代码报错ValueError: object __array__ method not producing an array求助

Jupyter Notebook执行matplotlib绘图代码报错ValueError: object array method not producing an array求助

您好!针对您遇到的「首次运行matplotlib散点图代码正常,但重跑单元格就报ValueError: object __array__ method not producing an array」的问题,结合您提供的环境信息和报错栈,我整理了几个可行的排查和解决方向,您可以逐一尝试:

一、调整库版本,解决兼容性冲突

您当前使用的numpy 1.26.4和matplotlib 3.9.2虽然官方标注兼容,但部分特殊环境下可能存在隐性版本冲突。建议尝试调整版本组合:

  • 降级numpy到1.25.x稳定系列,同时匹配matplotlib 3.9.x的兼容版本:
    pip install numpy==1.25.2 matplotlib==3.9.1 --force-reinstall
    
  • 安装完成后重启Jupyter内核,再重新测试代码。

二、清理Jupyter内核状态,消除残留异常

重跑单元格报错大概率和内核残留的变量或异常状态有关:

  1. 点击Jupyter菜单栏的「Kernel」→「Restart & Run All」,彻底重启内核并重新执行所有代码;
  2. 也可以在代码单元格开头添加清理命令,强制重置会话状态(注意:会清除当前会话的所有变量,执行前请保存重要数据):
    %reset -f
    import numpy as np
    import matplotlib.image as mpimg
    import matplotlib.pyplot as plt
    
    X = np.random.randn(50)
    Y = np.random.randn(50)
    plt.scatter(X,Y)
    plt.show()
    

三、排除TensorFlow的环境干扰

您安装了TensorFlow 2.18.0,它会依赖并可能修改numpy的运行环境,导致冲突:

  1. 尝试创建一个不包含TensorFlow的虚拟环境,单独安装numpy和matplotlib测试代码是否正常;
  2. 如果必须使用TensorFlow,尝试调整导入顺序,先导入numpy和matplotlib,再导入TensorFlow:
    import numpy as np
    import matplotlib.pyplot as plt
    import tensorflow as tf # 放在最后导入
    
    X = np.random.randn(50)
    Y = np.random.randn(50)
    plt.scatter(X,Y)
    plt.show()
    

四、更换Matplotlib后端,绕过渲染bug

报错栈显示问题出在Agg后端的渲染环节,尝试切换到其他后端:

import matplotlib
matplotlib.use('Qt5Agg') # 或'TkAgg',需确保对应依赖已安装
import numpy as np
import matplotlib.pyplot as plt

X = np.random.randn(50)
Y = np.random.randn(50)
plt.scatter(X,Y)
plt.show()

如果选择Qt5Agg,需要先安装PyQt5依赖:pip install pyqt5


您的问题详情参考:

执行代码:

import numpy as np
import matplotlib.image as mpimg
import matplotlib.pyplot as plt

X = np.random.randn(50)
Y = np.random.randn(50)
plt.scatter(X,Y)
plt.show()

报错信息:

ValueError: object array method not producing an array

环境信息:

  • Windows 11
  • Anaconda-client 1.12.3
  • numpy 1.26.4
  • tensorflow 2.18.0
  • matplotlib 3.9.2

完整报错栈:

ValueError                                Traceback (most recent call last)
File ~\anaconda3\Lib\site-packages\IPython\core\formatters.py:343, in BaseFormatter.__call__(self, obj)
    341     pass
    342 else:
--> 343     return printer(obj)
    344 # Finally look for special method names
    345 method = get_real_method(obj, self.print_method)

File ~\anaconda3\Lib\site-packages\IPython\core\pylabtools.py:170, in print_figure(fig, fmt, bbox_inches, base64, **kwargs)
    167     from matplotlib.backend_bases import FigureCanvasBase
    168     FigureCanvasBase(fig)
--> 170 fig.canvas.print_figure(bytes_io, **kw)
    171 data = bytes_io.getvalue()
    172 if fmt == 'svg':

File ~\anaconda3\Lib\site-packages\matplotlib\backend_bases.py:2204, in FigureCanvasBase.print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
   2200 try:
   2201     # _get_renderer may change the figure dpi (as vector formats
   2202     # force the figure dpi to 72), so we need to set it again here.
   2203     with cbook._setattr_cm(self.figure, dpi=dpi):
-> 2204         result = print_method(
   2205             filename,
   2206             facecolor=facecolor,
   2207             edgecolor=edgecolor,
   2208             orientation=orientation,
   2209             bbox_inches_restore=_bbox_inches_restore,
   2210             **kwargs)
   2211 finally:
   2212     if bbox_inches and restore_bbox:

File ~\anaconda3\Lib\site-packages\matplotlib\backend_bases.py:2054, in FigureCanvasBase._switch_canvas_and_return_print_method.<locals>.<lambda>(*args, **kwargs)
   2050     optional_kws = {  # Passed by print_figure for other renderers.
   2051         "dpi", "facecolor", "edgecolor", "orientation",
   2052         "bbox_inches_restore"}
   2053     skip = optional_kws - {*inspect.signature(meth).parameters}
-> 2054     print_method = functools.wraps(meth)(lambda *args, **kwargs: meth(
   2055         *args, **{k: v for k, v in kwargs.items() if k not in skip}))
   2056 else:  # Let third-parties do as they see fit.
   2057     print_method = meth

File ~\anaconda3\Lib\site-packages\matplotlib\backends\backend_agg.py:496, in FigureCanvasAgg.print_png(self, filename_or_obj, metadata, pil_kwargs)
    449 def print_png(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
    450     """
    451     Write the figure to a PNG file.
    452 
   (...)
    494         *metadata*, including the default 'Software' key.
    495     """
-> 496     self._print_pil(filename_or_obj, "png", pil_kwargs, metadata)

File ~\anaconda3\Lib\site-packages\matplotlib\backends\backend_agg.py:444, in FigureCanvasAgg._print_pil(self, filename_or_obj, fmt, pil_kwargs, metadata)
    439 def _print_pil(self, filename_or_obj, fmt, pil_kwargs, metadata=None):
    440     """
    441     Draw the canvas, then save it using `.image.imsave` (to which
    442     *pil_kwargs* and *metadata* are forwarded).
    443     """
-> 444     FigureCanvasAgg.draw(self)
    445     mpl.image.imsave(
    446         filename_or_obj, self.buffer_rgba(), format=fmt, origin="upper",
    447         dpi=self.figure.dpi, metadata=metadata, pil_kwargs=pil_kwargs)

File ~\anaconda3\Lib\site-packages\matplotlib\backends\backend_agg.py:387, in FigureCanvasAgg.draw(self)
    384 # Acquire a lock on the shared font cache.
    385 with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar
    386       else nullcontext()):
-> 387     self.figure.draw(self.renderer)
    388     # A GUI class may be need to update a window using this draw, so
    389     # don't forget to call the superclass.
    390     super().draw()

File ~\anaconda3\Lib\site-packages\matplotlib\artist.py:95, in _finalize_rasterization.<locals>.draw_wrapper(artist, renderer, *args, **kwargs)
     93 @wraps(draw)
     94 def draw_wrapper(artist, renderer, *args, **kwargs):
---> 95     result = draw(artist, renderer, *args, **kwargs)
     96     if renderer._rasterizing:
     97         renderer.stop_rasterizing()

File ~\anaconda3\Lib\site-packages\matplotlib\artist.py:72, in allow_rasterization.<locals>.draw_wrapper(artist, renderer)
     69     if artist.get_agg_filter() is not None:
     70         renderer.start_filter()
---> 72     return draw(artist, renderer)
     73 finally:
     74     if artist.get_agg_filter() is not None:

File ~\anaconda3\Lib\site-packages\matplotlib\figure.py:3161, in Figure.draw(self, renderer)
   3158         pass
   3159         # ValueError can occur when resizing a window.
-> 3161 self.patch.draw(renderer)
   3162 mimage._draw_list_compositing_images(
   3163     renderer, self, artists, self.suppressComposite)
   3165 renderer.close_group('figure')

File ~\anaconda3\Lib\site-packages\matplotlib\artist.py:72, in allow_rasterization.<locals>.draw_wrapper(artist, renderer)
     69     if artist.get_agg_filter() is not None:
     70         renderer.start_filter()
---> 72     return draw(artist, renderer)
     73 finally:
     74     if artist.get_agg_filter() is not None:

File ~\anaconda3\Lib\site-packages\matplotlib\patches.py:632, in Patch.draw(self, renderer)
    630 tpath = transform.transform_path_non_affine(path)
    631 affine = transform.get_affine()
--> 632 self._draw_paths_with_artist_properties(
    633     renderer,
    634     [(tpath, affine,
    635       # Work around a bug in the PDF and SVG renderers, which
    636       # do not draw the hatches if the facecolor is fully
    637       # transparent, but do if it is None.
    638       self._facecolor if self._facecolor[3] else None)])

File ~\anaconda3\Lib\site-packages\matplotlib\patches.py:617, in Patch._draw_paths_with_artist_properties(self, renderer, draw_path_args_list)
    614     renderer = PathEffectRenderer(self.get_path_effects(), renderer)
    616 for draw_path_args in draw_path_args_list:
--> 617     renderer.draw_path(gc, *draw_path_args)
    619 gc.restore()
    620 renderer.close_group('patch')

File ~\anaconda3\Lib\site-packages\matplotlib\backends\backend_agg.py:131, in RendererAgg.draw_path(self, gc, path, transform, rgbFace)
    129 else:
    130     try:
--> 131         self._renderer.draw_path(gc, path, transform, rgbFace)
    132     except OverflowError:
    133         cant_chunk = ''

ValueError: object __array__ method not producing an array
<Figure size 640x480 with 1 Axes>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 03:23:18