ssh调用matplotlib绘图报错RuntimeError: Invalid DISPLAY variable
1.问题:在本地用matplotlib绘图可以,但是在ssh远程绘图的时候会报错 RuntimeError: Invalid DISPLAY variable
2.原因:matplotlib的默认backend是TkAgg,而FltkAgg, GTK, GTKAgg, GTKCairo, TkAgg , Wx or WxAgg这几个backend都要求有GUI图形界面的,所以在ssh操作的时候会报错.
import matplotlib.pyplot as plt
Backend TkAgg is interactive backend. Turning interactive mode on. plt.get_backend()
Out[3]: u'TkAgg'
3.解决方法:指定不需要GUI的backend(Agg, Cairo, PS, PDF or SVG)
import matplotlib.pyplot as plt
plt.switch_backend('agg')
4.源码
查看plt.switch_backend()的源码实现和解析:

def switch_backend(newbackend):
"""
Switch the default backend. This feature is **experimental**, and
is only expected to work switching to an image backend. e.g., if
you have a bunch of PostScript scripts that you want to run from
an interactive ipython session, you may want to switch to the PS
backend before running them to avoid having a bunch of GUI windows
popup. If you try to interactively switch from one GUI backend to
another, you will explode. Calling this command will close all open windows.
"""
close('all')
global _backend_mod, new_figure_manager, draw_if_interactive, _show
matplotlib.use(newbackend, warn=False, force=True)
from matplotlib.backends import pylab_setup
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()

查看matplotlib.use()的源码:

def use(arg, warn=True, force=False):
"""
Set the matplotlib backend to one of the known backends. The argument is case-insensitive. *warn* specifies whether a
warning should be issued if a backend has already been set up.
*force* is an **experimental** flag that tells matplotlib to
attempt to initialize a new backend by reloading the backend
module. .. note:: This function must be called *before* importing pyplot for
the first time; or, if you are not using pyplot, it must be called
before importing matplotlib.backends. If warn is True, a warning
is issued if you try and call this after pylab or pyplot have been
loaded. In certain black magic use cases, e.g.
:func:`pyplot.switch_backend`, we are doing the reloading necessary to
make the backend switch work (in some cases, e.g., pure image
backends) so one can set warn=False to suppress the warnings. To find out which backend is currently set, see
:func:`matplotlib.get_backend`. """
# Lets determine the proper backend name first
if arg.startswith('module://'):
name = arg
else:
# Lowercase only non-module backend names (modules are case-sensitive)
arg = arg.lower()
name = validate_backend(arg) # Check if we've already set up a backend
if 'matplotlib.backends' in sys.modules:
# Warn only if called with a different name
if (rcParams['backend'] != name) and warn:
warnings.warn(_use_error_msg) # Unless we've been told to force it, just return
if not force:
return
need_reload = True
else:
need_reload = False # Store the backend name
rcParams['backend'] = name # If needed we reload here because a lot of setup code is triggered on
# module import. See backends/__init__.py for more detail.
if need_reload:
reload(sys.modules['matplotlib.backends'])

参考:DISPLAY error matplotlib http://chewpichai.blogspot.com/2008/01/display-error-matplotlib.html 。原文可能被墙了,需要设法翻一下。
原文内容:

DISPLAY error matplotlib
When error occur about this "$DISPLAY not set" when you run python code that use matplotlib this happened because your matplotlib backend is set to FltkAgg, GTK, GTKAgg, GTKCairo, TkAgg , Wx or WxAgg they required a GUI that why error occur. To solve this you must specific other backend that not required GUI (Agg, Cairo, PS, PDF or SVG) when use matplotlib like this
In code
import matplotlib
matplotlib.use('Agg')
In command line use -d option
python subplot_demo.py -dAgg Remember when call savefig('filename') don't give it extension this will handle by backend that you specific e.g Agg will create file filename.png

