Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saving figures using plt.savefig on colaboratory

I am using collaboratory(online jupyter notebook) I have the following code i am plotting some graphs using this functions and want to save plots locally how can I do this ?

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()
like image 200
AQEEL ALTAF Avatar asked Jan 31 '18 11:01

AQEEL ALTAF


2 Answers

maybe it can save the picture independently

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

like image 193
이성령 Avatar answered Sep 17 '22 14:09

이성령


As mentioned in another answer, the files.download function is the perfect solution if you want to create the image file and download it on the fly. But what if you do not actually need to download the file, but you simply want to store the image to a directory in your Google Drive account? Maybe you are generating tons of such files (e.g. intermediate results during a time-consuming machine learning job) and you just can't download each file one by one.

In that case the solution I employed might be of help for you too. First of all, let's mount our Google Drive on our runtime.

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

Note: you can do that at the beginning of your notebook and then forget about it for the entire session, no need to do that for each image of course!

With the Google Drive mounted, you can now store your image files (or any other file you wish, for that matter) in any directory of your choice in Drive, e.g.:

images_dir = '/content/gdrive/My Drive/Images'
plt.savefig(f"{images_dir}/abc.png")
like image 22
Sal Borrelli Avatar answered Sep 17 '22 14:09

Sal Borrelli