在Google Colaboratory上保存或下载matplotlib绘图图像

10

我正在Google Colaboratory中使用matplotlib,并尝试在某处保存绘图图像(无论是本地下载还是上传到Google Drive)。 我目前是通过以下方式内联显示图像:

plt.show()

这是我尝试过的,但它只下载了一张空白图片:

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)

我也尝试使用Drive API上传绘图图片,但也没有成功。


1
你能否右键点击并保存图片? - korakot
是的,但我正在生成许多图表。 - Mike Sall
3个回答

10

你确定在使用 savefig() 之前没有展示图形吗?这里有一个完整的可工作示例:

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

1
我曾经遇到过同样的问题,这个方法解决了它。在保存之前,我使用plt.show(),这在我的电脑上有效,但在colab上无效。 - lhhong
1
@lhhong 我也是这样 - anushka

5

您需要展示绘图并指定要保存的绘图。否则,您只是在保存一个空白的绘图画布。

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

2

如果您想使用高分辨率图像,请使用此代码:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接