R markdown not rendering Latex from HTML - r

I am trying to knit a document using plotly to generate the images and rmarkdown. Below is a basic example:
---
title: "Test"
author: "Me"
date: "`r Sys.Date()`"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(plotly)
library(webshot)
library(webshot2)
```
## R Markdown
This is an R Markdown document. It is a test.
```{r test, echo=FALSE}
x <- seq(-1, 1, 0.1)
y <- dnorm(x, 0, 0.5)
pl1 <- plot_ly(x=x, y=y, type='scatter', mode='lines') %>%
config(mathjax='cdn') %>%
plotly::layout(
showlegend=TRUE,
legend=list(itemsizing='trace', orientation='h',
xanchor='center', x=0.5), margin=list(b=80, l=45, r=30, t=80),
title=list(text=
TeX("M \\text{ updates for } N=n=1 \\text{ for } P(update) = \\gamma_{i}.")))
# pl1
htmlwidgets::saveWidget(widget = pl1, file = "pl1.html")
webshot(url = "pl1.html", file = "pl1.pdf")
The problem is that when I knit the document, the htmlwidgets function generates the correct rendering of Latex (top image), but the webshot function does not (bottom image). Also, I have tried using fig.show='hold' but this doesn't help either.
I have also tried using webshot2 and, when using webshot I have installed webshot::install_phantomjs()

Related

Start rmarkdown report with logo image

I'd like to create a report, but my report need to be start with a logo. In my example, I try to do :
Here is the .rmd file (say, cylinder.rmd)
---
```{r echo=FALSE, out.width = "30%", fig.align = "center"}
knitr::include_graphics("R_logo.png")
```
title: "cylinder_report"
author: "author_name"
date: "2023-01-25"
output: pdf_document
params:
cylinder: 0
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
df = mtcars
```
## Cylinder `r params$cylinder`
```{r output, echo=FALSE}
knitr::kable(df[df$cyl == params$cylinder,])
```
And my separated file is:
library(knitr)
library (rmarkdown)
data(mtcars)
cyls = unique(mtcars$cyl)
for(cyl in cyls) {
rmarkdown::render(
input = "cylinder.Rmd",
output_file = paste0("cylinder_report_", cyl),
params = list(cylinder = cyl)
)
}
#
This code doesn't work, but for better comprehension my desirable output must to be:
Please any help with it?
The solution was find in: https://bookdown.org/yihui/rmarkdown-cookbook/latex-logo.html
The .Rmd needs to be:
---
title: "cylinder_report"
author: "author_name"
date: "2023-01-25"
output: pdf_document
params:
cylinder: 0
header-includes:
- \usepackage{titling}
- \pretitle{\begin{center}
\includegraphics[width=2in,height=2in]{R_logo.png}\LARGE\\}
- \posttitle{\end{center}}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
df = mtcars
```
## Cylinder `r params$cylinder`
```{r output, echo=FALSE}
knitr::kable(df[df$cyl == params$cylinder,])
```

Programmatically create tab and plot in markdown

I'm trying to create a dynamic number of tabs in my rmd with some content inside.
This one doesn't help.
Something like this:
---
title: "1"
output: html_document
---
```{r }
library(highcharter)
library(tidyverse)
iris %>%
dplyr::group_split(Species) %>%
purrr::map(.,~{
# create tabset for each group
..1 %>%
hchart("scatter", hcaes(x = Sepal.Length, y = Sepal.Width))
})
```
You can set results = 'asis' knitr option to generate the tabs in the map function using cat.
Getting Highcharter to work with asis was trickier :
Highchart needs to be called once before the asis chunck, probably to initialize properly, hence the first empty chart.
to print the chart in the asis chunck, the HTML output is sent in character format to cat
Try this:
---
title: "Test tabs"
output: html_document
---
`r knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, cache = F)`
```{r}
library(highcharter)
library(tidyverse)
# This empty chart is necessary to initialize Highcharter in the tabs
highchart(height = 1)
```
```{r, results = 'asis'}
cat('## Tabs panel {.tabset} \n')
invisible(
iris %>%
dplyr::group_split(Species) %>%
purrr::imap(.,~{
# create tabset for each group
cat('### Tab',.y,' \n')
cat('\n')
p <- hchart(.x,"scatter", hcaes(x = Sepal.Length, y = Sepal.Width))
cat(as.character(htmltools::tagList(p)))
})
)
```
Note that while this solution works well, it goes beyond the original use for asis

How to share common code across analyses in R

