R在背景中添加图像

Cha*_*rot 5 plot r image plotly

我尝试使用"plotly"R包在R图形中绘制图像.

我首先尝试从本地计算机中包含一个图像:

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


    )
  )
Run Code Online (Sandbox Code Playgroud)

但我没有设法做到这一点.然后我认为那是因为情节显然需要http或https图像.

第一个问题:是否可以从本地文件导入图像(显然可以使用python:https://plot.ly/python/images/)?

由于似乎无法嵌入本地图像,我尝试导入我在Github上传的图像.但它似乎既不工作:

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


    )
  )
Run Code Online (Sandbox Code Playgroud)

这里有什么问题?

我已经到处看,贴在plotly论坛问题(http://community.plot.ly/t/import-a-local-image-in-plot/2476,http://community.plot.ly/t/add -a-background-image/2457)但我找不到答案.

你有什么主意吗?

Max*_*ers 5

需要改变的两件小事。

  • URL 指向的东西看起来像图像但实际上显示了整个 GitHub 页面,附加?raw=true确保只显示图像
  • 加载图像后,坐标在绘图之外

由于某些CORS问题,通过 htmlwidget 保存此代码仍然不显示图像。在第二个片段中,图像被base64编码并添加到绘图中。它不会显示在 RStudio 中,而是显示在 HTML 输出中。

下面的代码生成以下图。

在此处输入图片说明

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"
      )
    )
  )
Run Code Online (Sandbox Code Playgroud)

base64 编码图像的片段。

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")
Run Code Online (Sandbox Code Playgroud)