Skip to main content
 首页 » 编程设计

python之jupyter nbconvert 不为 matplotlib.savefig 保存文件

2025年01月19日10开发

我正在尝试使用 pyplot.savefig 函数保存一个 png 文件。通过 jupyter web UI 运行时工作正常。但是当我通过命令行运行它时,它不会创建图像。

命令行:jupyter nbconvert FILE_NAME.ipynb

代码:

import matplotlib.pyplot as plt 
 
# evenly sampled time at 200ms intervals 
t = np.arange(0., 5., 0.2) 
 
# red dashes, blue squares and green triangles 
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') 
 
plt.savefig('test-image-2.png', format='png', dpi=1200) 
 
plt.show() 

我在这里做错了什么?

请您参考如下方法:

您需要将命令更改为:

jupyter nbconvert FILE_NAME.ipynb --execute

否则,好吧,没有一个单元格被执行。

这在 jupyter nbconvert --help 显示的文档中有说明:

$ jupyter nbconvert --help 
This application is used to convert notebook files (*.ipynb) to various other 
formats. 
 
WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES. 
 
Options 
------- 
 
Arguments that take values are actually convenience aliases to full 
Configurables, whose aliases are listed on the help line. For more information 
on full configurables, see '--help-all'. 
 
--debug 
    set log level to logging.DEBUG (maximize logging output) 
--generate-config 
    generate default config file 
-y 
    Answer yes to any questions instead of prompting. 
--execute 
    Execute the notebook prior to export. 
[snip]