2016-10-23 20 views
5

"プロット" Rパッケージを使用して、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)に質問を投稿しましたが、回答が見つかりませんでした。

ご存知ですか?

+0

これはhttps://plot.ly/~as5165/12/#codeをご覧になりましたか? Rではないが助けになるかもしれない。画像はbase64です。あなたがどう乗っているのか教えてください – pssguy

答えて

1

変更が必要な2つの小さなもの。

  • URLは画像のように見えた何かを指摘したが、実際に?raw=trueが唯一の画像の座標がプロット外であった
  • 画像をロードした後に示されていることを確認する追加、全体のGitHubページを示し

このコードをhtmlwidgetで保存すると、画像はCORSの問題のため表示されません。 2番目のスニペットでは、画像は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") 
関連する問題