将 matplotlib 文件保存到目录

新手上路,请多包涵

这是生成绘图图像并将其保存在与代码相同的目录中的简单代码。现在,有没有办法可以将它保存在选择的目录中?

 import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(100))

fig.savefig('graph.png')

原文由 khan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 777
1 个回答

如果要保存的目录是工作目录的子目录,只需在文件名前指定相对路径:

     fig.savefig('Sub Directory/graph.png')

如果你想使用绝对路径,导入 os 模块:

     import os
    my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.
    ...
    fig.savefig(my_path + '/Sub Directory/graph.png')

如果您不想担心子目录名称前面的前导斜线,您可以智能地加入路径,如下所示:

     import os
    my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.
    my_file = 'graph.png'
    ...
    fig.savefig(os.path.join(my_path, my_file))

原文由 Eric 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题