我需要在文件中创建一个图形,而不在IPython笔记本中显示它。 我不清楚IPython
和matplotlib.pylab
在这方面的交互。但是,当我调用pylab.savefig("test.png")
时,当前的图形会被显示,并保存在test.png
中。当自动创建大量绘图文件时,这通常是不希望发生的情况。或者在需要进行外部处理的中间文件的情况下。
不确定这是一个matplotlib
还是IPython
笔记本问题。
我需要在文件中创建一个图形,而不在IPython笔记本中显示它。 我不清楚IPython
和matplotlib.pylab
在这方面的交互。但是,当我调用pylab.savefig("test.png")
时,当前的图形会被显示,并保存在test.png
中。当自动创建大量绘图文件时,这通常是不希望发生的情况。或者在需要进行外部处理的中间文件的情况下。
不确定这是一个matplotlib
还是IPython
笔记本问题。
这是一个关于matplotlib的问题,你可以通过使用不向用户显示的后端(例如“Agg”)来解决此问题:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('/tmp/test.png')
编辑:如果您不想失去显示图形的能力,请关闭交互模式,并且只有在准备好显示图形时才调用plt.show()
:
import matplotlib.pyplot as plt
# Turn interactive plotting off
plt.ioff()
# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)
# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')
# Display all "open" (non-closed) figures
plt.show()
close()
和show()
命令,这应该解决你的问题。如你所发现的那样,动态更改后端是不支持的。 - staticfloatmatplotlib.use('Agg')
就解决了问题。我的代码中根本不需要任何plt.show()
或plt.ioff()
。 - Zhanwen Chen%matplotlib inline
import pylab as plt
# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()
# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)
# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')
如果你在iPython中运行这段代码,它会显示第二个图形,如果你在结尾添加plt.close(fig2)
,你将看不到任何内容。
总之,如果你使用plt.close(fig)
关闭图形,它将不会被显示。
plt.ioff
后,会出现 RuntimeWarning: More than 20 figures have been opened...
的警告。使用 plt.close
解决了这个问题。 - Nagasaki45plt.close()
而不是 plt.show()
,它们就不会被显示出来。这是最好的解决方案,因为它不会改变任何全局行为,只需要一行代码即可。 - codeanandaplt.close()
而不是plt.show()
。xs = [1,2,3]
ys = [1,4,9]
plt.plot(xs, ys)
# plt.show() # will show the plot
plt.close() # will close the plot
ioff
。 - Vass