Add image in a plotly plot from numpy array (python)

Question:

I’m trying to add an image to a fixed position in a plotly figure; however, the only way i’ve been able to find so far is using add_layout_image, but i don’t really think it’s a very practical way, since the source of the image must be an url (it’s basically meant for dash apps).

Is there any simple way to embed an image, from, let’s say.. a numpy array in a fixed position in a plotly fig?

Asked By: Ghost

||

Answers:

You can give a try to go.Image:

import numpy as np
import plotly.graph_objects as go
import matplotlib.cm as cm
from matplotlib.colors import Normalize

# image dimensions (pixels)
n1 = 150 # height
n2 = 100 # width
# Generate an image starting from a numerical function
x, y = np.mgrid[-5:5:n1*1j, -3:3:n2*1j]
f = np.cos(x * y)

# use matplotlib to assign a colormap to the computed values
norm = Normalize(f.min(), f.max())
norm_f = norm(f)
# generate the image:
# img has a shape of (150, 100, 4).
# The four channels are R, G, B, alpha
# All values will be between 0 and 1
img = cm.viridis(norm_f)

# convert the image to values between 0 and 255
# this is required by go.Image
img = (img * 255).astype(int)

# Create the image
fig = go.Figure(data=[
        go.Image(
            # Note that you can move the image around the screen
            # by setting appropriate values to x0, y0, dx, dy
            x0=x.min(),
            y0=y.min(),
            dx=(x.max() - x.min()) / n2,
            dy=(y.max() - y.min()) / n1,
            z=img
        )
    ],
    layout={
        # set equal aspect ratio and axis labels
        "yaxis": {"scaleanchor": "x", "title": "y"},
        "xaxis": {"title": "x"}
    }
)
fig

enter image description here

Answered By: Davide_sd

Thanks for the answers, i nailed it using add_layout_image() and using the image converted into a PIL image from the np array.

Answered By: Ghost
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.