简体   繁体   中英

knit datatable format created in r into pdf

I am producing an R-markdown report where plots and data tables are knitted into a pdf .

These data tables (package DT) have fantastic formatting options like styleColorBar, which I can see from the Viewer, in an HTML when I print in that format, but not in pdf, as far as I tried. Here is a sample of my code, where the second column, dist, should have intensity-bars in the cell background.

---
title: "prove27_2"
author: "Roberto Di Pietro"
date: "27/2/2020"
output: pdf_document
---
knitr::opts_chunk$set(echo = TRUE)
library(DT)
colors<-viridis::viridis(3,alpha=.3)[1]
datatable(cars) %>% formatStyle(names(cars)[2],
                                            background = styleColorBar(range(cars[,2]),
                                                                       colors
                                            ),
                                            backgroundSize = '98% 88%',
                                            backgroundRepeat = 'no-repeat',
                                            backgroundPosition = 'center')

Is it something possible? Does it have to do with js or css or simply with an option that I am missing to find?

Your color is in hex format "#RRGGBBAA" It seems that doesn't work for such a format (even outside Rmarkdown). You can use "rgba(68,1,84,0.3)" instead.

But in order to have a correct rendering with a PDF Rmarkdown document, there is something else to do. By default, a htmlwidget in a PDF Rmarkdown document is converted to a PDF figure with webshot::webshot . But sometimes there are certain HTML elements that fail to render to the PDF screenshot. Use the chunk option dev='png' to get a PNG screenshot, which works better.

---
title: "prove27_2"
author: "Roberto Di Pietro"
date: "27/2/2020"
output: pdf_document
editor_options: 
  chunk_output_type: console
---

```{r, dev='png'}
knitr::opts_chunk$set(echo = TRUE)
library(DT)
datatable(cars) %>% 
  formatStyle(names(cars)[2],
              background = styleColorBar(range(cars[,2]), "rgba(68,1,84,0.3)"),
              backgroundSize = '98% 88%',
              backgroundRepeat = 'no-repeat',
              backgroundPosition = 'center')
```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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