Adding background image to R Markdown (.rmd) file for PDF document? - r

I have seen this post to include a background image to an R markdown report.
I have created a Shiny app to generate a pdf report:
shinyApp(
ui = fluidPage(
sliderInput("slider", "Slider", 1, 10, 5),
downloadButton("report", "Generate report")
),
server = function(input, output) {
test1 <- reactive({
n = input$slider
df=matrix(1:n^2,n,n)
df = as.data.frame(df)
result <- list(df=df,n=n)
return(result)
})
output$report <- downloadHandler(
# For PDF output, change this to "report.pdf"
filename = "report.pdf",
content = function(file) {
# Copy the report file to a temporary directory before processing it, in
# case we don't have write permissions to the current working dir (which
# can happen when deployed).
tempReport <- file.path(tempdir(), "report.Rmd")
file.copy("report.Rmd", tempReport, overwrite = TRUE)
# Set up parameters to pass to Rmd document
params <- list(n = test1()$n,
df = test1()$df)
# Knit the document, passing in the `params` list, and eval it in a
# child of the global environment (this isolates the code in the document
# from the code in this app).
rmarkdown::render(tempReport, output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
}
)
}
)
And here is my .rmd file :
---
title: "Title"
author: "Name"
date: "`r Sys.Date()`"
output:
pdf_document :
fig_caption: yes
keep_tex: yes
number_sections: yes
header-includes:
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{array}
\usepackage{multirow}
\usepackage{wrapfig}
\usepackage{float}
\usepackage{colortbl}
\usepackage{pdflscape}
\usepackage{tabu}
\usepackage{threeparttable}
\usepackage{threeparttablex}
\usepackage[normalem]{ulem}
\usepackage{makecell}
\usepackage{background}
\backgroundsetup{
scale=1,
color=black,
opacity=0.4,
angle=0,
pages=all,
contents={
\includegraphics[width=\paperwidth,height=\paperheight]{C:/Users/path_to_image/image.jpg}
}
}
params:
n: NA
df: NA
---
```{r}
# The `params` object is available in the document.
params$n
```
A plot of `params$n` random points.
```{r}
plot(rnorm(params$n), rnorm(params$n))
```
```{r}
params$df %>%
mutate_if(is.numeric, function(x) {
cell_spec(x, "latex", bold = T, color = spec_color(x, end = 0.85),
font_size = spec_font_size(x))
}) %>%
kable("latex", escape = F, booktabs = T, linesep = "", align = "c")%>%
kable_styling(latex_options = c("striped", "scale_down"))
```
The error that I'm getting is :
! Undefined control sequence.
l.171 \centering\rowcolors
{2}{gray!6}{white}
Here is how much of TeX's memory you used:
24161 strings out of 492990
415742 string characters out of 6136334
504502 words of memory out of 5000000
27291 multiletter control sequences out of 15000+600000
19644 words of font info for 30 fonts, out of 8000000 for 9000
1141 hyphenation exceptions out of 8191
62i,4n,56p,577b,315s stack positions out of 5000i,500n,10000p,200000b,80000s
[1]: http
Which in tex community they referring to forgetting something like \end{document}. I should mention that if I use the .rmd file alone and replace the last part with :
{r}
library(kableExtra)
library(dplyr)
iris[1:10, ] %>%
mutate_if(is.numeric, function(x) {
cell_spec(x, "latex", bold = T, color = spec_color(x, end = 0.9),
font_size = spec_font_size(x))
}) %>%
mutate(Species = cell_spec(
Species, "latex", color = "white", bold = T,
background = spec_color(1:10, end = 0.9, option = "A", direction = -1)
)) %>%
kable("latex", escape = F, booktabs = T, linesep = "", align = "c")
I will be able to compile it with that background image, the current shiny app is also generating the report if I exclude the part that related to the background image setting.

That's because xcolor must be loaded before background. Do:
---
title: "Title"
author: "Name"
date: "`r Sys.Date()`"
output:
pdf_document :
fig_caption: yes
keep_tex: yes
number_sections: yes
header-includes:
\usepackage{background}
\usepackage{float}
\backgroundsetup{
scale=1,
color=black,
opacity=0.4,
angle=0,
pages=all,
contents={
\includegraphics[width=\paperwidth,height=\paperheight]{C:/Users/path_to_image/image.jpg}
}
}
---
Note that your "header-includes" is useless because all these packages are automatically included.

Related

Rmarkdown document not rendering properly in Shiny App

I have a parametrized rmarkdown document based on Shiny inputs.
The rmarkdown pdf renders properly when the app runs locally. However when hosted on the shiny server it produces \end{landscape} at the end of each table.
Here is a snippet of the rmarkdown code:
---
title: "Custom Analysis Report"
date: "Last compiled on `r format(Sys.time(), '%d %B, %Y')`"
output:
pdf_document:
mainfont: Times New Roman
fontsize: 11pt
header-includes:
- \usepackage{booktabs}
- \usepackage{longtable}
- \usepackage{array}
- \usepackage{multirow}
- \usepackage{wrapfig}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage{pdflscape}
- \usepackage{lscape}
- \usepackage{tabu}
- \usepackage{threeparttable}
- \usepackage{threeparttablex}
- \usepackage[normalem]{ulem}
- \usepackage{makecell}
- \usepackage{xcolor}
always_allow_html: true
---
```{r setup, include=FALSE}
library(knitr)
library(kableExtra)
```
```{r echo = FALSE , warning = FALSE, message = FALSE, eval = TRUE , results='asis'}
if (nrow(org_profile_df1()) >= 1){
options(knitr.kable.NA = 'NA')
org_profile_df1() %>%
kable(align = "l",
format = "latex",
longtable = T,
booktabs = T,
caption = "Organizational Profile") %>%
kable_classic(full_width = F) %>%
# column_spec(1, bold = T, color = "red") %>%
kable_styling(latex_options = c("repeat_header", "bordered", "striped"),font_size = 4, position = "left",
#,"striped", "scale_down"),
repeat_header_continued = "\\textit{(Continued on Next Page...)}") %>%
#kable_paper(full_width = T) %>%
row_spec(0, bold = T) %>% landscape()
}
options(knitr.kable.NA = '-')
```
org_profile_df1() is a reactive dataset that is generated by shiny parameters. There are other such reactive datasets that get generated based on whether they exist or not (the if-statements). After every one of these tables a blank page with \end{landscape} appears (see also picture). However when I run the shiny app locally this does not appear. Only when the app is hosted on Shinyapps.io does this occur.
I have included a picture of a reactive table. There are special characters such as % and : in the reactviely generated tables.

LaTex code inside a kable table in an rmarkdown::beamer_presentation

In a larger report compiled with bookdown I used several kableExtra tables which included LaTex commands (e.g., to add italics, bullets to create a listing, and manually-added footnotes within the table).
When I copy the tables in a LaTex beamer presentation generated with rmarkdown::beamer_presentation, compilation unfortunately fails.
How to twist the kableExtra tables to include the LaTex commands?
MWE
---
title: "MWE"
subtitle: "Beamer presentation with R-markdown"
author: "Donald Duck"
institute: "some place"
date: "`r format(Sys.time(), '%B %d, %Y')`"
output:
bookdown::pdf_book:
base_format: rmarkdown::beamer_presentation
theme: "THEMENAME"
latex_engine: xelatex
toc: false
slide_level: 2
---
(ref:footnote-a) Text for footnote a
(ref:footnote-b) Text for footnote b
\renewcommand{\arraystretch}{1.3} <!-- increase line spacing for the table -->
```{r table-wLatex, echo=FALSE, fig.align="center", message=FALSE, warning=FALSE, out.width='66%'}
library(kableExtra)
library(dplyr)
# table with manually added footnotes within table
df <- data.frame(
col1 = c("Category 1", "Category 2"),
col2 = c(
"foo and \\emph{special foo}$^{a}$",
"bar and \n $\\boldsymbol{\\cdot}$ \\emph{random bar}$^{a}$\n $\\boldsymbol{\\cdot}$ \\emph{special bar}$^{b}$")
)
# header: add column names
names(df) <- c("Categories", "Description")
df %>%
mutate_all(linebreak) %>% # required for linebreaks to work
kable(
"latex",
# escape = FALSE, # needed to be able to include latex commands
booktabs=TRUE,
align = "l",
caption = "Caption Table with LaTex" # short caption for LoT
) %>%
kableExtra::footnote(
alphabet = c(
"(ref:footnote-a)",
"(ref:footnote-b)"
),
threeparttable = TRUE, # important! Else footnote runs beyond the table
footnote_as_chunk = TRUE, title_format = c("italic", "underline")
) %>%
column_spec(1, width = "11em") %>% # fix width column 1
column_spec(2, width = "27em") # fix width column 2
```
\renewcommand{\arraystretch}{1} <!-- reset row height/line spacing -->
Several LaTex packages had to be loaded for kableExtra table such that LaTex code can well be included inside.
To fix the column width, column_spec(1, width = "3cm") is better specified in cm instead of em (for the previous specification, table ran beyond the slide).
---
title: "LaTex code inside a kable table in an rmarkdown::beamer_presentation"
output:
bookdown::pdf_book:
base_format: rmarkdown::beamer_presentation
latex_engine: xelatex
toc: false
slide_level: 2
header-includes:
- \usepackage{booktabs}
- \usepackage{longtable}
- \usepackage{array}
- \usepackage{multirow}
- \usepackage{wrapfig}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage{pdflscape}
- \usepackage{tabu}
- \usepackage{threeparttable}
- \usepackage{threeparttablex}
- \usepackage[normalem]{ulem}
- \usepackage{makecell}
# - \usepackage[usenames,dvipsnames]{xcolor} # clashes, as loaded by markdown anyway
---
(ref:footnote-a) Text for footnote a
(ref:footnote-b) Text for footnote b
\renewcommand{\arraystretch}{1.3} <!-- increase line spacing for the table -->
```{r table-wLatex, echo=FALSE, fig.align="center", message=FALSE, warning=FALSE, out.width='30%'}
library(kableExtra)
library(dplyr)
# table with manually added footnotes within table
df <- data.frame(
col1 = c("Category 1", "Category 2"),
col2 = c(
"foo and \\emph{special foo}$^{a}$",
"bar and \n $\\boldsymbol{\\cdot}$ \\emph{random bar}$^{a}$\n $\\boldsymbol{\\cdot}$ \\emph{special bar}$^{b}$")
)
# header: add column names
names(df) <- c("Categories", "Description")
df %>%
mutate_all(linebreak) %>% # required for linebreaks to work
kable(
"latex",
escape = FALSE, # needed to be able to include latex commands
booktabs=TRUE,
align = "l",
caption = "Caption Table with LaTex" # short caption for LoT
) %>%
kableExtra::footnote(
alphabet = c(
"(ref:footnote-a)",
"(ref:footnote-b)"
),
threeparttable = TRUE, # important! Else footnote runs beyond the table
footnote_as_chunk = TRUE, title_format = c("italic", "underline")
) %>%
kable_styling( # for wide tables: scale them down to fit
full_width = F,
latex_options = c(
"scale_down"
)) %>%
column_spec(1, width = "3cm") %>% # fix width column 1
column_spec(2, width = "5cm") # fix width column 2
```
\renewcommand{\arraystretch}{1} <!-- reset row height/line spacing -->

Shiny to Markdown PDF Fails on Second and Subsequent Runs

I've been trying to follow this tutorial: generating reports
I've been able to get the suggested code to run successfully and produces PDFs without issue. When I try to run the Shiny app using my own .Rmd file, it works fine the first time and produces a PDF where desired. On the second and any additional runs, the file generation fails with ! LaTeX Error: Unknown float option 'H'.
I've tried mentioning the {float} package in the YAML header of the markdown file without any improvement. The only success seems to be removing all of the r code blocks, which leaves my document looking pretty sparse.
Here is app.R:
shinyApp(
ui = fluidPage(
sliderInput("slider", "Slider", 1, 100, 50),
dateInput("dateinput", "Select a date"),
downloadButton("report.pdf", "Generate report")
),
server = function(input, output) {
output$report.pdf <- downloadHandler(
filename = "report.pdf",
content = function(file) {
tempReport <- file.path(tempdir(), "deviants.Rmd")
file.copy("deviants.Rmd", tempReport, overwrite = TRUE)
params <- list(n = input$slider, d = input$dateinput)
print(class(params$n))
print(class(params$d))
print(params)
rmarkdown::render(tempReport, output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
}
)
}
)
and deviants.Rmd:
---
output: pdf_document
always_allow_html: yes
params:
n: NA
d: NA
header-includes:
- \usepackage{booktabs}
- \usepackage{sectsty} \subsectionfont{\centering}
- \usepackage{sectsty} \sectionfont{\centering}
- \usepackage{float{
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(grid)
library(png)
library(dplyr)
```
```{r echo=FALSE, results='asis'}
cat(params$n)
cat(params$d)
```
```{r echo=FALSE}
sampleMetrics <- data.frame(
Sample = c("Threshold","A","2","4","11","C","DEF"),
Length = c(">= 6", 10, 11, 11, 11, 11, 12),
Experiment1 = c(">= 10000",5696,8006,6675,9477,5028,7093),
Experiment2 = c(">= 10000", 21223, 27890, 34623, 24152, 25716, 45187),
Sum = c(">=20000", 28409, 41895, 46181, 34129, 12244, 51910),
Total1 = c("N/A", 41382, 132670, 78271, 89930, 98788, 13015),
Total2 = c("N/A", 43170, 53280, 57568, 46584, 51156, 55045),
stringsAsFactors = FALSE
)
super_cell_spec <- function(data, threshold) {
cell_spec(as.numeric(data), "latex", background = ifelse(
as.numeric(data) >= threshold, "#45ff41", "#ff4242"))
}
sampleMetrics$Length[-1] <- super_cell_spec(sampleMetrics$Length[-1], 6)
sampleMetrics$Experiment1[-1] <- super_cell_spec(
sampleMetrics$Experiment1[-1], 10000)
sampleMetrics$Experiment2[-1] <- super_cell_spec(
sampleMetrics$Experiment2[-1], 10000)
sampleMetrics$Sum[-1] <- super_cell_spec(sampleMetrics$Sum[-1], 20000)
sampleMetrics[1,] <- cell_spec(sampleMetrics[1,], "latex",
background = "#afafaf")
sampleMetrics%>%
kable("latex", booktabs = F, escape = F,
col.names = linebreak(c("Sample",
"Length", "Experiment 1",
"Experiment 2","Sum",
"Total\n1", "Total\n2"),
align = "c")) %>%
kable_styling(latex_options = "scale_down")
```
I definitely wouldn't be as confused if it didn't work flawlessly the first time around. Maybe something to do with the envir = new.env(parent = globalenv()) in app.R? Thanks for any thoughts.
Managed to fix this by adding additional packages, mostly through the trial and error of ! Undefined control sequence errors. It would report an issue with multirow and I would look up the right latex package to include.
In the end, my YAML Rmarkdown header looked like:
---
output: pdf_document
always_allow_html: yes
params:
d: NA
st: NA
header-includes:
- \usepackage[table]{xcolor}
- \usepackage{makecell, tabularx, float, multirow, pgfplots}
- \usepackage{booktabs}
- \usepackage{sectsty} \subsectionfont{\centering}
- \usepackage{sectsty} \sectionfont{\centering}
---
This fixed the problem.

Rmarkdown Kable with custom background colors knits successfully, but fails when called from render

I have written an Rmarkdown file that loads some data and generates a kableExtra table with some symbols and custom colors and lines, printing it to pdf.
It works when I open the Rmarkdown file and knit, and produces the exact output that I want. For various reasons I need to call this Rmarkdown file from another .R file.
However, when I do this (using the rmarkdown::render function), I get an error that doesn't occur when knitted directly from within the .Rmd file. Specifically, the errors are caused by setting background within the cell_spec function; removing this call to set the background color allows me to successfully render the .Rmd file from another file. The error is:
! Illegal parameter number in definition of \reserved#a.
<to be read again>
f
l.111 ...; background-color: #ffe6e6;" >1</span>}}
\\
Thanks so much for any advise.
Here is a complete Rmd file that reproduces the issue. The output when knitted directly from Rmd looks like this:
Here is the code.
---
title: ""
always_allow_html: yes
output:
pdf_document:
latex_engine: xelatex
geometry: margin=0.3in
header-includes:
- \usepackage[T1]{fontenc}
- \usepackage{array}
- \usepackage{booktabs}
- \usepackage{xcolor}
- \usepackage{makecell}
- \usepackage{longtable}
- \usepackage{multirow}
- \usepackage{wrapfig}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage{pdflscape}
- \usepackage{tabu}
- \usepackage{threeparttable}
- \usepackage{threeparttablex}
- \usepackage[normalem]{ulem}
- \usepackage{hyperref}
- \setmainfont{Helvetica}
- \pagenumbering{gobble}
- \DeclareTextCommand{\nobreakspace}{TU}{\leavevmode\nobreak\ }
documentclass: article
classoption: a4paper
---
```{r, echo=FALSE, message = FALSE, warning = FALSE}
# Packages
suppressMessages(library(ggplot2))
suppressMessages(library(extrafont))
suppressMessages(library(dplyr))
suppressMessages(library(pander))
suppressMessages(library(kableExtra))
# Data
table_dat <- data.frame(latex_symbol = c("", "$\\blacktriangle$",
"$\\blacklozenge$", "$\\blacklozenge$",
"$\\bullet$", "+"),
color = c("#0c0000", "#ffde71", "#cb6f86",
"#0c0000", "#0c0000", "#0c0000"),
name = c("Thing 1", "Thing 2", "Thing 3",
"Thing 4", "Thing 5", "Thing 6"),
latex_font_size = c(14, 11, 8, 11, 16, 8),
value = c(1,"<0",3,4,5,6),
stringsAsFactors = FALSE)
fsize <- 12
bgcolor <- c(rep("#ffe6e6",2), rep("#ffffff", 4))
table_dat$value <- cell_spec(table_dat$value, background = bgcolor)
ktable <- table_dat %>%
rename(color_ = color) %>%
mutate(latex_symbol = cell_spec(latex_symbol, color = color_,
font_size = latex_font_size,
escape = FALSE,
format = "latex")) %>%
select(latex_symbol, name, value) %>%
kable(escape = FALSE, align = rep("l", 3),
booktabs = TRUE, format = "latex",
col.names = c("Symbol", "Name", "Value"),
linesep = "") %>%
row_spec(1:6, color = "darkgray") %>%
row_spec(0, bold = TRUE) %>%
column_spec(1, "5em") %>%
column_spec(2, "11em") %>%
column_spec(3, "4em") %>%
kable_styling(font_size = fsize) %>%
row_spec(1, bold = TRUE) %>%
row_spec(1:4, hline_after = TRUE)
```
```{r, echo=FALSE}
ktable
```
Note: the reason for so many packages being cited explicitly in the header is that I've had issues similar to this in the past that were solved by citing all of the packages associated with kable in my header before rendering. However, that didn't seem to solve my problem this time.

Update plot from interactive table in html

What I would like to be able to do is to update the plot based on the output from the (DT-)table after filtering in the html.
For example - here is a screenshot of the table filtered for maz in the html:
I would like the scatter plot to update to only show the values shown in the filtered table.
Is this possible? I know I could achieve something like this using a shiny web app, but is it possible to embed some shiny code into the html to achieve this? (I have very limited experience using shiny/html so would be grateful for any pointers/ideas).
I am using R-markdown (and here is a link to the html produced):
---
title: "Filter interative plots from table results"
date: "`r format(Sys.time(), '%B %e, %Y')`"
output:
html_notebook:
theme: flatly
toc: yes
toc_float: yes
number_sections: true
df_print: paged
html_document:
theme: flatly
toc: yes
toc_float: yes
number_sections: true
df_print: paged
---
```{r setup, include=FALSE, cache=TRUE}
library(DT)
library(plotly)
library(stringr)
data(mtcars)
```
# Clean data
## Car names and models are now a string: "brand_model" in column 'car'
```{r include=FALSE}
mtcars$car <- rownames(mtcars)
mtcars$car <- stringr::str_replace(mtcars$car, ' ', '_')
rownames(mtcars) <- NULL
```
# Interactive table using DT
```{r rows.print=10}
DT::datatable(mtcars,
filter = list(position = "top"),
selection="none", #turn off row selection
options = list(columnDefs = list(list(visible=FALSE, targets=2)),
searchHighlight=TRUE,
pagingType= "simple",
pageLength = 10, #default length of the above options
server = TRUE, #enable server side processing for better performance
processing = FALSE)) %>%
formatStyle(columns = 'qsec',
background = styleColorBar(range(mtcars$qsec), 'lightblue'),
backgroundSize = '98% 88%',
backgroundRepeat = 'no-repeat',
backgroundPosition = 'center')
```
# Plot disp against mpg using plotly
```{r fig.width=8, fig.height=8}
p <- plot_ly(data = mtcars,
x = ~disp,
y = ~mpg,
type = 'scatter',
mode = 'markers',
text = ~paste("Car: ", car, "\n",
"Mpg: ", mpg, "\n"),
color = ~mpg,
colors = "Spectral",
size = ~-disp
)
p
```
Contrary to my first assessment, it is actually possible. There are multiple additions to your code. I will go through them chronologically:
You need to add runtime: shiny in the yaml-header to start shiny in any R-markdown file
Optional: I added some css style in case you need to adjust your shiny application to fit into certain screen sizes
Shiny-documents contain an UI-part, where you configure the user interface. Usually you just use a fluidPage function for that
The next part is the server.r-part where the interesting stuff happens:
We assign, i.e., your DT::datatable to an output-object (usually a list)
For each assignment we need to set a shinyID which we configure in ui.r and then add, i.e, output$mytable
I added an element which shows which rows are selected for debugging
The heart of all the changes is input$mytable_rows_all. All the controls we set up in the ui.r can be called inside the render-functions. In this particular case mytable refers to the shinyID I set for the DT::datatable in the UI-part and rows_all tells shiny to take all the rownumbers inside the shown table.
That way we just subset the data using mtcars[input$mytable_rows_all,]
To learn shiny I recommend Rstudio's tutorial. After learning and forgetting everything again I advise you to use the wonderful cheatsheet provided by Rstudio
The whole modified code looks like this:
---
title: "Filter interative plots from table results"
date: "`r format(Sys.time(), '%B %e, %Y')`"
runtime: shiny
output:
html_document:
theme: flatly
toc: yes
toc_float: yes
number_sections: true
df_print: paged
html_notebook:
theme: flatly
toc: yes
toc_float: yes
number_sections: true
df_print: paged
---
<style>
body .main-container {
max-width: 1600px !important;
margin-left: auto;
margin-right: auto;
}
</style>
```{r setup, include=FALSE, cache=TRUE}
library(stringr)
data(mtcars)
```
# Clean data
## Car names and models are now a string: "brand_model" in column 'car'
```{r include=FALSE}
mtcars$car <- rownames(mtcars)
mtcars$car <- stringr::str_replace(mtcars$car, ' ', '_')
rownames(mtcars) <- NULL
```
# Plot disp against mpg using plotly
```{r}
library(plotly)
library(DT)
## ui.r
motor_attributes=c('Cylinder( shape): V4','Cylinder( shape): V6','Cylinder( shape): V8','Cylinder( shape): 4,Straight Line','Cylinder( shape): 6,Straight Line','Cylinder( shape): 8,Straight Line','Transmission: manual','Transmission: automatic')
fluidPage(# selectizeInput('cyl','Motor characteristics:',motor_attributes,multiple=TRUE,width='600px'),
downloadLink('downloadData', 'Download'),
DT::dataTableOutput('mytable'),
plotlyOutput("myscatter"),
htmlOutput('Selected_ids'))
### server.r
output$mytable<-DT::renderDataTable({
DT::datatable(mtcars,
filter = list(position = "top"),
selection='none', #list(target='row',selected=1:nrow(mtcars)), #turn off row selection
options = list(columnDefs = list(list(visible=FALSE, targets=2)),
searchHighlight=TRUE,
pagingType= "simple",
pageLength = 10, #default length of the above options
server = TRUE, #enable server side processing for better performance
processing = FALSE)) %>%
formatStyle(columns = 'qsec',
background = styleColorBar(range(mtcars$qsec), 'lightblue'),
backgroundSize = '98% 88%',
backgroundRepeat = 'no-repeat',
backgroundPosition = 'center')
})
output$Selected_ids<-renderText({
if(length(input$mytable_rows_all)<1){
return()
}
selected_rows<-as.numeric(input$mytable_rows_all)
paste('<b> #Cars Selected: </b>',length(selected_rows),'</br> <b> Cars Selected: </b>',
paste(paste('<li>',rownames(mtcars)[selected_rows],'</li>'),collapse = ' '))
})
output$myscatter<-renderPlotly({
selected_rows<-as.numeric(input$mytable_rows_all)
subdata<-mtcars[selected_rows,]
p <- plot_ly(data = subdata,
x = ~disp,
y = ~mpg,
type = 'scatter',
mode = 'markers',
text = ~paste("Car: ", car, "\n",
"Mpg: ", mpg, "\n"),
color = ~mpg,
colors = "Spectral",
size = ~-disp
)
p
})
```

Resources