I try to use the "plotly" R package to plot an image in an R graphic.
I first tried to include an image from a local computer:
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"
)
)
)
But I did not manage to do it. I then thought that was because plotly apparently requires an http or https image.
First question: Is it possible to import image from a local file (apparently it is possible with python: https://plot.ly/python/images/)?
As it seems to be impossible to embed a local image, I try to import an image that I had upload on my Github. But it seems not to work neither:
library(plotly)
plot_ly(x = c(1, 2, 3), y = c(1, 2, 3)) %>%
layout(
images = list(
list(
source = "https://github.com/charlottesirot/elementR/blob/master/inst/www/2.png",
xref = "x",
yref = "y",
x = 1,
y = 1,
sizex = 2,
sizey = 2,
sizing = "stretch",
opacity = 0.4,
layer = "below"
)
)
)
What is the problem here?
I have looked everywhere, posted questions on plotly forum (http://community.plot.ly/t/import-a-local-image-in-plot/2476, http://community.plot.ly/t/add-a-background-image/2457) but I did not find my answers.
Do you have any idea?
Two small things which needed to be changed.
?raw=true
makes sure that only the image is shownSaving this code via htmlwidget still does not show the image because of some CORS issue. In the second snippet the image is base64
encoded and added to the plot. It doesn't show in RStudio but in the HTML output.
The code below produces the following plot.
library('plotly')
plot_ly(x = c(1, 2, 3), y = c(1, 2, 3), type = 'scatter', mode = 'markers') %>%
layout(
images = list(
list(
source = "https://github.com/charlottesirot/elementR/blob/master/inst/www/2.png?raw=true",
xref = "x",
yref = "y",
x = 1,
y = 3,
sizex = 2,
sizey = 2,
sizing = "stretch",
opacity = 0.4,
layer = "below"
)
)
)
Snippet for base64 encoded image.
library('plotly')
library('htmlwidgets')
library('RCurl')
image_file <- "/temp/2.png"
txt <- RCurl::base64Encode(readBin(image_file, "raw", file.info(image_file)[1, "size"]), "txt")
p <- plot_ly(x = c(1, 2, 3), y = c(1, 2, 3), type = 'scatter', mode = 'markers') %>%
layout(
images = list(
list(
source = paste('data:image/png;base64', txt, sep=','),
xref = "x",
yref = "y",
x = 1,
y = 3,
sizex = 2,
sizey = 2,
sizing = "stretch",
opacity = 0.4,
layer = "below"
)
)
)
p
htmlwidgets::saveWidget(p, "/tmp/plot.html")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With