【问题标题】:How to save matplotlib plot with the same file name as its filename.py如何使用与其 filename.py 相同的文件名保存 matplotlib 图
【发布时间】:2017-11-07 02:16:02
【问题描述】:

我从 thisfilename.py 运行用于 Matplotlib 绘图的 python 代码。是否有一个变量存储此文件名而没有文件路径?因为我想将绘图保存为 thisfilename.png 而无需每次都输入这样的文件名?

if __name__ == '__main__':
  ...
  plt.savefig('thisfilename.png')

我想把最后一行改成类似

  # pseudocode
  plt.savefig(variable, '.png')

我测试过

  plt.savefig(__file__, ".png")

保存的文件名有 .py、文件路径和 .png 前面的空格,我不想要

【问题讨论】:

标签: python matplotlib


【解决方案1】:

要保存与 python 文件同名的图形,将“.py”替换为“.png”并删除路径,我会使用:

plt.gcf().savefig(__file__.rstrip('.py').split('/')[-1] + ".png")

rstrip 从 file 字符串的右侧删除“.py”, split 方法在每个“/”处分隔您的链,并且 [-1] 仅保留列表的最后一项 + 可用于连接字符串

【讨论】:

    【解决方案2】:
    import inspect
    import matplotlib.pyplot as plt
    import numpy as np
    
    frame = inspect.currentframe()
    path = inspect.getfile(frame)
    fname = path.split('.')[0]
    
    t = np.linspace(0,1, 1000)
    plt.plot(t, np.sin(2*np.pi*t*4))
    plt.savefig(fname + ".jpg")
    

    【讨论】:

      【解决方案3】:

      您可以使用 Python 的 splitext()__file__ 分成两部分,然后添加所需的扩展,如下所示:

      import os
      
      output_filename = os.path.splitext(__file__)[0] + '.png'
      plt.savefig(output_filename)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-08
        • 2018-09-01
        • 1970-01-01
        • 2020-06-17
        • 2022-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多