Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving or downloading matplotlib plot images on Google Colaboratory

I am using matplotlib in Google Colaboratory and trying to save the plot images somewhere (either downloading locally or uploading to Google Drive). I'm currently displaying the image inline with:

plt.show()

Here's what I've attempted, although it only downloads a blank image:

import os    
local_download_path = os.path.expanduser('~/data')
plot_filepath = os.path.join(local_download_path, "plot.png")

plt.savefig(plot_filepath)

from google.colab import files
files.download(plot_filepath)

I've also tried using the Drive API to upload the plot image, but haven't had success there either.

like image 648
Mike Sall Avatar asked Jun 20 '18 17:06

Mike Sall


2 Answers

If you want high resolution image use this code:

  import matplotlib.pyplot as plt
  from google.colab import files

  image = plt.figure(figsize=(16,10), dpi= 200)
  image.savefig('myimage.png',  bbox_inches="tight")
  files.download('myimage.png')
like image 77
Mustapha Babatunde Avatar answered Oct 19 '22 21:10

Mustapha Babatunde


Did you make sure that you didn't show the plot before using savefig()? Here is a complete working example:

import matplotlib.pyplot as plt
from google.colab import files

test = plt.figure()
plt.plot([[1, 2, 3], [5, 2, 3]])
plt.savefig('test.pdf')

files.download('test.pdf')
like image 28
hhh Avatar answered Oct 19 '22 20:10

hhh