如何解决matplotlib运行出现的Invalid DISPLAY variable

简介: 最近在服务器上运行matplotlib相关的脚本时遇到了"Invalid DISPLAY variable"报错,从报错中就可以知道这是因为没有显示设备导致的报错。

最近在服务器上运行matplotlib相关的脚本时遇到了"Invalid DISPLAY variable"报错,从报错中就可以知道这是因为没有显示设备导致的报错。

解决方案:

方案一: ~/.config/matplotlib/matplotlibr,在里面添加backend : Agg

这个方案不一定有用,如果失效考虑下面两种

方案二: 更换后端

可以先设置后端,然后导入pyplot

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

或者先导入pyplot,然后切换后端

import matplotlib.pyplot as plt
plt.switch_backend('Agg')

之后可以以Pdf形式或者其他格式保存到硬盘上。

from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
plt.switch_backend('Agg')
pdf = PdfPages('cut_figure.pdf')         #先创建一个pdf文件
plt.figure()
...
...
pdf.savefig()                            #将图片保存在pdf文件中
plt.close()
pdf.close()                              #这句必须有,否则程序结束pdf文件无法打开
目录
相关文章
|
9月前
variable `xxx' has initializer but incomplete type的解决方法
variable `xxx' has initializer but incomplete type的解决方法
142 0
|
4月前
|
Ubuntu 定位技术 Python
numpy库报错has no attribute ‘_no_nep50_warning‘的解决
numpy库报错has no attribute ‘_no_nep50_warning‘的解决
|
4月前
|
数据库
Greenplum【异常 03】COPY命令报错 > ERROR: invalid input syntax for type double precision: ““(问题分析及解决方案)数据去重
Greenplum【异常 03】COPY命令报错 > ERROR: invalid input syntax for type double precision: ““(问题分析及解决方案)数据去重
73 0
|
5月前
|
SQL Java 数据库连接
错误:FUNCTION simple_notebook.count does not exist.解决方法
错误:FUNCTION simple_notebook.count does not exist.解决方法
|
5月前
|
JSON 小程序 API
小程序踩坑-Setting data field "list" to undefined is invalid.
小程序踩坑-Setting data field "list" to undefined is invalid.
120 0
|
Ubuntu 开发工具 芯片
安装mkimage工具,解决报错“Invalid CPU Type - valid names are:”
安装mkimage工具,解决报错“Invalid CPU Type - valid names are:”
129 0
安装mkimage工具,解决报错“Invalid CPU Type - valid names are:”
解决办法:RuntimeError: dictionary changed size during iteration
解决办法:RuntimeError: dictionary changed size during iteration
86 0
|
Python
如何处理错误消息Unable to install breakpoint due to missing line number attributes
如何处理错误消息Unable to install breakpoint due to missing line number attributes
158 0
如何处理错误消息Unable to install breakpoint due to missing line number attributes
C中遇到错误error: jump to label [-fpermissive]的解决办法
C中遇到错误error: jump to label [-fpermissive]的解决办法
897 0