繁体   English   中英

R在背景中添加图像

[英]R plotly add a image in background

我尝试使用“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"
      )


    )
  )

这里有什么问题?

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

你有什么主意吗?

需要改变的两件小事。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM