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 ...
随机推荐
- Java温故而知新(7)Object类及其方法讲解
一.java.lang.Object java.lang包在使用的时候无需显示导入,编译时由编译器自动导入. Object类是类层次结构的根,Java中所有的类从根本上都继承自这个类. Object类 ...
- ComfortColor.xcs
ComfortColor.xcs [comfort color] text=dce2e2text(bold)=dce2e2 magenta=dd3682magenta(bold)=dd3682 whi ...
- unity3d之如何控制人物移动、旋转和动画播放
代码源自噩梦射手,记录一下方便后续使用,顺便将老师的解释给备注上去_(:з」∠)_ using UnityEngine; using UnitySampleAssets.CrossPlatformIn ...
- Linux Loop设备 使用
有时候需要一个独立的块设备,loop设备是个方便的选择,可通过如下方式创建 dd if=/dev/zero of=./loopback_file bs=1M count=1000 losetup /d ...
- csharp: Getting all image files in folder
/// <summary> /// /// </summary> /// <param name="sender"></param> ...
- Python基础-map/reduce/filter
一.map Python内置函数,用法及说明如下: class map(object): """ map(func, *iterables) --> map obj ...
- arcgis 地理国情建库软件已完成
arcgis 地理国情软件已完成: 1.创建1:25000(或则其他比例尺)国家2000坐标系接合表 2.按照地理国情普查数据库标准,创建标准数据库 3.外业调查工作底图制作 4.矢量和影像数据批量裁 ...
- 【Machine Learning】分类与回归 区别
一.分类与回归的区别 两类监督学习 Classification Regression 分类和回归的区别在于输出变量的类型(而非输入变量). 定性输出称为分类,或者说是离散变量预测(discrete) ...
- JS复制DOM元素文字内容
要实现的效果:将HTML页面中的某个DOM元素例如DIV下面的文本内容进行复制. 实现过程如下: <html> <head> <title>Copy text De ...
- WCF服务上应用protobuf z
protobuf是google提供的一个开源序列化框架,类似于XML,JSON这样 的数据表示语言,其最大的特点是基于二进制,因此比传统的XML表示高效短小得多.虽然是二进制数据格式,但并没有因此变得 ...