【问题标题】:saving figures using plt.savefig on colaboratory在 colaboratory 上使用 plt.savefig 保存数字
【发布时间】:2018-07-10 11:55:12
【问题描述】:

我正在使用协作(在线 jupyter 笔记本) 我有以下代码我正在使用此函数绘制一些图表并希望在本地保存图表 我该怎么做?

def make_plot_comparison(Xlabel,Ylabel,l1,l2,l1_title,l2_title,name): 
    plt.xlabel(Xlabel)
    plt.ylabel(Ylabel)
    plt.plot(l1,label=l1_title)
    plt.plot(l2,label=l2_title)
    plt.legend(loc='center right')
    plt.title(name)
    #plt.xlim(-5, 25)
    plt.savefig("abc.png")
    plt.show()

【问题讨论】:

  • 鼠标右键,“图片另存为...”?
  • 是的,它可以工作,但我想通过代码来实现!因为我正在绘制太多图表,所以无法右键单击并保存所有图表!
  • open('filetosavein.img', 'w') 然后写入文件
  • 如果“在线 jupyter 笔记本”在服务器上运行,我怀疑您是否可以运行任何将图像保存在某处的代码,而不是在该服务器上。但是应该可以下载完整的笔记本。
  • 是的@ImportanceOfBeingErnest,但我无法在我的机器上运行它,这就是我在服务器上使用它的原因!

标签: python matplotlib jupyter-notebook


【解决方案1】:

也许它可以独立保存图片

from google.colab import files
plt.savefig("abc.png")
files.download("abc.png") 

https://colab.research.google.com/notebook#fileId=/v2/external/notebooks/io.ipynb&scrollTo=p2E4EKhCWEC5

【讨论】:

    【解决方案2】:

    正如另一个答案中提到的,如果您想创建图像文件并即时下载,files.download 函数是完美的解决方案。但是,如果您实际上不需要下载文件,而只是想将图像存储到您的 Google Drive 帐户中的目录中,该怎么办?也许您正在生成大量此类文件(例如,在耗时的机器学习工作中生成中间结果),而您无法逐个下载每个文件。

    在这种情况下,我采用的解决方案也可能对您有所帮助。首先,让我们在运行时挂载我们的 Google Drive。

    # mount drive
    from google.colab import drive
    drive.mount('/content/gdrive')
    

    注意:您可以在笔记本的开头这样做,然后在整个会话中忘记它,当然不需要对每张图片都这样做!

    安装 Google Drive 后,您现在可以将图像文件(或任何其他您希望的文件)存储在 Drive 中您选择的任何目录中,例如:

    images_dir = '/content/gdrive/My Drive/Images'
    plt.savefig(f"{images_dir}/abc.png")
    

    【讨论】:

    • G盘中保存的图片文件竟然是空白文件。有什么可能导致这种情况的线索吗?
    • 没有更多细节很难说,但通常这类问题与权限问题有关。您确定您有权写入您尝试将文件存储到的文件夹吗?
    【解决方案3】:

    来自 google colab 的 seaborn 导出图表

    plt.figure(figsize=(8,5))
    ax = sns.stripplot(x='colname', y='colname', data=database)
    ax.set_xlabel('') # this line hide/remove the label in x axis
    ax.set_ylabal('label')
    plt.savefig('name.png')
    files.download('name.png') # this line opens your documents in your pc to save your png
    

    【讨论】:

      【解决方案4】:
      plt.savefig('/content/gdrive/MyDrive/tesis/imagenes/50prc_trabajo.png',bbox_inches='tight')
      files.download("/content/gdrive/MyDrive/tesis/imagenes/50prc_trabajo.png")
      

      【讨论】:

        猜你喜欢
        • 2023-03-08
        • 2020-07-25
        • 1970-01-01
        • 2018-05-06
        • 1970-01-01
        • 2021-06-17
        • 2018-11-29
        • 2019-03-14
        • 1970-01-01
        相关资源
        最近更新 更多