matplotlib:从命令行运行ipython时,在Web浏览器中顺序显示图

时间:2019-04-09 15:59:32

标签: python matplotlib ipython

当前,我有3个带有pyplot的单独的窗口...我不想要...我想在与jupyter输出类似的单个Web浏览器窗口中看到所有按顺序列在“内联”中的图,除了我从Windows命令行作为ipython脚本运行的脚本...

# File: plotit.ipy

# toy ipython plotting example
import numpy as np
import matplotlib.pyplot as plt 
%matplotlib

t = np.linspace(0, 10, 100)
y1 = 5*t
y2 = -0.5*t
y3 = 2*t**2

# display as 1st inline graph in "jupyter web browser window"
plt.figure()
plt.plot(t,y1)
plt.show()

# display as 2nd inline graph in "jupyter web browser window"
plt.figure()
plt.plot(t,y2)
plt.show()

# display as 3rd inline graph in "jupyter web browser window"
plt.figure()
plt.plot(t,y3, '.')
plt.show()

这是我使用ActiveState Python 3.6从命令行运行它的方式:

C:\> ipython 
In [1]: %run testit.ipy
Using matplotlib backend: TkAgg    

是否有一种方法可以将Jupiter文档转换为ipython脚本,并作为一个整体脚本从命令行运行它,但是在绘制时,仍然在matyplotlib图上依次在jupyter输出窗口中显示“内联”在运行脚本时。示例:

2 个答案:

答案 0 :(得分:1)

我不知道是否可以在不实际运行的情况下模拟jupyter笔记本。

一种替代方法是使用webagg后端。在这种情况下,只有一个plt.show()调用会放在末尾,以在同一页面上显示所有三个数字。

import numpy as np
import matplotlib
matplotlib.use("webagg")
import matplotlib.pyplot as plt 


t = np.linspace(0, 10, 100)
y1 = 5*t
y2 = -0.5*t
y3 = 2*t**2

# display as 1st inline graph in "jupyter web browser window"
plt.figure()
plt.plot(t,y1)

# display as 2nd inline graph in "jupyter web browser window"
plt.figure()
plt.plot(t,y2)

# display as 3rd inline graph in "jupyter web browser window"
plt.figure()
plt.plot(t,y3, '.')
plt.show()

运行此命令时,浏览器窗口应打开,并显示三个数字

enter image description here

答案 1 :(得分:0)

将所有图保存为图像文件而不显示它们,然后在运行python脚本后编写一个html文件以显示所有图像文件。

data-role=page

html:

# File: plotit.ipy

# toy ipython plotting example
import numpy as np
import matplotlib.pyplot as plt 

t = np.linspace(0, 10, 100)
y1 = 5*t
y2 = -0.5*t
y3 = 2*t**2

# display as 1st inline graph in jupyter web browser window
fig = plt.figure()
plt.plot(t,y1)
fig.savefig("plot1.png")

# display as 2nd inline graph in jupyter web browser window
fig = plt.figure()
plt.plot(t,y2)
fig.savefig("plot2.png")

# display as 3rd inline graph in jupyter web browser window
fig = plt.figure()
plt.plot(t,y3)
fig.savefig("plot3.png")

另一个html结果页面:

<!-- FILE: results.html -->
<html>
<body>
    <img src="plot1.png"/><br>
    <img src="plot2.png"/><br>
    <img src="plot3.png"/><br>
</body>
</html>