AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79584062
Accepted
Sun Bear
Sun Bear
Asked: 2025-04-21 13:15:22 +0800 CST2025-04-21 13:15:22 +0800 CST 2025-04-21 13:15:22 +0800 CST

Aviso ao usuário: FigureCanvasAgg não é interativo e, portanto, não pode ser exibido

  • 772

Estou tentando mostrar uma figura matplotlib.pyplot no Python 3.10, mas não consigo. Estou ciente dessa questão e tentei as respostas, mas ainda não obtive sucesso. A distribuição padrão do sistema operacional é o Ubuntu 24.04, usando o Python 3.12 como padrão.

Veja como configurei o projeto Python 3.10 venve numpyinstalei matplotlib:

$ uv init test_py310 --python 3.10 
Initialized project `test-py310` at `/home/user/test_py310`
$ cd test_py310/
$ uv add numpy matplotlib
Using CPython 3.10.16
Creating virtual environment at: .venv
Resolved 12 packages in 136ms
Prepared 1 package in 1.96s
Installed 11 packages in 43ms
 + contourpy==1.3.2
 + cycler==0.12.1
 + fonttools==4.57.0
 + kiwisolver==1.4.8
 + matplotlib==3.10.1
 + numpy==2.2.5
 + packaging==25.0
 + pillow==11.2.1
 + pyparsing==3.2.3
 + python-dateutil==2.9.0.post0
 + six==1.17.0

test_matplotlib.py:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y, label='sin(x)', color='blue', linestyle='--')
plt.show()

Erro:

/home/user/Coding/test_py310/.venv/bin/python /home/user/test_py310/test_matplotlib,py 
/home/user/test_py310/test_matplotlib,py:7: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
  plt.show()

Em seguida, tentei instalar PyQt5conforme compartilhado nesta resposta , mas ainda encontrei erro.

$ uv add pyqt5
Resolved 15 packages in 89ms
Installed 3 packages in 45ms
 + pyqt5==5.15.11
 + pyqt5-qt5==5.15.16
 + pyqt5-sip==12.17.0

Executando o mesmo script python

$ /home/user/test_py310/.venv/bin/python /home/user/test_py310/test_matplotlib,py
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, wayland-xcomposite-egl, wayland-xcomposite-glx, webgl, xcb.

Aborted (core dumped)

Mudando import matplotlib.pyplot as pltpara:

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

Deu esse erro:

$ /home/user/test_py310/.venv/bin/python /home/user/test_py310/test_matplotlib,py
AttributeError: module '_tkinter' has no attribute '__file__'. Did you mean: '__name__'?

The above exception was the direct cause of the following exception:

