Python 在colaboratory上使用plt.savefig保存图形

Python 在colaboratory上使用plt.savefig保存图形,python,matplotlib,jupyter-notebook,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_ti

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

也许它可以独立保存图片

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

如另一个答案所述,
files.download
功能是理想的解决方案,如果您想创建图像文件并动态下载它。但是,如果您实际上不需要下载该文件,但您只是想将该图像存储到您的Google Drive帐户中的一个目录,该怎么办?可能您正在生成大量这样的文件(例如,在耗时的机器学习作业中生成中间结果),而您无法逐个下载每个文件

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

# mount drive
from google.colab import drive
drive.mount('/content/gdrive')
注意:您可以在笔记本的开头这样做,然后在整个会话中忘记它,当然不需要对每张图像都这样做

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

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

从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

鼠标右键,“将图像另存为…”是的,它可以工作,但我想通过代码来完成!因为我正在绘制太多的图形,所以无法右键单击并保存所有图形!打开('filetosavein.img','w'),然后写入文件。如果“在线jupyter笔记本”是在服务器上运行的,我怀疑您是否可以在该服务器以外的其他位置运行任何保存图像的代码。但是,应该可以下载完整的笔记本。是@ImportanceOfBeingErnest,但我无法在我的机器上运行它,这就是我在服务器上使用它的原因!
plt.savefig('/content/gdrive/MyDrive/tesis/imagenes/50prc_trabajo.png',bbox_inches='tight')
files.download("/content/gdrive/MyDrive/tesis/imagenes/50prc_trabajo.png")