You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly加载Google Drive背景图失败问题求助(附代码)

解决Plotly在Colab中无法加载Google Drive图片链接的问题

我刚好碰到过类似的情况,咱们一步步来搞定:

一、公开Google Drive文件的加载 workaround

你提到的https://docs.google.com/uc?export=download&id=<file-id>链接在Markdown里能正常显示,但Plotly加载失败,大概率是因为Plotly的图片加载逻辑没正确处理Google Drive的重定向或请求验证。一个简单的解决方法是先把图片下载到Colab本地,再用本地路径加载:

import requests
from PIL import Image
import io
import plotly.express as px

# 先把图片下载到内存
drive_url = "https://docs.google.com/uc?export=download&id=1JEyyYCse6sWM3yMUwDG2l7XzaGxej-VZ"
response = requests.get(drive_url)
img = Image.open(io.BytesIO(response.content))

# 保存到Colab本地(本地路径加载更稳定)
img.save("background_image.png")

# 你的热力图代码(已修正语法错误)
fig = px.density_heatmap(df, x="x", y="y", 
                         color_continuous_scale = [(0, "rgba(0, 255, 0, 0)"), 
                                                  (0.5, "rgba(0, 255, 0, 0.5)"), 
                                                  (1, "rgba(0, 255, 0, 1)")], 
                         height=810, width=1440)
# 改用本地路径加载图片
fig.add_layout_image( dict( source="background_image.png", 
                           xref="x", yref="y", 
                           x=0, y=0, sizex=1920, sizey=1080, 
                           sizing="stretch", opacity=1, layer="below") )
fig.update_layout(template="plotly_white")
fig.show()

二、非公开Google Drive文件的最优方案(借助Colab凭证)

如果你的文件不想设置成公开共享,直接挂载Google Drive到Colab是最靠谱的方式——这样能直接访问Drive内的文件,完全不需要依赖公共链接:

  1. 先挂载Drive:
from google.colab import drive
drive.mount('/content/drive')

执行后会弹出授权链接,跟着提示完成授权就能挂载成功。

  1. 直接用Drive内的文件路径加载图片:
    假设你的图片存在Drive的My Drive/visualization/background.png路径下,代码改成这样:
import plotly.express as px

fig = px.density_heatmap(df, x="x", y="y", 
                         color_continuous_scale = [(0, "rgba(0, 255, 0, 0)"), 
                                                  (0.5, "rgba(0, 255, 0, 0.5)"), 
                                                  (1, "rgba(0, 255, 0, 1)")], 
                         height=810, width=1440)
fig.add_layout_image( dict( source="/content/drive/My Drive/visualization/background.png", 
                           xref="x", yref="y", 
                           x=0, y=0, sizex=1920, sizey=1080, 
                           sizing="stretch", opacity=1, layer="below") )
fig.update_layout(template="plotly_white")
fig.show()

为什么原来的uc链接不行?

本质原因是Plotly的add_layout_image在加载网络图片时,没有模拟浏览器的请求行为(比如处理Cookie、重定向),而Google Drive的uc链接需要这些验证才能正确返回图片资源。Colab的Markdown渲染器能正常显示,是因为它内置了处理这类请求的逻辑。

内容的提问来源于stack exchange,提问作者Alex_H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 08:07:46