this recently came up with the gt:: package but I also remember this from kableExtra as well iirc.
I'm trying to both use the packages title option but also RMarkdowns fig.cap.
Is there a way to enable both or do I have to work around it, for example with {{captioneer}} ?
edit: this question has been solved using gt::gt(caption = "xy")
Next: is it possible to place this caption at the bottom of the table?
Thanks!
---
title: "gt caption"
author: ""
date: "10 5 2022"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Header
```{r, fig.cap="I also want this fig.cap", echo = FALSE}
tab <- gt::gt(pressure, caption = "xy")
tab <- gt::tab_header(tab,
title = gt::md(
"Title via tab_header"))
tab
```
You could replace the caption argument in gt() with gt::tab_footnote()
tab <- gt::gt(pressure)
tab <- gt::tab_footnote(tab, footnote = "xy")
tab <- gt::tab_header(tab,
title = gt::md(
"Title via tab_header"))
tab
Related
I am using bookdown to create pdf reports, but my tables are all floating down to the bottom of the page, regardless of how much space there is. See this example:
---
title: "test_doc"
author: "Jake Thompson"
date: "6/30/2017"
output:
bookdown::pdf_document2:
toc: false
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, collapse = TRUE)
library(tidyverse)
```
# Test heading
Let make a data frame and print it in Table \#ref(tab:test-table)
```{r test-table}
data_frame(col_a = seq_len(5), col_b = rnorm(5), col_c = runif(5)) %>%
knitr::kable(caption = "This is a test")
```
The resulting pdf looks like this:
Why does the table go to the bottom of the page? And is there a way to prevent this behavior?
You can solve this problem with kableExtra by
data_frame(col_a = seq_len(5), col_b = rnorm(5), col_c = runif(5)) %>%
knitr::kable(caption = "This is a test") %>%
kableExtra::kable_styling(latex_options = "hold_position")
It basically insert a [!h] to the LaTeX table environment which will prevent the floating behavior and pin the table at current location.
I had to use
kable_styling(latex_options = "HOLD_position")
Note the uppercase HOLD_position, different from hold_position. See also here.
To be able to use that, I also had to add to the top section of the doc (from How to build a latex kable through bookdown::render_book?):
output:
pdf_document:
extra_dependencies: ["float"]
Default R Markdown captions in Word appear as:
Figure 1: Figure Title
Table 1: Table Title
I would like to format my captions so that the Figure 1/Table 1 is bold and the title is italic on the next line. This is the APA style of captions:
Figure 1
Figure Title
I have been trying to figure out an easy way to do this, but can't seem to find a solution. (If figure captions can be above figure, rather than below, that would also be great!). Here is a minimal reprex:
---
title: "Untitled"
author: "Test"
date: "11/8/2020"
output:
bookdown::word_document2: default
---
{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(flextable)
{r table, tab.cap="Descriptives", echo=FALSE, message=FALSE, warning=FALSE}
psych::describe(cars) %>%
as.data.frame() %>%
flextable() %>%
set_table_properties(layout = "autofit", width = 1)
{r fig, fig.cap="Pressure Figure", echo=FALSE, message=FALSE, warning=FALSE}
plot(pressure)
For tables you can do it with officedown, officer and flextable packages, styling in reference_doxc, and by taking the advantage of "\n\n" for tables.
In yaml in the pre argument you set up a prefix for every table and a separator between the number and the title itself.
---
title: "Untitled"
author: "Test"
date: "11/8/2020"
output:
officedown::rdocx_document:
tables:
caption:
pre: 'Table '
sep: ''
---
With
tab.cap.fp_text = officer::fp_text_lite()
you can define the formatting of the caption prefix. In APA style it would be bold without italics, preferrably configured in the global knitr options, e.g.
knitr::opts_chunk$set(tab.cap.fp_text = officer::fp_text_lite(italic = FALSE, bold = TRUE))
And you add
"\n\n"
to the table caption to produce a new line
{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, tab.cap.fp_text = officer::fp_text_lite(italic = FALSE, bold = TRUE))
library(tidyverse)
library(flextable)
{r table, tab.cap="\n\nDescriptives", echo=FALSE, message=FALSE, warning=FALSE}
psych::describe(cars) %>%
as.data.frame() %>%
flextable() %>%
set_table_properties(layout = "autofit", width = 1)
The last thing is to create a reference_doxc in which you add italics to the table caption style. The caption prefix is not affected, as you control it with the knitr options.
i am new to R and recently started working on a Shiny App. While I've managed to fix most of the problems in the project, I've been struggling with a menu issue for a while. Specifically, over the two inputs that I want to use I want to plot an image that depends on the first input (selectInput). I do this through a renderImage function, but the problem is that when plotting these images a space is generated that I cannot eliminate. I have tried using renderPlot and renderText, but the problem is not solved or they do not give the desired results. Is there a way to eliminate or reduce this space? I am attaching a simplified version of my code and an image of the problem.
---
title: "TEST"
output:
flexdashboard::flex_dashboard:
orientation: rows
runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r paquetes, include=FALSE}
{
library(data.table)
library(dplyr)
library(plyr)
library(highcharter)
library(flextable)
library(officer)
library(readxl)
library(gridExtra)
library(plotly)
library(ggrepel)
library(kableExtra)
library(knitr)
library(scales)
library(flexdashboard)
}
```
Sidebar {.sidebar data-width=300}
=====================================
<center>
```{r echo = FALSE}
renderImage({
filename <- paste0("images/",input$countryInput,".png")
list(src = filename, height = 100)
})
```
</center>
```{r input01, echo=FALSE}
selectInput("countryInput", "REGIÓN",
choices = c("NACIONAL","XV ARICA Y PARINACOTA","I TARAPACÁ","II ANTOFAGASTA",
"III ATACAMA","IV COQUIMBO","V VALPARAÍSO","XIII METROPOLITANA",
"VI O´HIGGINS","VII MAULE","XVI ÑUBLE","VIII BÍO BÍO",
"IX ARAUCANÍA","XIV LOS RÍOS","X LOS LAGOS","XI AYSÉN","XII MAGALLANES"))
```
```{r input02, echo=FALSE}
dateRangeInput("dateInput", "TRIMESTRES",
language = "es",
format = "yyyy/mm/dd",
min = as.Date("2018-01-01"),
max = as.Date("2020-07-01"),
start = as.Date("2019-07-01"),
end = as.Date("2020-07-01"),
separator = "hasta")
```
Página
====================================
Row
-----------------------------
###
Problem photo
This is my first post on the forum, so any help is appreciated and I apologize in case I forgot to add information.
Use imageOutput to control the height of the div containing the image:
output[["image"]] <- renderImage({
filename <- paste0("images/",input$countryInput,".png")
list(src = filename, height = 100)
})
imageOutput("image", height = "100px")
I've already tried using the print function:
print(dfSummary(df), method = "render")
And also all the solutions here but they don't seem to work with html_document as the output file type of the R Markdown.
Olá, Inês
The answer is in provided link. You just need to add max.tbl.height argument and specify height in pixels:
print(dfSummary(df),
max.tbl.height = 250,
method = "render")
Here goes an reproducible example (see # comments for tips & tricks):
---
title: "Title"
author: "Author"
date: "26/05/2020"
output:
html_document:
toc: TRUE
toc_float: TRUE
---
```{r setup, include = FALSE}
library(knitr)
library(summarytools)
knitr::opts_chunk$set(results = "asis")
```
### Adding a scrollbar to dfSummary
```{r summarytools-css, echo = FALSE}
# with summarytools’ CSS we can cancel Bootstrap’s CSS (both are included by default)
# without it odd layout are expected, especially with dfSummary()
st_css(bootstrap = FALSE)
```
```{r dfSummary, echo = FALSE}
print(dfSummary(tobacco,
style = "grid", # set style to “grid”
valid.col = FALSE, # drop Valid column if redundant
graph.magnif = 0.82), # zoom factor (max = 1) for bar plots and histograms
headings = FALSE,
footnote = NA,
# use maximum table (specified) height (in pixels) and wrap the results in a scrollable window
max.tbl.height = 300,
method = "render")
```
If you have interest, check out Dominic's vignette - "Recommendations for Using summarytools With Rmarkdown".
May I suggest using the package "DT", if you absolutely need dfSummary I can try again, but would need the minimal amount of code for replicate your example. DT has search functionality along with letting the user control how many rows they see when viewing the data.
---
title: "DF summary"
author: "stackoverflow"
date: "5/24/2020"
output: html_document
---
```{r}
library(DT)
datatable(head(mtcars, 30), options = list(
order = list(list(2, 'asc'), list(4, 'desc'))
))
```
Is it possible to move the caption above my figure when knitting to HTML in RMarkdown? It seems that it is possible in PDF, ie when knitting to PDF, but I can't figure out how to replicate this for HTML. I am using bookdown to number figures.
When I run something like this:
```{r fig.cap= "caption"}
df <- data.frame(letter = letters[1:5], value = 1)
ggplot(df, aes(as(factor(1), value, fill = letters))) +
geom_bar(stat = "identity")
```
the caption is displayed at the bottom of the figure, but I would like to display it above the figure.
For HTML output, you may set the chunk option fig.topcaption = TRUE to place captions above figures. Below is a minimal example (it works for both html_document and bookdown's HTML output formats):
---
title: "Reprex"
output:
html_document: null
bookdown::html_document2: null
---
```{r, fig.cap='A caption.', fig.topcaption=TRUE}
plot(cars)
```
You can do that, but if you set echo = TRUE, the caption will appear above the code...
---
title: "Untitled"
author: "Stéphane Laurent"
date: "29 février 2020"
output: html_document
---
```{r setup, include=FALSE}
knitr::knit_hooks$set(htmlcap = function(before, options, envir) {
if(before) {
paste('<p class="caption">', options$htmlcap, "</p>",sep="")
}
})
```
```{r, echo = FALSE, htmlcap="Hello Dolly"}
library(ggplot2)
ggplot(diamonds,aes(price,carat)) + geom_point()
```
This is not a successful answer, but code output shows that the choice of a bookdown format, that would otherwise number the figure, is suppressed by inclusion of the solution proposed by Stéphane, or, as below, solution from the link suggested by dyrland.
---
title: "Untitled"
author: "Internet"
date: "29 février 2020"
output:
bookdown::html_document2
---
```{r setup2}
#https://stackoverflow.com/a/26743812/4927395
library(knitr)
knit_hooks$set(plot = function(x, options) {
paste('<figure><figcaption>', options$fig.cap, '</figcaption><img src="',
opts_knit$get('base.url'), paste(x, collapse = '.'),
'"></figure>',
sep = '')
}) #comment out to restore numbering
library(ggplot2)
```
```{r, echo = TRUE, fig.cap="Hello Dolly"}
ggplot(diamonds,aes(price,carat)) + geom_point()
```
Can a solution include both the numbering and the caption at the top?
N.B Author of the original question did mention bookdown, but did not provide a full working example to demonstrate this. Happy to edit original question if other think that would be more useful.
EDIT
Yihui has shown in his answer that there is an easy option with fig.topcaption=TRUE - Thanks! Unfortunately that caption, though it retains correct numbering, is still pushed to the bottom (in the case of plotly figures). Example below:
---
title: "Untitled"
author: "Internet"
date: "29 février 2020"
output:
bookdown::html_document2
---
```{r setup, message=FALSE, echo=FALSE}
library(knitr)
library(ggplot2)
library(plotly)
```
Here is a ggplot object with caption at the top as desired.
```{r, fig.cap="Hello ggplot", fig.topcaption=TRUE, message=FALSE, echo=FALSE}
ggplot(diamonds,aes(price,carat)) + geom_point()
```
Here is the previous ggplot converted to a plotly object with caption reverting to the bottom.
```{r, fig.cap="Hello plotly", fig.topcaption=TRUE, message=FALSE, echo=FALSE}
my_ggplot <- ggplot(diamonds,aes(price,carat)) + geom_point()
ggplotly(my_ggplot)
```
Caption reverts to bottom even if plotly object is not created from ggplot object
```{r, fig.cap="Hello plotly2", fig.topcaption=TRUE, message=FALSE, echo=FALSE}
plot_ly(
x=c(1,2,3),
y=c(5,6,7),
type='scatter',
mode='lines')
```
EDIT 2
Plotly caption location issue solved with css here
Hardcoding a function is function is never my preferred option, but it works (Create another function for Tables.) (Source code here: R Markdown HTML Number Figures)
Now, to figure out how to reference these...
---
title: "Untitled"
author: "Internet"
date: "29 fevrier 2020"
output:
bookdown::html_document2
---
```{r setup2}
#https://stackoverflow.com/a/26743812/4927395
library(knitr)
library(ggplot2)
capFigNo <- 1
capFig <- function(x){
x <- paste0("Figure ",capFigNo,": ",x)
capFigNo <<- capFigNo + 1
x
}
knit_hooks$set(plot = function(x, options) {
paste('<figure><figcaption>',
options$fig.cap,
'</figcaption><img src="',
opts_knit$get('base.url'),
paste(x, collapse = '.'),
'"></figure>',
sep = '')
}) #comment out to restore numbering
```
```{r echo = TRUE, fig.cap=capFig("Hello Dolly")}
#the trick is to wrap your caption in your number prefixing function.
ggplot(diamonds,aes(price,carat)) + geom_point()
```
```{r echo = TRUE, fig.cap=capFig("Hello Dolly2")}
ggplot(diamonds,aes(price,carat)) + geom_point()
```