将 matplotlib fig 上传到谷歌云存储桶

时间:2021-03-18 02:14:12

标签: python image matplotlib google-cloud-platform jupyter-lab

我正在使用 gcloud dataproc 集群开发 jupyterlab。我正在尝试将一个 matplotlib 文件保存到存储桶中,但我收到错误,提示没有这样的目录。我的代码是

# create figure and axis objects with subplots()
fig,ax = plt.subplots()
# make a plot
ax.plot(df_opt.year, df_opt.pop, marker='o', color='navy', alpha=0.3)
ax.set_xlabel("Year",fontsize=14)
ax.set_ylabel("Population",fontsize=14, color='navy', alpha=0.8)
# twin object for two different y-axis on the sample plot
ax2=ax.twinx()
# make a plot with different y-axis using second axis object
ax2.plot(df_opt.year, df_opt.gdp, marker='o', color='mediumvioletred', alpha=0.5)
ax2.set_ylabel("GDP per cap",fontsize=14, color='mediumvioletred')
plt.show()
# save the plot as a file
fig.savefig("gs://mybucket/popgdp.png")

我得到的错误是“没有这样的文件或目录:gs://mybucket/popgdp.png”

谢谢!

1 个答案:

答案 0 :(得分:0)

savefig() 不能直接保存到 GCS 存储桶。您可以做的是先将其保存在本地,然后将文件复制到 GCS。有关详细信息,请参阅 uploading a file in GCS 的文档。

from google.cloud import storage

# create figure and axis objects with subplots()
fig,ax = plt.subplots()
# make a plot
ax.plot(df_opt.year, df_opt.pop, marker='o', color='navy', alpha=0.3)
ax.set_xlabel("Year",fontsize=14)
ax.set_ylabel("Population",fontsize=14, color='navy', alpha=0.8)
# twin object for two different y-axis on the sample plot
ax2=ax.twinx()
# make a plot with different y-axis using second axis object
ax2.plot(df_opt.year, df_opt.gdp, marker='o', color='mediumvioletred', alpha=0.5)
ax2.set_ylabel("GDP per cap",fontsize=14, color='mediumvioletred')
plt.show()
# save the plot as a file
fig.savefig("gs://mybucket/popgdp.png")


bucket_name = "mybucket"
destination_blob_name = "popgdp.png"
source_file_name = "your_local_file_path/popgdp.png"

storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file_name)