Ubuntu升级至24.04.1 LTS后Matplotlib出现报错问题
问题描述
将Ubuntu系统升级至24.04.1 LTS后,Anaconda Python环境中的Matplotlib出现异常,其他科学库运行正常。
测试代码:
import matplotlib.pyplot as plt import numpy as np plt.hist(np.random.normal(10))
执行后返回计算结果,但触发回调错误,报错信息如下:
plt.hist(np.random.normal(10)) Out[7]: (array([0., 0., 0., 0., 0., 1., 0., 0., 0., 0.]), array([8.40468485, 8.50468485, 8.60468485, 8.70468485, 8.80468485, 8.90468485, 9.00468485, 9.10468485, 9.20468485, 9.30468485, 9.40468485]), <BarContainer object of 10 artists>)Error in callback <function _draw_all_if_interactive at 0x7ff6a0b9cc20> (for post_execute), with arguments args (),kwargs {}: Traceback (most recent call last): File ~/miniconda3/lib/python3.11/site-packages/matplotlib/pyplot.py:268 in _draw_all_if_interactive draw_all() File ~/miniconda3/lib/python3.11/site-packages/matplotlib/_pylab_helpers.py:131 in draw_all manager.canvas.draw_idle() File ~/miniconda3/lib/python3.11/site-packages/matplotlib/backend_bases.py:1905 in draw_idle self.draw(*args, **kwargs) File ~/miniconda3/lib/python3.11/site-packages/matplotlib/backends/backend_agg.py:387 in draw self.figure.draw(self.renderer) File ~/miniconda3/lib/python3.11/site-packages/matplotlib/artist.py:95 in draw_wrapper result = draw(artist, renderer, *args, **kwargs) File ~/miniconda3/lib/python3.11/site-packages/matplotlib/artist.py:72 in draw_wrapper return draw(artist, renderer) File ~/miniconda3/lib/python3.11/site-packages/matplotlib/figure.py:3161 in draw self.patch.draw(renderer) File ~/miniconda3/lib/python3.11/site-packages/matplotlib/artist.py:72 in draw_wrapper return draw(artist, renderer) File ~/miniconda3/lib/python3.11/site-packages/matplotlib/patches.py:632 in draw self._draw_paths_with_artist_properties( File ~/miniconda3/lib/python3.11/site-packages/matplotlib/patches.py:617 in _draw_paths_with_artist_properties renderer.draw_path(gc, *draw_path_args) File ~/miniconda3/lib/python3.11/site-packages/matplotlib/backends/backend_agg.py:131 in draw_path self._renderer.draw_path(gc, path, transform, rgbFace) ValueError: object __array__ method not producing an array
当前环境版本:Numpy 1.26.4,Matplotlib 3.9.1
解决方案
临时切换Matplotlib后端:在代码开头添加以下两行,强制使用非交互式后端规避绘图回调错误
import matplotlib matplotlib.use('Agg')若需要交互式绘图,可尝试切换到
TkAgg或Qt5Agg后端,需确保系统已安装对应依赖库。重新安装并降级Matplotlib:卸载现有版本后安装兼容Ubuntu 24.04的稳定版本
pip uninstall matplotlib -y pip install matplotlib==3.8.4补充系统图形依赖:Ubuntu升级后可能缺失必要的绘图依赖,执行以下命令安装
sudo apt-get install libpng-dev libfreetype6-dev libxcb-xinerama0重建Anaconda虚拟环境:若上述方法无效,创建全新环境避免依赖冲突
conda create -n new_sci_env python=3.11 numpy matplotlib conda activate new_sci_env
内容的提问来源于stack exchange,提问作者Taylor
相关产品推荐
相关产品推荐