I’ve copied codes into parent and child file and located the child as C:/temp/child.Rmd
The statements in parent program
---
title: "parent"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(ggplot2)
```
```{r, parent, include = FALSE}
src <- lapply(
sort(unique(iris$Species)),
FUN = function(x) {
knitr::knit_expand(
file = here::here("C:/temp/child.Rmd"),
title = x
)
}
)
```
`r knitr::knit(text = unlist(src))`
The statements in child program
---
title: "child1"
output: pdf_document
---
## {{title}}
```{r plot_{{title}}}
iris %>%
filter(Species == "{{title}}") %>%
ggplot() +
aes(x = Sepal.Length, y = Sepal.Width) +
geom_point() +
labs(title = "{{title}}")
```
When I knit the parent program, the error message as below. Why and how to fix it?
Quitting from lines 14-23 (trypc.Rmd)
Error in file(con, "r") : cannot open the connection
Calls: <Anonymous> ... one_string -> paste -> read_utf8 -> readLines -> file
Execution halted
Thanks

R Markdown not displaying plotly graphics

I am using Rstudio Version 1.1.447. on a Dell Latitude E5470 using Windows 10. I am trying to create a presentation for an assignment using R markdown and knittr and ioslides. The resultant presentation has a complete black page instead of the graph. The graph however does display in Rstudio if I run the code on its own outside of R markdown.
Here is my code:
```{r, echo = TRUE, include=FALSE}
library("plotly")
library("ggplot2")
library("datasets")
data("state")
x <- state.area
y <- state.x77[,1]*1000
z <- state.x77[,5]
fac <- state.division
newdf <- as.data.frame(cbind(state.area, state.x77[,1]*1000, state.x77[,5], state.division))
colnames(newdf) <- c("Area", "Population", "Murder", "Division")
p <-plot_ly(newdf,
x="Area",
y="Population",
z="Murder",
type="scatter3d",
mode="markers",
color="Division")
p
```
Try the same but removing the {r, echo = TRUE, include=FALSE} and replace it with just {r}.
Here is a complete working answer.
---
title: "Plotly in Markdown Example"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library("plotly")
library("ggplot2")
library("datasets")
data("state")
x <- state.area
y <- state.x77[,1]*1000
z <- state.x77[,5]
fac <- state.division
```
## Plot title goes here
Awesome comments about plot output goes here:
```{r}
newdf <- as.data.frame(cbind(state.area, state.x77[,1]*1000, state.x77[,5], state.division))
colnames(newdf) <- c("Area", "Population", "Murder", "Division")
p <-plot_ly(newdf,
x="Area",
y="Population",
z="Murder",
type="scatter3d",
mode="markers",
color="Division")
p
```

Display two rCharts NVD3 figures next to each other in rmarkdown

I want to display two charts with the rCharts package, one next to the other, more or less like the two pies are displayed in this link:
http://nvd3.org/examples/pie.html
I have a partial solution using <iframe>, but the solution has three problems:
It is too case specific
Including controls becomes a complicated task
It does not look too nice
Minimum working example:
---
title: "Example"
output: html_document
---
```{r rcht, message=FALSE, echo=FALSE, results='asis'}
library(rCharts)
df<-data.frame(label=c("One","Two","Three"),valuea=c(1,2,3),othera=c(10,11,12),
valueb=c(4,5,6),otherb=c(10,11,12),stringsAsFactors = FALSE)
p1 <- nPlot(valuea~ label, data = df, type = 'pieChart',height = 225, width = 300)
p2<- nPlot(valueb~ label, data = df, type = 'pieChart',height = 225, width = 300)
p1$show('inline', include_assets = TRUE, cdn = F)
p2$show('inline', include_assets = TRUE, cdn = F)
```
```{r message=FALSE, echo=FALSE}
p1$save("pie1.html", standalone = TRUE)
p2$save("pie2.html", standalone = TRUE)
```
<div align="center">
<font size="10" color="black" face="sans-serif">Both Pies</font><br>
<p>
<iframe src="pie1.html" height="400" width="400"></iframe>
<iframe src="pie2.html" height="400" width="400"></iframe>
</p>
<div>
I know pie charts should not be used and that I could use a multi-bar chart. However, I want to use this type of layout with other kinds of charts in the rCharts package.
Additionally, I would like to include controls in the charts whilst they are shown next to each other. Including the following code before the $save() function adds the controls:
```{r message=FALSE, echo=FALSE}
p1$addControls('y','valuea',values=c('valuea','othera'))
p2$addControls('y','valueb',values=c('valueb','otherb'))
```
This issue is less relevant to me, but if someone has a solution (preferably with only one control for both charts), it would be great.
I understand all this might be too much to handle from R. Any help/advice is appreciated.
Not elegant, but functional (I did not try it with controls):
---
title: "Example"
output: html_document
---
```{r rcht, message=FALSE, echo=FALSE, results='asis'}
library(rCharts)
library(htmltools)
df <- data.frame(label=c("One","Two","Three"),valuea=c(1,2,3),othera=c(10,11,12),
valueb=c(4,5,6),otherb=c(10,11,12),stringsAsFactors = FALSE)
p1 <- nPlot(valuea~ label, data = df, type = 'pieChart',height = 225, width = 300)
p2 <- nPlot(valueb~ label, data = df, type = 'pieChart',height = 225, width = 300)
```
```{r echo=FALSE, results="asis"}
cat("<table width='100%'><tr style='width:100%'><td width='50%'>")
```
```{r echo=FALSE, results="asis"}
p1$show('inline', include_assets = TRUE, cdn = FALSE)
```
```{r echo=FALSE, results="asis"}
cat("</td><td>")
```
```{r echo=FALSE, results="asis"}
p2$show('inline', include_assets = TRUE, cdn = FALSE)
```
```{r echo=FALSE, results="asis"}
cat("</td></tr></table>")
```
Hi I am having the same problem with controls it looks that in the viewer of R-studio everything works fine but not when I compile with Rmarkdown it doesn't show the plot at all.
```{r results = 'asis', comment = NA}
require(rCharts)
require(datasets)
p2 <- nPlot(mpg ~ cyl, group = 'wt',
data = mtcars, type = 'scatterChart')
p2$xAxis(axisLabel = 'Log2')
p2$yAxis(axisLabel = 'Log2')
p2$chart(tooltipContent = "#! function(key, x, y, e){
return '<b>Name:</b> ' + e.point.GeneID
} !#")
p2$chart(color = c('red', 'green'))
p2$addControls("x", value = 'mpg', values = names(mtcars))
p2$addControls("y", value = 'cyl', values = names(mtcars))
cat('<style>.nvd3{height: 400px;}</style>')
p2$print('chart2', include_assets = TRUE)
```
The code above is the addControls are removed actually works also in the rmarkdown.
Also, if you try to run the code above in Rstudio console (just from p2<-nPlot to cat command) and then calling p2 I can actually see the controls.

Resources