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的更多相关文章

  1. matplotlib 绘图报错 RuntimeError: Invalid DISPLAY variable

    ssh 远程登录 Linux 服务器使用 matplotlib.pyplot 绘图时报错 原因: matplotlib 在 windows 下的默认 backend 是 TkAgg:在 Linux 下 ...

  2. [Python] RuntimeError: Invalid DISPLAY variable

    1.问题:在本地用matplotlib绘图可以,但是在ssh远程绘图的时候会报错 RuntimeError: Invalid DISPLAY variable 2.原因:matplotlib的默认ba ...

  3. 错误RuntimeError: Invalid DISPLAY variable

    原因:matplotlib的backend中的FltkAgg, GTK, GTKAgg, GTKCairo, TkAgg , Wx or WxAgg这几个backend都要求有GUI图形界面的 首先查 ...

  4. pylab,matplotlib Invalid DISPLAY variable

    在cetos 服务器使用源码包,安装matplotlib, 安装成功后, import pylab as pl pl.figure(figsize=(16,8)) python 解析器报错,Inval ...

  5. 安装tesserocr的步骤和报错RuntimeError: Failed to init API, possibly an invalid tessdata path解决办法

    1,首先下载合适的tesseract-ocr的版本 2,然后安装到这一步注意要勾选这一项来安装OCR识别支持的语言包,这样OCR就可以识别多国语言,然后就可以一直点击下一步完成安装. 3,安装tess ...

  6. c++中sort函数调用报错Expression : invalid operator <的内部原理 及解决办法

    转自:https://www.cnblogs.com/huoyao/p/4248925.html 当我们调用sort函数进行排序时,中的比较函数如果写成如下 bool cmp(const int &a ...

  7. c++中sort函数调用报错Expression : invalid operator <的内部原理

    当我们调用sort函数进行排序时,中的比较函数如果写成如下 bool cmp(const int &a, const int &b) { if(a!=b) return a<b; ...

  8. Jade报错:Invalid indentation,you can use tabs or spaces but not both问题

    现象:通过html生成jade文件之后,更改jade文件时,语句没什么问题的情况下,jade文件编译不通过,报错:Invalid indentation,you can use tabs or spa ...

  9. 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 ...

随机推荐

  1. GuavaCache实现堆缓存

    一.缓存 频繁地数据库I/O是很大的负担,而缓存是减少I/O提高性能的银弹. 缓存的实现一般上是以类似map的键值对的形式,并对外提供put和get方法,但缓存空间不能无限扩大,所以它得有一种缓存清除 ...

  2. MongoDB 学习(一)安装配置和简单应用

    一.安装和部署 1.服务端安装 1.官网下载(官方网站 https://www.mongodb.org/downloads/#production),傻瓜式安装,注意修改安装路径. 安装完成后的目录结 ...

  3. console.log出来的信息不一定是真的

    一.问题 拿接口取值,明明this.props.chartsValue[0]已经返回json数据,结果this.props.chartsValue[0].history报错:无法获得undefined ...

  4. webpack-loader原理

    loader loader 是导出为一个函数的 node 模块.该函数在 loader 转换资源的时候调用.给定的函数将调用 loader API,并通过 this 上下文访问. loader配置 { ...

  5. java 文件的上传和下载

    主要介绍使用 smartupload.jar 包中的方法对文件的上传和下载.上传时文件是存放在服务器中,我用的是tamcat. 首先建立一个servlet 类,对文件的操作 package com.d ...

  6. JavaScript的重载(通过argument.length)

    偶然间在博客园看到的关于js的重载(重载就是一组具有相同名字.不同参数列表,实现不同操作的函数或方法)问题,作为初学者,在看红宝书的时候,记得书中有概念说明js是没有重载的 所以,觉得有必要把这一段 ...

  7. java idea+ssm框架遇到的问题

    0.学习教程 http://www.cnblogs.com/jiekzou/p/9205117.html https://github.com/crossoverJie/SSM 1.gradle没刷新 ...

  8. 01_编程规约——OOP规约

    1.[强制]避免通过一个类的对象引用访问此类的静态变量或静态方法,避免增加编译器解析成本,直接用“类名.变量名”访问即可. 2.[强制]所有的覆盖方法,必须加@Override注解 说明:加@Over ...

  9. KLEE错误汇报一:One phenomenon after the execution using klee

    https://github.com/klee/klee/issues/649#issuecomment-300424204 Hi, all,      If you write test.c wit ...

  10. WPF&Silverlight5 常用功能差异

    一晃从Wpf转到sl也有半年多了,总想总结一下wpf和sl的差异,今天终于下笔. 首先来个整体图: 通过上图可以发现其实sl只是使用了wpf的一小部分,只是sl依赖的freamwork有很大部分都一样 ...