ImportError: failed to load tkinter functions

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/user/test_py310/test_matplotlib,py", line 9, in <module>
    plt.plot(x, y, label='sin(x)', color='blue', linestyle='--')
  File "/home/user/test_py310/.venv/lib/python3.10/site-packages/matplotlib/pyplot.py", line 3827, in plot
    return gca().plot(
  File "/home/user/test_py310/.venv/lib/python3.10/site-packages/matplotlib/pyplot.py", line 2774, in gca
    return gcf().gca()
  File "/home/user/test_py310/.venv/lib/python3.10/site-packages/matplotlib/pyplot.py", line 1108, in gcf
    return figure()
  File "/home/user/test_py310/.venv/lib/python3.10/site-packages/matplotlib/pyplot.py", line 1042, in figure
    manager = new_figure_manager(
  File "/home/user/test_py310/.venv/lib/python3.10/site-packages/matplotlib/pyplot.py", line 551, in new_figure_manager
    _warn_if_gui_out_of_main_thread()
  File "/home/user/test_py310/.venv/lib/python3.10/site-packages/matplotlib/pyplot.py", line 528, in _warn_if_gui_out_of_main_thread
    canvas_class = cast(type[FigureCanvasBase], _get_backend_mod().FigureCanvas)
  File "/home/user/test_py310/.venv/lib/python3.10/site-packages/matplotlib/pyplot.py", line 369, in _get_backend_mod
    switch_backend(rcParams._get("backend"))
  File "/home/user/test_py310/.venv/lib/python3.10/site-packages/matplotlib/pyplot.py", line 425, in switch_backend
    module = backend_registry.load_backend_module(newbackend)
  File "/home/user/test_py310/.venv/lib/python3.10/site-packages/matplotlib/backends/registry.py", line 317, in load_backend_module
    return importlib.import_module(module_name)
  File "/home/user/.local/share/uv/python/cpython-3.10.16-linux-x86_64-gnu/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/home/user/test_py310/.venv/lib/python3.10/site-packages/matplotlib/backends/backend_tkagg.py", line 1, in <module>
    from . import _backend_tk
  File "/home/user/test_py310/.venv/lib/python3.10/site-packages/matplotlib/backends/_backend_tk.py", line 25, in <module>
    from . import _tkagg
ImportError: initialization failed

Usando

import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt

deu

$ /home/user/test_py310/.venv/bin/python /home/user/test_py310/test_matplotlib,py
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, wayland-xcomposite-egl, wayland-xcomposite-glx, webgl, xcb.

Aborted (core dumped)

Também removi o pyqt5 e adicionei o pyqt6, e usei, matplotlib.use('Qt6Agg')mas recebi este erro:

$ /home/user/test_py310/.venv/bin/python /home/user/test_py310/test_matplotlib,py
Traceback (most recent call last):
  File "/home/user/test_py310/test_matplotlib,py", line 4, in <module>
    matplotlib.use('Qt6Agg')
  File "/home/user/test_py310/.venv/lib/python3.10/site-packages/matplotlib/__init__.py", line 1265, in use
    name = rcsetup.validate_backend(backend)
  File "/home/user/test_py310/.venv/lib/python3.10/site-packages/matplotlib/rcsetup.py", line 278, in validate_backend
    raise ValueError(msg)
ValueError: 'Qt6Agg' is not a valid value for backend; supported values are ['gtk3agg', 'gtk3cairo', 'gtk4agg', 'gtk4cairo', 'macosx', 'nbagg', 'notebook', 'qtagg', 'qtcairo', 'qt5agg', 'qt5cairo', 'tkagg', 'tkcairo', 'webagg', 'wx', 'wxagg', 'wxcairo', 'agg', 'cairo', 'pdf', 'pgf', 'ps', 'svg', 'template']

O que devo fazer para plotar uma figura matplotlib.pyplot em um ambiente virtual instalado com o Python 3.10? Só para acrescentar, consigo plotar uma figura matplotlib.pyplot em um ambiente virtual separado usando o Python 3.12.

python
  • 1 1 respostas
  • 78 Views

1 respostas

  • Voted
  1. Best Answer
    furas
    2025-04-21T20:13:07+08:002025-04-21T20:13:07+08:00

    Eu uso o Linux Mint 22 baseado no Ubuntu 24.04.

    O código funciona para mim com uve Python 3.10quando eu instalo PyQt6, mas não comPyQt5

    E não precisa de linha matplotlib.use('Qt5Agg')nem matplotlib.use('QtAgg')
    (mas funciona também com essas linhas)


    Quanto a tkinter: normalmente tkinteré instalado diretamente com, Python
    mas no Ubuntu é um pacote separado que é instalado com apt install python3.10-tk.
    E acho que pode ser um problema instalá-lo em uma versão instalada com uv.

    BTW: na versão Ubuntu Server(que não tem o X11 instalado e geralmente é usada em computadores sem monitor) pode ter o Python sem ele, tkinterpois tkinteré inútil sem X11um monitor.

    Não há problema quando você instala o completo Python 3.10usando apt install python3.10-fullou apt install python3.10 python3.10-tke depois cria um ambiente virtual compython3.10 -m venv ...


    Código completo usado para testes:

    $ uv init test_py310 --python 3.10 
    $ cd test_py310/
    $ uv add numpy matplotlib pyqt6
    $ uv run main.py
    

    main.py

    Permite executar com parâmetros comouv run main.py tkagg

    import sys
    print('>>> Executable:', sys.executable)
    
    import numpy as np
    import matplotlib.pyplot as plt
    
    import matplotlib
    # matplotlib.use('QtAgg')   # works for me when installed `PyQt6` but not `PyQt5`
    # matplotlib.use('Qt5Agg')  # works for me when installed `PyQt6` but not `PyQt5`
    # matplotlib.use('Qt6Agg')  # doesn't exist `Qt6Agg`
    # matplotlib.use('TkAgg')   # `tkinter` is not installed with `uv`
    
    if len(sys.argv) > 1:
        print('>>> Using:', sys.argv[1])
        matplotlib.use(sys.argv[1])
    
    x = np.linspace(0, 10, 100)
    y = np.sin(x)
    plt.plot(x, y, label='sin(x)', color='blue', linestyle='--')
    # plt.ion()  # ion = Interactive ON
    plt.show()
    

    Esses comandos de configuração funcionaram no Ubuntu 24.04 (testado por @SunBear):

    $ uv init test_py310 --python 3.10 
    $ cd test_py310/
    $ uv add numpy matplotlib pyqt6
    $ sudo apt install python3.10-tk libxcb-cursor0
    $ uv run main.py
    
    • 2

relate perguntas

  • Como divido o loop for em 3 quadros de dados individuais?

  • Como verificar se todas as colunas flutuantes em um Pandas DataFrame são aproximadamente iguais ou próximas

  • Como funciona o "load_dataset", já que não está detectando arquivos de exemplo?

  • Por que a comparação de string pandas.eval() retorna False

  • Python tkinter/ ttkboostrap dateentry não funciona quando no estado somente leitura

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve