警告「FigureCanvasAgg is non-interactive, and thus cannot be shown」の解決方法
発生環境
- Windows 10
- PyCharm 2021.3.3 Professional
- Python 3.11.5
- matplotlib 3.8.1
問題の本質
Pythonでmatplotlib
を使用してplt.show()
を実行した際に、次の警告が表示されます:
none
UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown plt.show()
これは「Agg」バックエンドが非対話型であり、画像表示機能を持たないことが原因です。以下が問題の核心部分です:
python
import matplotlib
matplotlib.use('Agg') # ← 非対話型バックエンドの指定
import matplotlib.pyplot as plt
効果的な解決策
解決策1: デフォルトバックエンドに変更(推奨)
- コードから
matplotlib.use('Agg')
を完全に削除 - Tkinterをインストール(Pythonに同梱されていない場合)
bash
# Debian/Ubuntu
sudo apt-get install python3-tk
# macOS (Homebrew)
brew install python-tk
デフォルト動作の確認
python
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show() # 正常に表示される
解決策2: 代替バックエンドの使用
Tkinterが利用できない環境では、別のバックエンドを明示的に指定します:
python
import matplotlib
matplotlib.use('TkAgg') # Tkinterベースのバックエンド
import matplotlib.pyplot as plt
python
import matplotlib
matplotlib.use('Qt6Agg') # Qt6ベースのバックエンド
import matplotlib.pyplot as plt
必要なライブラリのインストール
PyQt6(最新推奨)
bash
pip install PyQt6
Tkinter(軽量ソリューション)
bash
# Windows: PythonインストーラでTcl/Tkを有効化
# Linux/macOS: 上記のインストールコマンド実行
PySide2(Qtの代替)
bash
pip install PySide2
環境別対応ガイド
PyCharmユーザー向け
- Settings > Python Interpreter で正しいインタプリタを選択
- 仮想環境使用時は必要なライブラリがインストールされているか確認
- 実行設定で
Show plots in tool window
が有効になっているか確認
VS Codeユーザー向け
.vscode/settings.json
に次を追加:
json
{
"jupyter.runStartupCommands": [
"import matplotlib",
"matplotlib.use('TkAgg')"
]
}
永続的な設定変更
matplotlibrc
ファイルを編集(場所はmatplotlib.matplotlib_fname()
で確認):
ini
# matplotlibrc内の該当行
backend: TkAgg # デフォルトバックエンド変更
よくある落とし穴と対処法
注意点
matplotlib
インポート前にmatplotlib.use()
を呼び出す必要がある- 複数モジュールでmatplotlibをインポートする場合、最初のインポート時にのみバックエンド設定が適用される
複数モジュールでインポートされる場合の安全なコード例:
python
import sys
if 'matplotlib' not in sys.modules:
import matplotlib
matplotlib.use('TkAgg') # 最初のインポートでのみ設定
import matplotlib.pyplot as plt
技術的背景
Matplotlibはバックエンドシステムで描画方法を切り替えます:
Agg
:ファイル出力専用(PNG等生成)TkAgg
:TkinterベースのGUIQt5Agg
/Qt6Agg
:QtベースのGUImacosx
:macOSネイティブ
開発環境ではTkAgg
やQtAgg
のようなインタラクティブバックエンドを選択することで、plt.show()
が正常動作します。