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

Mik*_*all 7 matplotlib google-colaboratory

我在 Google Colaboratory 中使用 matplotlib 并尝试将绘图图像保存在某处(本地下载或上传到 Google Drive)。我目前正在内嵌显示图像:

plt.show()
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的,虽然它只下载一个空白图像:

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)
Run Code Online (Sandbox Code Playgroud)

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

had*_*enj 8

你确定你在使用之前没有显示情节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')
Run Code Online (Sandbox Code Playgroud)


amb*_*nut 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')
Run Code Online (Sandbox Code Playgroud)