R re-add the image in the background

I am trying to use a "plotly" R package to plot an image on graph R.

First, I tried to include an image from the 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 succeed. Then I thought that this was because the plot seemed to require an http or https image.

First question: Is it possible to import images from a local file (apparently this is possible with python: https://plot.ly/python/images/ )?

It seems impossible to embed a local image, I'm trying to import the image that I uploaded to my Github. But it doesn't seem to work either:

 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?

I searched everywhere, answered questions on the 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 the answers.

Do you have any ideas?

+5
source share
1 answer

Two little things that needed to be changed.

  • The URL pointed to what looked like an image, but actually showed the entire GitHub page, adding ?raw=true , make sure that only the image is displayed
  • After loading the image, the coordinates were off the chart

Saving this code with htmlwidget still does not display the image due to a CORS error. In the second fragment, the base64 image is encoded and added to the plot. It is not displayed in RStudio, but in HTML output.

The code below shows the following graph.

enter image description here

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

Fragment 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") 
+1
source

Source: https://habr.com/ru/post/1258666/


All Articles