Suppress alt text for GIFs in rmarkdown HTML output - r

I'm generating GIFs using the gganimate package within an RMarkdown file. When using output = github_document in the front matter, the GIF appears as expected in the output (github-document-output). However, when using output = html_document, the GIF generates with alt text, which defaults to the chunk name (html-document-output).
Is there a way to suppress this automatic caption? I've tried setting my own caption using the fig.cap chunk option, but that was unsuccessful.
RMarkdown code
---
output:
html_document: default
github_document: default
---
```{r}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "output/test-fig-",
cache.path = "output/test-cache-"
)
```
```{r cache = FALSE}
library(knitr)
library(animation)
ani.options(autobrowse = FALSE, interval = 1)
opts_knit$set(animation.fun = function(x, options, format = "gif") {
x = c(knitr:::sans_ext(x), knitr:::file_ext(x))
fig.num = options$fig.num
format = sub("^[.]", "", format)
fig.fname = paste0(sub(paste0(fig.num, "$"), "*", x[1]),
".", x[2])
mov.fname = paste0(sub(paste0(fig.num, "$"), "", x[1]), ".",
format)
# order correctly
figs <- Sys.glob(fig.fname)
figs <- figs[order(as.numeric(stringr::str_match(figs, paste0("(\\d+)\\.", x[2]))[, 2]))]
animation::im.convert(figs, output = mov.fname)
sprintf("![%s](%s)", options$label, paste0(opts_knit$get("base.url"), mov.fname))
})
opts_chunk$set(cache = TRUE, message = FALSE, warning = FALSE, fig.show = "animate")
```
```{r pkgs, cache = FALSE}
library(gapminder)
library(ggplot2)
theme_set(theme_bw())
```
```{r setup}
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent, frame = year)) +
geom_point() +
scale_x_log10()
```
```{r dependson = "setup"}
library(gganimate)
gg_animate(p)
```

The problem here is that you include the resulting animation with markdown syntax. This introduces some iiritations I guess.
Taking a look at hook_plot_html we can simulate the default output for standard plots:
sprintf(paste0('<div class="figure %s">',
'<img src="%s">',
'<p class="caption">%s</p>',
'</div>'), options$fig.align, mov.fname, options$fig.cap)

Related

How to suppress downloading progress in HTML file

