R在背景中添加图像

时间:2016-10-23 15:15:43

标签: r image plot 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"
      )


    )
  )

但我没有成功。然后我认为这是因为情节显然需要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"
      )


    )
  )

这里有什么问题?

我到处寻找,在情节论坛上发布了问题(http://community.plot.ly/t/import-a-local-image-in-plot/2476http://community.plot.ly/t/add-a-background-image/2457),但我找不到答案。

你知道吗?

1 个答案:

答案 0 :(得分:4)

需要改变的两件小事。

  • 网址指向看似图像但实际显示整个GitHub页面的内容,附加?raw=true确保只显示图像
  • 加载图像后,坐标位于图表之外

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

以下代码生成以下图表。

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

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