Adding an image to a datatable in R
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.
How to embed an image in a cell a table using DT, R and Shiny
You can use the escape = FALSE
in your DT call, as per: https://rstudio.github.io/DT/#escaping-table-content
# ui.R
require(shiny)
library(DT)
shinyUI(
DT::dataTableOutput('mytable')
)
# Server.R
library(shiny)
library(DT)
dat <- data.frame(
country = c('USA', 'China'),
flag = c('<img src="test.png" height="52"></img>',
'<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Flag_of_the_People%27s_Republic_of_China.svg/200px-Flag_of_the_People%27s_Republic_of_China.svg.png" height="52"></img>'
)
)
shinyServer(function(input, output){
output$mytable <- DT::renderDataTable({
DT::datatable(dat, escape = FALSE) # HERE
})
})
Want to have a column with images in a datatable; it works with URL but does not work with local paths
Indeed, that doesn't work. This way works, with the images in the www subfolder:
render <- c(
"function(data, type, row){",
" if(type === 'display'){",
" var tag = '<img src=\"' + data + '.png\" width=\"100\"/>';",
" return tag;",
" } else {",
" return data;",
" }",
"}"
)
df <- reactiveValues(data = data.frame(
Name = readUnits$label,
Icon=c("img1",
"img1",
"img2",
.........),
Actions = shinyInput(
actionButton, 12, 'button_', label = "Linked to", onclick = 'Shiny.onInputChange(\"select_button\", this.id)'
),
stringsAsFactors = FALSE,
row.names = 1:12
))
output$data <- renderDT({
datatable(
df$data,
selection = 'none',
options = list(
columnDefs = list(
list(targets = 2, render = JS(render))
)
)
)
}, server = FALSE)
Add an image to a table-like output in R
If you are using knitr with the rmarkdown package, it is pretty easy -- just use the Markdown syntax ![]()
to include images, e.g.
---
title: "Flags"
author: "Yihui Xie"
date: "2014/08/03"
output: html_document
---
```{r results='asis'}
dat <- data.frame(
country = c('Canada', 'United Kindom'),
abbr = c('ca', 'gb'),
var1 = c(1, 2),
var2 = rnorm(2)
)
dat$flag <- sprintf('![](http://flagpedia.net/data/flags/mini/%s.png)', dat$abbr)
library(knitr)
kable(dat)
```
If you need LaTeX/PDF output, you have to download these images by yourself. Here is an example:
---
title: "Flags"
author: "Yihui Xie"
date: "2014/08/03"
output: html_document
---
```{r}
dat <- data.frame(
country = c('Canada', 'United Kindom'),
abbr = c('ca', 'gb'),
var1 = c(1, 2),
var2 = rnorm(2)
)
dat$file <- paste0(dat$abbr, '.png')
dat$link <- paste0('http://flagpedia.net/data/flags/mini/', dat$file)
dat$flag <- sprintf('![](%s)', dat$file)
for (i in seq_len(nrow(dat))) {
if (!file.exists(dat$file[i])) xfun::download_file(dat$link[i])
}
knitr::kable(dat[, -c(5, 6)])
```
Rendering images in DT table in R Shiny
A little hidden in the Shiny documentation, you will find METHOD 3 that involves supplying the image files inside a www
directory (example reference here or in the cheatsheet).
If your folder structure looks as follows
├── image_test_case.R
├── image_test_case_table.csv
├── www/
│ ├── amerikaan.jpg
│ └── tilia.jpg
then you may set the src
tag to the image path relative to the www
path.
<img src='amerikaan.jpg' height='200'></img>
<img src='tilia.jpg' height='200'></img>
Note that www
is used for all sorts of static resources (most common images, javascript and css files).
Embedding an image in a table cell using DT, R and Shiny not working
Your example is incomplete. Does this work?
require(shiny)
library(DT)
ui <- shinyUI(
DT::dataTableOutput('mytable')
)
dat <- data.frame(
country = c('USA', 'China'),
flag = c('<img src="http://flaglane.com/download/american-flag/american-flag-large.png" height="52"></img>',
'<img src="https://upload.wikimedia.org/wikipedia/commons/2/2e/Flag_of_China.png" height="52"></img>'
)
)
server <- shinyServer(function(input, output){
output$mytable <- DT::renderDataTable({
DT::datatable(dat, escape = FALSE)
})
})
shinyApp(ui, server)
It works fine for me.
How to save a table I created with (DT), datatable into a high quality image?
You can use the saveWidget
function to save the datatable in a html file, then use the webshot
package to take a snapshot.
library(DT)
library(webshot)
dtable <- datatable(iris[1:8,])
html <- "dtable.html"
saveWidget(dtable, html)
webshot(html, "dtableSnapshot.png") # you can also export to pdf
Related Topics
Population Pyramid Plot with Ggplot2 and Dplyr (Instead of Plyr)
Merge Multiple Data.Frames in R with Varying Row Length
Variable Results with Dplyr Summarise, Depending on Output Variable Naming
R: How to Retrieve a Column Name of a Data Frame
Dependent Inputs in Shiny Application with R
Retain Numerical Precision in an R Data Frame
How to Convert a Numeric Value into a Date Value
How to Print on a Serie Sof Graphs Pairwise Comparisons Bars and Effect Size Value
Wordcloud Package: Get "Error in Strwidth(…):Invalid 'Cex' Value"
R: Removing Duplicate Elements in a Vector
Vector of Cumulative Sums in R
Merge Data.Frames with Duplicates
Finding Number of Elements in One Vector That Are Less Than an Element in Another Vector
R: Read in Random Rows from File Using Fread or Equivalent
How to Merge Two Data Frame Based on Partial String Match with R