【问题标题】:How to change default path for "save the figure" in python?如何在python中更改“保存图形”的默认路径?
【发布时间】:2016-02-21 20:45:23
【问题描述】:

我有一个 python 代码来创建一个图形。用plt.show()显示后,我想保存图。
为了避免弄乱纵横比、分辨率等,我不想在代码中使用savefig-command。相反,我想使用图形窗口中的“保存图形”按钮。
但是,默认情况下,它会提示我的主文件夹作为保存位置。我希望自动保存在执行代码的目录中。
如何/在哪里可以更改此窗口默认路径以保存到当前文件夹(或其他位置)?

我一开始就从Change directory to the directory of a Python script 尝试了这个命令,但它没有帮助,即使给出了正确的文件名:

os.chdir(os.path.dirname(__file__))

【问题讨论】:

    标签: python matplotlib path save


    【解决方案1】:

    看来您可以通过更改默认文件matplotlibrc 来设置此设置,请查看http://matplotlib.org/users/customizing.html 下的指南 重要的行在 savefig 参数下:

    # the default savefig params can be different from the display params
    
    ...
    
    savefig.directory   : ~        # default directory in savefig dialog box, 
                                   # leave empty to always use current working directory
    

    this 似乎是在 matplotlib 1.3 中引入的。我想你可以使用,

    matplotlib as mpl
    mpl.rcParams["savefig.directory"] = os.chdir(os.path.dirname(__file__))
    

    在脚本顶部或通过更改matplotlibrc 文件。 让对话框默认为 cwd 而不是脚本位置(感谢jjcf89

    matplotlib as mpl 
    mpl.rcParams["savefig.directory"] = ""
    

    【讨论】:

    • 太棒了!现在它可以工作了。我无法通过编辑 matplotrc 来修复它,但是您的最后一个命令有所帮助,我必须进行一些小改动:... =“path-to-my-folder”。不知何故 os.chdir 没有工作。 PS:看看 matplotrc 设置真的很好。现在我也可以改变很多其他的东西了
    • 嗨@physiker,很高兴听到它有效。我想知道是否甚至可以在matplotrc 文件中设置您想要的表单的动态文件路径。如果在导入 matplotlib 时它只是像脚本一样运行,我假设你可以import os 并使用类似os.chdir 的东西。在脚本中,命令os.chdir(os.path.dirname(__file__)) 应该返回一个字符串,该字符串与硬连线的“我的文件夹路径”一样有效,除非我错过了什么......
    • 嗨@Ed Smith,实际上“路径到我的文件夹”只是“。”这是天真的动态!我会根据您的建议进行更多尝试,如果我成功了,我会向您报告。谢谢
    • 需要注意的是savefig.directory仅在点击交互图中的Save按钮时使用,而不是在脚本plt.savefig('/some/path')中使用
    • 请注意,如果您希望对话框默认为 cwd 而不是脚本位置,则以下操作有效。 # Configure save dialog to use current directoryimport matplotlib as mplmpl.rcParams["savefig.directory"] = ""
    【解决方案2】:

    对于非代码解决方案,您可以创建一个名为 matplotlibrc 的文件,其内容如下:

    savefig.directory:
    

    这会将savefig.directory 的值设置为空字符串,使其默认为当前工作目录。

    您可以将此matplotlib 文件放在当前工作目录中,或放在documentation 中指定的位置。例如,在 Linux 上,它应该在 .config/matplotlib/ 中(如果那里没有 matplotlibrc 文件,请不要担心,我的机器上也没有)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      • 2019-10-02
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多