Python 为什么 matplotlib 不绘图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14558843/
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
Why matplotlib does not plot?
提问by Roman
I started to learn MatPlotLib using thistutorial for beginners. Here is the first example.
我开始使用本教程为初学者学习 MatPlotLib 。这是第一个例子。
from pylab import *
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)
If I write these 3 lines into my python file and execute it in the command line (by typing python file_name.py), nothing happens. No error message, no plot.
如果我将这 3 行写入我的 python 文件并在命令行中执行它(通过键入python file_name.py),则没有任何反应。没有错误信息,没有情节。
Does anybody know why I do not see the plot?
有人知道为什么我看不到情节吗?
ADDED
添加
Of course I need to use show. But even if I add the following 3 lines:
我当然需要使用show. 但即使我添加以下 3 行:
plot(X,C)
plot(X,S)
show()
it still does no generate anything.
它仍然没有产生任何东西。
ADDED
添加
Here are the lines that I use now:
以下是我现在使用的行:
import pylab as p
C = [1,2,3,4]
S = [10, 20, 30, 10]
p.plot(C,S)
p.show()
I still have the same result (nothing).
我仍然有相同的结果(没有)。
采纳答案by Francesco Montesano
It could be a problem with the backend.
What is the output of
python -c 'import matplotlib; import matplotlib.pyplot; print(matplotlib.backends.backend)'?
可能是后端的问题。的输出是
python -c 'import matplotlib; import matplotlib.pyplot; print(matplotlib.backends.backend)'什么?
If it is the 'agg' backend, what you see is the expected behaviour as it is a non-interactive backend that does not show anything to the screen, but work with plt.savefig(...).
You should switch to, e.g., TkAgg or Qt4Agg to be able to use show. You can do it in the matplotlib.rc file.
如果它是“agg”后端,您看到的是预期的行为,因为它是一个非交互式后端,不会在屏幕上显示任何内容,但可以使用 plt.savefig(...)。您应该切换到例如 TkAgg 或 Qt4Agg 才能使用show. 您可以在 matplotlib.rc 文件中执行此操作。
@shashank: I run matplotlib both on 12.04 and 12.10 without problems. In both cases I use the Qt4Agg backend. If you don't have the matplotlibrc set, the default backend is used. I'm sure that for Precise matplotlib repo was built with TkAgg. If the Quantal version has been built with e.g. Agg, then that would explain the difference
@shashank:我在 12.04 和 12.10 上运行 matplotlib 都没有问题。在这两种情况下,我都使用 Qt4Agg 后端。如果您没有设置 matplotlibrc,则使用默认后端。我确定 Precise matplotlib repo 是用 TkAgg 构建的。如果 Quantal 版本是用例如 Agg 构建的,那么这将解释差异
回答by Oz123
You need to call the function:
您需要调用该函数:
show()
to be more exact:
更准确地说:
pylab.show()
and even better don't use:
最好不要使用:
from pylab import *
rather do:
而是这样做:
import pylab as p:
and then:
进而:
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)
p.plot(C,S)
p.show()
回答by Siddharth Naik
Try adding. I use Jupyter and this worked for me.
尝试添加。我使用 Jupyter,这对我有用。
%matplotlib inline

