show()不再重绘了
我在使用Linux系统,遇到一个问题,就是用Python和matplotlib画图的时候,图表只显示一次。第一次调用show()的时候,图表正常显示,但第二次和之后的调用就不行了。
我在两次调用之间关闭了显示图表的窗口。你知道这是为什么吗?怎么解决这个问题呢?
谢谢,AFG
from numpy import * from pylab import * data = array( [ 1,2,3,4,5] ) plot(data) [<matplotlib.lines.Line2D object at 0x90c98ac>] show() # this call shows me a plot #..now I close the window... data = array( [ 1,2,3,4,5,6] ) plot(data) [<matplotlib.lines.Line2D object at 0x92dafec>] show() # this one doesn't shows me anything
4 个回答
0
show()
这个命令在程序中只应该用一次,最好是在最后使用:它是一个不停循环的过程,用来检查图形窗口中的事件。
通常,想要实现你想要的效果,可以这样做:
# … plot …
draw() # Draws for real
raw_input() # Or anything that waits for user input
# … 2nd plot …
draw()
raw_input()
# Last plot
show() # or, again, draw(); raw_input()
你可以试试看这样是否适合你。
另外,你也可以尝试更换后端,因为有些后端的表现比其他的要好:
import matplotlib
matplotlib.use('TkAgg') # For other backends, do matplotlib.use('') in a shell
1
你可能遇到了编辑器或IDE(集成开发环境)窗口和绘图窗口之间的冲突。
解决这个问题的一个很好方法是使用IPython。IPython是一个很棒的交互式环境,它解决了这些问题,并且还有很多其他优点。刚开始时,可以在终端窗口中用命令ipython -pylab
启动IPython,这样它就会进入交互式的pylab模式。
2
在Windows系统上,这个方法运行得很好:
from pylab import *
plot([1,2,3,4])
[<matplotlib.lines.Line2D object at 0x03442C10>]
#close window here
plot([1,2,3,4])
[<matplotlib.lines.Line2D object at 0x035BC570>]
你试过这个吗:
from matplotlib import interactive
interactive(True)
有时候使用matplotlib会让人感到困扰,因为我们需要记住一些选项是在matplotlibrc文件中设置的(比如后端和交互参数)。如果你在不同的编辑器中使用matplotlib(比如IDLE-tk、pycrust-wxpython),或者在交互模式和脚本模式之间切换,那么你需要考虑在一种模式下有效的配置可能在另一种模式下会出问题,这时候就需要通过编程修改或者使用专门的配置文件来解决。
我给出的这个例子可以直接运行(而且不需要调用show()),因为在matplotlibrc文件中,我把交互模式默认设置为True。