Add a background image

Hello there !

I am a beginner in plotly (very nice package by the way, thank you very much for this great job) and I am completely stuck on a very simple problem.

I try to embed a logo in my graph as here (https://plot.ly/r/logos/). When I take the example of this web page everything works correctly.

However, when I change the source of my image from a local image, no background is printed. I think that I have not correctly set up the parameters of my image layout but I cannot figure out how !!

I tried to look on the similar topics (http://stackoverflow.com/questions/39590845/embed-image-in-plotly , http://stackoverflow.com/questions/39490549/adding-an-image-logo-in-plotly-pie-chart) but I still don’t find my answer.

Here is my code:

library(plotly)

outfile <- tempfile(fileext = ".png")

png(outfile)
plot(rnorm(200), rnorm(200))
dev.off()

plot_ly(x = c(1, 2, 3), y = c(1, 2, 3)) %>%
  layout(
    images = list(
      list(
        source =  outfile,
        xref = "x",
        yref = "y",
        x = 1,
        y = 1,
        sizex = 2,
        sizey = 2,
        sizing = "stretch",
        opacity = 0.4,
        layer = "below"
      )

      
    )
  )

Does anyone have an idea why it is not working?

Thank you very much in advance !!

Cha

Hi @boubchat,
I think that’s due to the fact that Plotly requires the image to be in an https address. It hasn’t worked for me with local files either.
Easiest way of solving this is creating a github account and having a public repo where you store the images you want to use.

I found a workaround that worked for me in the Julia language. I’m not sure how well it generalizes to other languages, but here it goes:

According to this reply you can also have data URI’s as your source. The challenge then becomes to get the right data URI of your image.

A data URI consists of some fixed parts, and a Base64 encoding of your image.

The way to get the Base64 encoding of you image is different from language to language, but here is a post on how to get the encoding in Julia.

Putting all these answers together I get:

sourcePath = "Your/path/to/file"
data = read(sourcePath)
imagetext = base64encode(data)
 
plot(
    scatter(
        x = [1, 2, 3],
        y = [1, 2, 3],
        mode = "markers"
    ), 
    Layout(
        images = [
            attr(
                source = "data:image/png;base64,$(imagetext)",
                xref="x",
                yref="y",
                x=1,
                y=3,
                sizex=2,
                sizey=2,
                sizing="stretch",
                opacity=0.4,
                layer="below"
            )
        ]
    )
)

Hope this translates easily to other languages!