Python 从 bash 终端运行文件时,不显示 Matplotlib 图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36269746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:40:14  来源:igfitidea点击:

Matplotlib plots aren't shown when running file from bash terminal

pythonbashmatplotlibterminal

提问by drake

Plots are normally shown when I run files from the ipython shell or from an ipython notebook, but they don't show up when I run the file from a bash terminal -- everything else works fine when is run from a bash terminal.

当我从 ipython shell 或 ipython notebook 运行文件时,通常会显示图,但当我从 bash 终端运行文件时,它们不会显示——当从 bash 终端运行时,其他一切正常。

Sample python script (trial.py):

示例python脚本(trial.py):

import matplotlib.pyplot as plt

print 'please, show my graph'

plt.plot([1,2,3], [1,2,3])

plt.show()

This is what I get (plot doesn't show up):

这就是我得到的(情节没有出现):

[~/Desktop]$ python trial.py
please, show my graph
[~/Desktop]$

If I do

如果我做

import matplotlib
matplotlib.use('TkAgg')

before importing pyplot, then a window opens and closes immediately when I run it from the terminal.

在导入 pyplot 之前,当我从终端运行它时,一个窗口会立即打开和关闭。

I've tried different ways of importing modules without success:

我尝试了不同的导入模块的方法,但没有成功:

import matplotlib.pyplot as plt
import matplotlib.pylab as plt
from matplotlib import pyplot as plt
from matplotlib import pylab as plt

I have the plt.show() function in my file.

我的文件中有 plt.show() 函数。

Do you know how I can fix it?

你知道我该如何解决吗?

Some info about versions and installation:

关于版本和安装的一些信息:

I'm on a mac OSX 10.11.3.

我在 Mac OSX 10.11.3 上。

In [61]: print matplotlib.__file__
/usr/local/lib/python2.7/site-packages/matplotlib/__init__.pyc

In [62]: print matplotlib.__version__
1.4.2

In [64]: print sys.version
2.7.9 (default, Apr  7 2015, 07:58:25)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]

In [65]: matplotlib.get_backend()
Out[65]: u'MacOSX'

回答by Munir

You need to add matplotlib.pyplot.show()in your code to show plots in non-interactive mode. See docs at http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show

您需要添加matplotlib.pyplot.show()代码以在非交互模式下显示绘图。请参阅http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show 上的文档

编辑:

After further info from OP, blocking had to be enabled explicitly using plt.show(block=True).

从 OP 获得更多信息后,必须使用plt.show(block=True).