ssh调用matplotlib绘图报错RuntimeError: Invalid DISPLAY variable的更多相关文章
- matplotlib 绘图报错 RuntimeError: Invalid DISPLAY variable
ssh 远程登录 Linux 服务器使用 matplotlib.pyplot 绘图时报错 原因: matplotlib 在 windows 下的默认 backend 是 TkAgg:在 Linux 下 ...
- [Python] RuntimeError: Invalid DISPLAY variable
1.问题:在本地用matplotlib绘图可以,但是在ssh远程绘图的时候会报错 RuntimeError: Invalid DISPLAY variable 2.原因:matplotlib的默认ba ...
- 错误RuntimeError: Invalid DISPLAY variable
原因:matplotlib的backend中的FltkAgg, GTK, GTKAgg, GTKCairo, TkAgg , Wx or WxAgg这几个backend都要求有GUI图形界面的 首先查 ...
- pylab,matplotlib Invalid DISPLAY variable
在cetos 服务器使用源码包,安装matplotlib, 安装成功后, import pylab as pl pl.figure(figsize=(16,8)) python 解析器报错,Inval ...
- 安装tesserocr的步骤和报错RuntimeError: Failed to init API, possibly an invalid tessdata path解决办法
1,首先下载合适的tesseract-ocr的版本 2,然后安装到这一步注意要勾选这一项来安装OCR识别支持的语言包,这样OCR就可以识别多国语言,然后就可以一直点击下一步完成安装. 3,安装tess ...
- c++中sort函数调用报错Expression : invalid operator <的内部原理 及解决办法
转自:https://www.cnblogs.com/huoyao/p/4248925.html 当我们调用sort函数进行排序时,中的比较函数如果写成如下 bool cmp(const int &a ...
- c++中sort函数调用报错Expression : invalid operator <的内部原理
当我们调用sort函数进行排序时,中的比较函数如果写成如下 bool cmp(const int &a, const int &b) { if(a!=b) return a<b; ...
- Jade报错:Invalid indentation,you can use tabs or spaces but not both问题
现象:通过html生成jade文件之后,更改jade文件时,语句没什么问题的情况下,jade文件编译不通过,报错:Invalid indentation,you can use tabs or spa ...
- Django报错:提交表单报错---RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and you have APPEND_SLASH set.
Django报错:提交表单报错---RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and ...
随机推荐
- Spring_Spring的特点
一.非侵入式编程 Spring框架的API不会再业务逻辑上出现,即业务逻辑是POJO(Plain Ordinary Java Object).由于业务逻辑中没有Spring的API,所以业务逻辑可以从 ...
- lintcode题目记录4
Russian Doll Envelopes Largest Divisible Subset Two Sum - Input array is sorted Russian Doll ...
- centos install redis
1. 下载 [logan@localhost java]$ wget http://download.redis.io/releases/redis-3.2.8.tar.gz2. 解压 [log ...
- window onload || jquery $()
1.window 的 onload 机制只指定一个函数,且在页面DOM及静态资源加载完之后执行: window.onload = function(){ alert(); } 2.$(document ...
- 11.6NOIP模拟赛解题报告
心路历程 预计得分:\(100 + 100 + 100 = 300\) 实际得分:\(100 +100 +100 = 300\) 学OI两年终于AK了一次qwq(虽然题目炒鸡水..) 纪念一下这令人激 ...
- 【Anaconda】windows安装报错:UnicodeDecodeError解决方法
UnicodeDecodeError: 'utf8' codec can't decode byte 0xce in position 11: invalid continuation byte 解决 ...
- javascript 事件相关使用总结01
javascript 事件相关使用总结01 这里总结一下js事件相关的经验. addEventLinstener()介绍 注册事件最基础的函数是这个 target.addEventListener(t ...
- 微软与Node.js的开源之旅
微软近年来在开源领域可谓是大刀阔斧的前进中,继2015年微软与红帽合作,微软智能云Azure与Linux进一步融合等举措之后,2016年,微软继续加大开源之举,大力推进Node.js的开发和开源社区的 ...
- Windows ->> FIX: “The security database on the server does not have a computer account for this workstation trust relationship”
前几天在做AlwaysOn实验时遇到搭建活动目录域时某台已经加入AD的机器无法以域管理员账户登录的情况. 报错信息是:The security database on the server does ...
- Best Time to Buy and Sell Stock II--疑惑
https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 代码如下时能AC class Solution { publi ...