- 问题
使用Pycharm的Python控制端,绘图时出现图像空白,一直显示未响应,强制关闭后,显示进程已结束,退出代码。
解决方法。设置Matplotlib的后端为Qt5Agg
import matplotlib
matplotlib.use('Qt5Agg')
- Matplotlib的前端与后端
有些人在Python shell中交互式地使用Matplotlib,输入命令后就会弹出绘图窗口。有些人运行Jupyter notebook并绘制内联图来快速进行数据分析。还有人将Matplotlib嵌入到图形用户界面中,如PyQt或PyGObject,以构建丰富的应用程序。有些人在批处理脚本中使用Matplotlib从数值模拟中生成postscript图像,还有一些人运行web应用程序服务器来动态地提供图形。为了支持所有这些用例,Matplotlib可以有不同的输出,每一种功能都被称为后端。
“前端”是面向用户的代码,即绘图代码,而“后端”在幕后完成所有辛苦的工作以生成图形。后端有两种类型:用户界面后端(用于PyQt/PySide、PyGObject、Tkinter、wxPython或macOS/Cocoa中);也称为“交互式后端”)和硬拷贝后端,用于制作图像文件(PNG、SVG、PDF、PS;也称为“非交互式后端”)。
- 如何查看当前后端的类型?
import matplotlib
matplotlib.get_backend()
matplotlib.matplotlib_fname()
默认的后端是'QtAgg',后一条语句是输出当前Matplotlib的配置文件的路径。
- 配置后端的方式
有三种办法,第一种是代码配置法。
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
第二种是设置环境变量的方法。
#Linux系统中
> export MPLBACKEND=qtagg
> python simple_plot.py
> MPLBACKEND=qtagg python simple_plot.py
#window系统
> set MPLBACKEND=qtagg
> python simple_plot.py
另外也可通过修改Matplotlib的配置文件来实现。
backend : qtagg # use pyqt with antigrain (agg) rendering
- Matplotlib内置的后端
非交互式的后端
Renderer | Filetypes | Description |
---|---|---|
AGG | png | raster graphics -- high quality images using the Anti-Grain Geometry engine |
| | vector graphics -- Portable Document Format |
PS | ps, eps | vector graphics -- Postscript output |
SVG | svg | vector graphics -- Scalable Vector Graphics |
PGF | pgf, pdf | |
Cairo | png, ps, pdf, svg |
交互式的后端
Backend | Description |
---|---|
QtAgg | Agg rendering in a Qt canvas (requires PyQt or Qt for Python, a.k.a. PySide). This backend can be activated in IPython with |
ipympl | Agg rendering embedded in a Jupyter widget. (requires ipympl). This backend can be enabled in a Jupyter notebook with |
GTK3Agg | Agg rendering to a GTK 3.x canvas (requires PyGObject, and pycairo or cairocffi). This backend can be activated in IPython with |
GTK4Agg | Agg rendering to a GTK 4.x canvas (requires PyGObject, and pycairo or cairocffi). This backend can be activated in IPython with |
macosx | Agg rendering into a Cocoa canvas in OSX. This backend can be activated in IPython with |
TkAgg | Agg rendering to a Tk canvas (requires TkInter). This backend can be activated in IPython with |
nbAgg | Embed an interactive figure in a Jupyter classic notebook. This backend can be enabled in Jupyter notebooks via |
WebAgg | On |
GTK3Cairo | Cairo rendering to a GTK 3.x canvas (requires PyGObject, and pycairo or cairocffi). |
GTK4Cairo | Cairo rendering to a GTK 4.x canvas (requires PyGObject, and pycairo or cairocffi). |
wxAgg | Agg rendering to a wxWidgets canvas (requires wxPython 4). This backend can be activated in IPython with |