html Plotly无法在子图中显示png图像

uoifb46i  于 2022-12-28  发布在  其他
关注(0)|答案(1)|浏览(183)

有没有办法把PNG图像,而不是这个散点图之一?我只能找到如何使用的图像作为标志或背景图像

from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(rows=1, cols=2)

fig.add_trace(
    go.Scatter(x=[1, 2, 3], y=[4, 5, 6]),
    row=1, col=1
)

fig.add_trace(
    go.Scatter(x=[20, 30, 40], y=[50, 60, 70]),
    row=1, col=2
)

fig.update_layout(height=600, width=800, title_text="Side By Side Subplots")
fig.show()

我尝试在fig.update_layout之前添加以下行

from PIL import Image
import plotly.express as px
img = Image.open('plot1.png')
plotly_img = px.imshow(img)
fig.add_trace(go.Image(plotly_img), row=1, col=2)
#fig.add_trace(go.Image(img), row=1, col=2)

但它不起作用
ValueError:plotly.graph_objs.Image构造函数的第一个参数必须是dict或:class的示例:plotly.graph_objs.Image

vnjpjtjt

vnjpjtjt1#

可能的解决方案是使用base64 example

import plotly.graph_objects as go
from skimage importdata
import base64
from io import BytesIO
from PIL import Image

img = data.astronaut()
img_obj = Image.fromarray(img)
prefix = "data:image/png;base64,"
with BytesIO() as stream:
    img_obj.save(stream, format='png')
    b64_str = prefix + base64.b64encode(stream.getvalue()).decode('unicode_escape')
fig = go.Figure(data=go.Image(
    source=b64_str
))
fig.show()

相关问题