I am using imfr package to download some IMF data series
library(imfr)
t <- imf_data(database_id = "BOP", indicator = "BCA_BP6_USD",
country = "all", start = "1990", freq = "Q")
I prespecified certain parameters in a separate chunk before to suppress downloading progress
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE, error = FALSE, results = 'hide', fig.keep = 'all')
However, neither of these options did the job. Moreover results = 'hide' suppressed all the output including text and figures.
How can I solve this issue without having a separate chunk for data downloading?
You can capture all those downloads message and progress bar in capture.output and wrap it with invisible. (Got this idea from this question and answer on SO).
And then make a wrapper function imf_data which works the same (mask the imfr::imf_data function) but does not print all those download messages and the progress bar.
---
title: "IMF Data"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE)
imf_data <- function(...) {
invisible(capture.output(dt <- imfr::imf_data(...)))
return(dt)
}
```
```{r}
library(imfr)
t <- imf_data(database_id = "BOP", indicator = "BCA_BP6_USD",
country = "all", start = "1990", freq = "Q")
```
```{r, comment=""}
head(t)
```

rmarkdown resize plot inside of code chunk

I have an rmarkdownfile with a chunck that has a loop that creates many pages. Below is a toy example. See the "loop_chunk" code chunk. The "loop_chunk" has fig.width=9, fig.height=6, results="asis" and I am running into a problem where i need to reduce the size of a plot inside loop_chunk. All plots are 9x6 but I need to adjust one plot. I found the codee below: http://michaeljw.com/blog/post/subchunkify/
and I tried using it below but when you run the code you can see that there are 2 plots on pages 3 and 5 and there should not be. it is somehow not keeping the \newpages. There should be 1 plot on pages 2,3,4 and 5. There should only be 5 pages.
Any idea how to fix this?
---
title: "Untitled"
output: pdf_document
toc: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE , comment = NA, message= FALSE, warning = TRUE)
subchunkify <- function(g, fig_height=7, fig_width=5) {
g_deparsed <- paste0(deparse(
function() {g}
), collapse = '')
sub_chunk <- paste0("
`","``{r sub_chunk_", floor(runif(1) * 10000), ", fig.height=", fig_height, ", fig.width=", fig_width, ", echo=FALSE}",
"\n(",
g_deparsed
, ")()",
"\n`","``
")
cat(knitr::knit(text = knitr::knit_expand(text = sub_chunk), quiet = TRUE))
}
data = data.frame(group= c("A","A"), value = c(1,3))
```
```{r loop_chunk, fig.width=9, fig.height=6, results="asis", message= FALSE, warning = FALSE}
for(i in 1:nrow(data)){
cat(paste0("\\newpage\n # Page ", i ," \n"))
plot(data$value[i])
cat("\n\n")
cat(paste0("\\newpage\n ## page with smaller plot \n\n"))
cat("Here is some text on this page for the smaller plot.")
cat("\n\n")
data2 = data.frame(x = 7, y = 900)
library(ggplot2)
myplot = ggplot(data2, aes(x = x, y = y ))+geom_point()
subchunkify(myplot , 4,4 )
# print(myplot) -> IS there a way to just reduce the height and width with print()?
cat("\n\n")
}
```
Using your subchunkify() function for the graphics::plot call outputs those plots to the intended pages. Replacing plot(data$value[i]) in your second chunk with
subchunkify(plot(data$value[i]), 5, 5)
outputs the 5 pages with plots as intended (where height & width are set to 5/can be edited to conditionally set dimensions for a specific plot).

Rotate column headers on Hmisc generated table

I need to rotate the headers from a table 90 degrees using the Hmisc package. I tried changing the 'colnamesTexCmd' command but nothing changes on the column headers.
Below is a reproducible example of my problem
---
title: ""
author: ""
date: "November 20, 2015"
header-includes:
- \usepackage{longtable, colortbl, xcolor, lscape, rotating, ctable}
output: rmarkdown::tufte_handout
---
```{r tableDescStatTest, results ='asis', echo=FALSE, message = FALSE, warning = FALSE, include=TRUE}
library(Hmisc)
data(iris)
DescTableTest <- summary(Species ~ Sepal.Length + Sepal.Width,
data = iris,
method = "reverse",
test = T,
continuous = 0)
# fuction to take the first row of comment from the latex output
mylatex <- function (...) {
o <- capture.output(latex(...))
# this will strip /all/ line-only comments; or if you're only
# interested in stripping the first such comment you could
# adjust accordingly
o <- grep('^%', o, inv=T, value=T)
cat(o, sep='\n')
}
# render the table
options(digits = 1)
mylatex(DescTableTest,
exclude1 = FALSE,
colnamesTexCmd = "rotatebox{90}",
npct = 'numerator',
npct.size = "footnotesize",
what = c('%'),
landscape = FALSE,
file = "",
long = T,
middle.bold = TRUE,
longtable = FALSE,
overall = TRUE,
label = "tbl:descTable1",
prmsd = FALSE,
caption = "Descriptive statistics",
caption.loc = 'bottom',
where = "!htbp")
```
You are using the S3 latex method for class summary.formula.reverse
? Hmisc::summary.formula
which does not take the argument colnamesTexCmd

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.

R kableExtra latex: Add linebreaks to rotated header row

I'm trying to produce table to a Latex-pdf document. I'm using kableExtra and knitr in R.
I have a table that has long column names. When I rotate the header row by 90 degrees linebreaks won't work. Does anyone have an idea how I could achieve both rotated row and linebreaks?
My example is the same as in Hao's Best Practice for newline in Latex table, but I added piped row_spec to the end of the code.
\documentclass[10pt,a4paper]{article}
\usepackage[table]{xcolor}
\begin{document}
\begin{table}
<<global_options, echo=FALSE>>=
library(kableExtra)
library("dplyr")
dt_lb <- data.frame(
Item = c("Hello\nWorld", "This\nis a cat"),
Value = c(10, 100)
)
dt_lb %>%
mutate_all(linebreak) %>%
kable("latex", booktabs = T, escape = F,
col.names = linebreak(c("Item\n(Name)", "Value\n(Number)"))) %>%
row_spec(0, angle = 90, align='l', monospace=T)
#
\end{table}
\end{document}
What I get is this, but the [l] tags hint that there's something else wrong with the tags as well:
On StackExchange TEX I found a question about rotation and linebreaks, this is what I'm trying achieve: https://tex.stackexchange.com/questions/14730/big-table-with-rotated-column-labels-using-booktabs
You could use tableHTML:
library(tableHTML)
Replace the new line character "\n" with the HTML tag <br>:
headers <- c("Item\n(Name)", "Value\n(Number)") %>%
stringr::str_replace_all(pattern = "\\n", replacement = "<br>")
Create a tableHTML object and rotate the headers using add_css_header():
dt_lb %>%
tableHTML(rownames = FALSE,
headers = headers,
escape = FALSE,
widths = c(100, 100),
theme = 'scientific') %>%
add_css_header(css = list(c('transform', 'height', 'text-align'),
c('rotate(-45deg)', '70px', 'center')),
headers = 1:2)
The result looks like this:
Note: you can add more css or default themes. Check out the vignettes for more details:
If you want to create a pdf document, you could use RMarkdown:
---
title: "tableHTML2pdf"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
\
```{r}
library(tableHTML)
dt_lb <- data.frame(
Item = c("Hello\nWorld", "This\nis a cat"),
Value = c(10, 100)
)
headers <- c("Item\n(Name)", "Value\n(Number)") %>%
stringr::str_replace_all(pattern = "\\n", replacement = "<br>")
dt_lb %>%
tableHTML(rownames = FALSE,
headers = headers,
escape = FALSE,
widths = c(100, 100),
theme = 'scientific') %>%
add_css_header(css = list(c('transform', 'height', 'text-align'),
c('rotate(-45deg)', '70px', 'center')),
headers = 1:2)
```
\
It will then create an HTML file. This file can then be converted to PDF using wkhtmltopdf.
I think you probably rendered your rmarkdown document into HTML... In the rmarkdown yaml header, does it say html_document right now? If so, you can try to change it to pdf_document.....
I rendered a pdf_document with exactly the same code and I think I got what you were looking for...
---
title: "Table Sample"
output: pdf_document
---
``` {r, include = FALSE}
library(tidyverse)
library(kableExtra)
```
```{r}
dt_lb <- data.frame(
Item = c("Hello\nWorld", "This\nis a cat"),
Value = c(10, 100)
)
dt_lb %>%
mutate_all(linebreak) %>%
kable("latex", booktabs = T, escape = F,
col.names = linebreak(c("Item\n(Name)", "Value\n(Number)"), align = "c")) %>%
row_spec(0, angle = 90)
```
Latex package makecell was missing.
Hao pointed out that Page 3 of this manual lists some of the necessary Latex packages: haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf

Resources