导入Matplotlib而不显示 [英] Import Matplotlib without a display

查看:112
本文介绍了导入Matplotlib而不显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Linux服务器上运行python脚本,并制作和保存一些绘图.我已经安装了ipythonpylabmatplotlib,但是当我运行脚本时,出现此错误:

I am trying to run a python script on my linux server and make and save some plots. I have installed ipython and pylab and matplotlib but then when I run my script I get this error:

Traceback (most recent call last):
  File "/root/dining_hall_graph.py", line 14, in <module>
    from pylab import * 
  File "/usr/lib64/python2.7/site-packages/pylab.py", line 1, in <module>
    from matplotlib.pylab import *
  File "/usr/lib64/python2.7/site-packages/matplotlib/pylab.py", line 265, in <module>
    from matplotlib.pyplot import *
  File "/usr/lib64/python2.7/site-packages/matplotlib/pyplot.py", line 97, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "/usr/lib64/python2.7/site-packages/matplotlib/backends/__init__.py", line 25, in pylab_setup
    globals(),locals(),[backend_name])
  File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_gtkagg.py", line 10, in <module>
    from matplotlib.backends.backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\
  File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_gtk.py", line 13, in <module>
    import gtk; gdk = gtk.gdk
  File "/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py", line 64, in <module>
    _init()
  File "/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py", line 52, in _init
    _gtk.init_check()
RuntimeError: could not open display

在此行上from pylab import *

如何在Linux服务器上运行的python脚本中绘制和保存图形?

How can I plot and save graphs in my python script that I am running on my linux server?

谢谢

推荐答案

您几乎永远不应使用from pylab import *.

You should almost never use from pylab import *.

numpyscipymatplotlib导入所需的内容.

Import what you need from numpy, scipy and matplotlib.

在无显示的计算机上,您需要使用agg后端:

On machines without display, you need to use the agg backend:

您可以通过指定环境变量MPLBACKEND

You can achieve this by specifying the environmental variable MPLBACKEND

$ MPLBACKEND=Agg python plot.py

或者在导入matplotlib.pyplot之前先导入matplotlib :

Or by importing matplotlib before importing matplotlib.pyplot:

import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt

plt.plot([1, 2, 1])
plt.savefig('test.pdf')

要将其设置为默认值,可以创建一个名为matplotlibrc的文件 在当前目录中或在$HOME/.config/matplotlib中具有以下内容:

To make this the default, you can create a file called matplotlibrc in the current directory or in $HOME/.config/matplotlib with the following content:

backend: Agg

您还可以启用X转发,这样绘图将在您的主机上弹出:

Ot you could enable X-Forwarding, so the plots will pop up on your host machine:

ssh -X user@server

这篇关于导入Matplotlib而不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