Mike Sall
Mike Sall

Reputation: 101

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.

Upvotes: 10

Views: 23961

Answers (3)

Babatunde Mustapha
Babatunde Mustapha

Reputation: 2663

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')

Upvotes: 2

ambitiousdonut
ambitiousdonut

Reputation: 394

You need to show the plot and specify which plot to save. Otherwise, you're just saving a blank plot canvas.

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

test = plt.figure()
plt.plot([[1, 2, 3], [5, 2, 3]])
plt.figure(figsize=(50,50))
test.show()

test.savefig('samplefigure.png')
files.download('samplefigure.png')

Upvotes: 5

hadrienj
hadrienj

Reputation: 2003

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')

Upvotes: 10

Related Questions