简体   繁体   中英

Plotly can't display png images in subplots

Is there any way to put png image instead of one of this Scatter graphs? I could only find how to use the image as logo or background image

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

I tried to add this lines before 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)

but it doesn't work

ValueError: The first argument to the plotly.graph_objs.Image constructor must be a dict or an instance of:class: plotly.graph_objs.Image

Possible solution is to use 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM