【问题标题】:R plotly add a image in backgroundR plotly在背景中添加图像
【发布时间】:2016-10-23 15:15:43
【问题描述】:

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


    )
  )

但我没能做到。然后我认为这是因为 plotly 显然需要 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)上发布了问题,但我没有找到答案。

你有什么想法吗?

【问题讨论】:

  • 你看到了吗plot.ly/~as5165/12/#code。不是 R,但可能会有所帮助。图片是base64。让我们知道您的进展情况

标签: r image plot plotly


【解决方案1】:

两件小事需要改变。

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

由于某些CORS 问题,通过 htmlwidget 保存此代码仍然不显示图像。在第二个 sn-p 中,图像被 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")

【讨论】:

    猜你喜欢
    • 2019-01-13
    • 2011-02-25
    • 2018-06-26
    • 2022-01-13
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多