Adding an image to a datatable in R

风格不统一 提交于 2019-12-01 18:23:34

问题


I'm trying to add an image to a datatable in R form the DT package. I fount this question: How to embed an image in a cell a table using DT, R and Shiny and it works for the image that's online. But when I tried to add a image that i have locally (created with R) it just doesn't come up. This is an example of my problem:

x = rnorm(1000)   
png(paste0("Graficas/test.png"))
Plot = plot(x, type = "l")
dev.off()
camino = '<img src="Graficas/test.png" height="30"></img>'
data = data.frame(0.5,camino)
datatable(data, escape = FALSE)

the output is

and I can't understand why its happening


回答1:


This is one way to do it (by embedding base64 encoded images and using that for the src).

First we'll make a small helper:

img_uri <- function(x) { sprintf('<img src="%s"/>', knitr::image_uri(x)) }

That will let us make a data uri. We're slurping up the whole file and converting it to base64 then doing a bit more formatting before sticking the entire blob into the src attribute.

This is what a 1x1 pixel PNG looks like encoded that way:

<img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX/TQBcNTh/AAAAAXRSTlPM0jRW/QAAAApJREFUeJxjYgAAAAYAAzY3fKgAAAAASUVORK5CYII=\"/>

So, we just do the same with the one you created:

x = rnorm(1000)   
png(paste0("test.png"))
Plot = plot(x, type = "l")
dev.off()

camino = img_uri("test.png")
data = data.frame(0.5 ,camino)
DT::datatable(data, escape = FALSE)

Yours is having an issue b/c it's not "URI" and it has no way of pulling from the local system. It might work in a browser context with a file://… URL.



来源:https://stackoverflow.com/questions/47804593/adding-an-image-to-a-datatable-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!