Reputation: 79
I'm using Knitr to generate a PDF report, where each page is dynamically created in a loop, displaying plots and tables side by side. The approach works well for tables, but the plots fail to appear in the output.
I'm using ggsurvminer and storing plots in a list, then attempting to print them inside the loop. However, while tables render correctly, the plots do not show up in the final document.
Here’s a MRE illustrating the issue:
#```{r config, include=FALSE}
newslide <- function(content) {
code <- deparse(substitute(content))
cat(sep = "\n",
knitr::knit_child(
quiet = TRUE,
text = c("```{r dpi=600, warning=FALSE, message=FALSE, echo=FALSE, results='asis', escape = TRUE}",
code,
"```")
)
)
}
#```
#```{r latex, echo=FALSE, results = 'asis', escape = "TRUE"}
plot_list <- list()
category <- c("A","B","C")
for (cat in category){
fit <- survfit(Surv(time, status) ~ sex, data = lung)
p <- ggsurvplot(fit, data = lung)
plot_list[[cat]] <- p
}
for (cat in category){
plot1 <- plot_list[[cat]]$plot #I've also tried without "$plot"
table1_latex <- kable(head(lung), format = "latex")
newslide(
content = {
cat("\\begin{multicols}{2}\n")
cat("\\noindent\n")
print(table1_latex)
cat("\\columnbreak\n")
cat("\\begin{center}\n")
print(plot1)
cat("\n")
cat("\\end{center}\n")
cat("\\end{multicols}\n")
}
)
}
I'm getting this error message when knitting:
! Missing $ inserted.
<inserted text>
$
l.561 <!-- -->
Thank you in advance for any suggestions.
Upvotes: 3
Views: 60
Reputation: 79
I solved it by adding cat('\n\n')
directly after printing the plot.
Upvotes: 3