使用plt.savefig在colaboratory上保存数字

时间:2018-01-31 11:26:57

标签: python matplotlib jupyter-notebook

我正在使用collaboratory(在线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()

4 个答案:

答案 0 :(得分:3)

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

在这种情况下,我采用的解决方案也可能对您有所帮助。首先,让我们在运行时安装Google云端硬盘。

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

注意:您可以在笔记本的开头进行此操作,然后在整个会话过程中都将其忘却,当然不必对每个图像都这样做!

在安装了Google云端硬盘后,您现在可以将图像文件(或与此相关的任何其他文件)存储在云端硬盘中您选择的任何目录中,例如:

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

答案 1 :(得分:2)

也许它可以独立保存图片

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 :(得分:0)

来自 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

答案 3 :(得分:0)

plt.savefig('/content/gdrive/MyDrive/tesis/imagenes/50prc_trabajo.png',bbox_inches='tight')
files.download("/content/gdrive/MyDrive/tesis/imagenes/50prc_trabajo.png")
相关问题