Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Markdown: How do I make text float around figures?

I made a flowchart with R which I included in my R Markdown file.

How it looks like right now: enter image description here

The code:

```{r flowchart-data, echo = FALSE, message = FALSE, fig.cap = "Ablauf der Datenverarbeitung", fig.align = "right",  fig.width = 7, fig.height = 6, out.extra = 'trim = {0 1.1cm 0 0}, clip', out.width=".7\\textwidth"}
library(grid)
library(Gmisc)

# grid.newpage()
# set some parameters to use repeatedly
leftx <- .2
midx <- .5
rightx <- .8

myBoxGrob <- function(text, ...) {
  boxGrob(label = text, bjust = "top", box_gp = gpar(fill = "lightgrey"), ...)
}

# create boxes
(Pharmazie <- myBoxGrob("Verbrauchsdaten von der\n Spitalpharmazie  (Excel-Tabelle)", x=leftx, y=1, width = 0.36))
(Finanzen <- myBoxGrob("Belegzahlen vom Ressort\n Finanzen (Excel-Tabelle)", x=rightx, y=1, width = 0.36))
(A <- myBoxGrob("Import der Daten aus Excel ins\n Microsoft Access (Datenbanksoftware)", x=midx, y=0.83, width = 0.45))
(B <- myBoxGrob("Zusammenführen der Informationen\n und erstellen neuer, berechneter Tabellen", x=midx, y=.66, width = 0.45))
(C <- myBoxGrob("Export der neu erstellten Tabellen\n in Form von Excel-Tabellen", x=midx, y=.49, width = 0.45))
(D <- myBoxGrob("Import der neuen Tabellen in R", x=midx, y=.32,  width = 0.45))
(E <- myBoxGrob("Berechnung und grafische Darstellung\n der Grafiken und Tabellen", x=midx, y=.19, width = 0.45))


connectGrob(Pharmazie, A, "L")
connectGrob(Finanzen, A, "L")
connectGrob(A, B, "N")
connectGrob(B, C, "N")
connectGrob(C, D, "N")
connectGrob(D, E, "N")
```

What I would like:

  1. I want the text to use the space on the left of the figure.
  2. I would like for the figure caption to align with the center of the figure. Right now the caption is in the middle of the page, ignoring if the figure is centered, right or left aligned.

How can I achieve those things?

EDIT 1: I want to knit to pdf.

EDIT 2: As requested in the comments, how my page looks now: How my page looks now

like image 562
Hurlikus Avatar asked Jan 08 '19 22:01

Hurlikus


People also ask

How do you Bolden text in R Markdown?

To make the formatted text into bold type, you can simply use a pair of ** around the marked up text with no space. For example **bold** in the . Rmd file generates bold in the output document.

What does ## do in R Markdown?

headers - Place one or more hashtags at the start of a line that will be a header (or sub-header). For example, # Say Hello to markdown . A single hashtag creates a first level header. Two hashtags, ## , creates a second level header, and so on.

How do you add a subscript in R Markdown?

Subscripts and Superscripts To indicate a subscript, use the underscore _ character. To indicate a superscript, use a single caret character ^ . Note: this can be confusing, because the R Markdown language delimits superscripts with two carets.

How do you add a vertical space in R Markdown?

To create vertical space (Markdown to PDF), I use &nbsp; This command works like \vspace{12pt} for latex. Fantastic!

How do I prevent floating figures in R Markdown?

The option value !H will prevent any floating within the document. We can set the default behavior for the document so that all chunks have this setting by including the following line in the first code chunk in your R Markdown document: In general, we do not recommend that users force LaTeX to stop floating figures.

How do I include an image in R Markdown?

Using the include_graphics function for adding images and figures We include external images in our R markdown documents using the include_graphics function from the knitr package. Images can also be included using either raw HTML with img tags ( <img src = "" />) or using markdown directly ( ! [image] (imagepath) ).

What is the default fig width and height in R Markdown?

Use fig.width and fig.height for R-generated figures only Default is fig.width = 7 and fig.height = 5 (in inches, though actual width will depend on screen resolution). Remember that these settings will default to rmarkdown values, not knitr values. How images and figures in the HTML document are affected by using fig.width and fig.height:

Can Pandoc convert Markdown code that contains an image?

For example, Pandoc will convert the following Markdown code that contains an image ! [This is a figure.] (images/cool.jpg) The figure environment is a floating environment.


1 Answers

There is a chunk option called fig.env with which one can switch from the figure to the marginfigure environment. Unfortunetly, the list of possible environments does not include wrapfigure. Therefore we will alter the plot chunk:

defOut <- knitr::knit_hooks$get("plot")  # save the default plot hook 
knitr::knit_hooks$set(plot = function(x, options) {  # set new plot hook ...
  x <- defOut(x, options)  # first apply the default hook
  if(!is.null(options$wrapfigure)) {  # then, if option wrapfigure is given ...
    # create the new opening string for the wrapfigure environment ...
    wf <- sprintf("\\begin{wrapfigure}{%s}{%g\\textwidth}", options$wrapfigure[[1]], options$wrapfigure[[2]])
    x  <- gsub("\\begin{figure}", wf, x, fixed = T)  # and replace the default one with it.
    x  <- gsub("{figure}", "{wrapfigure}", x, fixed = T)  # also replace the environment ending
  }
  return(x)
})

The comments should clarify what we are actually doing here. Notice, that the expected value of wrapfigure is a list of two elements. The first one tells LaTeX to move the figure to either side of the page. The second element tells LaTeX the width of the wrapped figure. To move a figure with a width of 0.7\\textwidth to the right you set wrapfigure = list("R", 0.7) (as you might have guessed, L moves it to the left). All we have to do now is to include the wrapfig package in the YAML and set this chunk option. Here is a reproducible example:

---
header-includes:
  - \usepackage{wrapfig}
  - \usepackage{lipsum}
output: 
  pdf_document:
    keep_tex: true
---

```{r, include = F}
defOut <- knitr::knit_hooks$get("plot")  # save the default plot hook 
knitr::knit_hooks$set(plot = function(x, options) {  # set new plot hook ...
  x <- defOut(x, options)  # first apply the default hook
  if(!is.null(options$wrapfigure)) {  # then, if option wrapfigure is given ...
    # create the new opening string for the wrapfigure environment ...
    wf <- sprintf("\\begin{wrapfigure}{%s}{%g\\textwidth}", options$wrapfigure[[1]], options$wrapfigure[[2]])
    x  <- gsub("\\begin{figure}", wf, x, fixed = T)  # and replace the default one with it.
    x  <- gsub("{figure}", "{wrapfigure}", x, fixed = T)  # also replace the environment ending
  }
  return(x)
})
```


Vivamus vehicula leo a justo. Quisque nec augue. Morbi mauris wisi, aliquet vitae, dignissim eget, sollicitudin molestie, ligula. In dictum enim sit amet risus. Curabitur vitae velit eu diam rhoncus hendrerit. Vivamus ut elit. Praesent mattis ipsum quis turpis. Curabitur rhoncus neque eu dui. Etiam vitae magna. Nam ullamcorper. Praesent interdum bibendum magna. Quisque auctor aliquam dolor. Morbi eu lorem et est porttitor fermentum. Nunc egestas arcu at tortor varius viverra. Fusce eu nulla ut nulla interdum consectetuer. Vestibulum gravida. 

```{r echo = F, warning = F, message = F, fig.width=7, fig.height = 6, out.width = ".7\\textwidth", fig.cap = "My Flowchart", fig.align="right", wrapfigure = list("R", .7)}
plot(mpg ~ hp, data = mtcars)
```

Morbi mattis libero sed est. Vivamus vehicula leo a justo. Quisque nec augue. Morbi mauris wisi, aliquet vitae, dignissim eget, sollicitudin molestie, ligula. In dictum enim sit amet risus. Curabitur vitae velit eu diam rhoncus hendrerit. Vivamus ut elit. Praesent mattis ipsum quis turpis. Curabitur rhoncus neque eu dui. Etiam vitae magna. Nam ullamcorper. Praesent interdum bibendum magna. Quisque auctor aliquam dolor. Morbi eu lorem et est porttitor fermentum. Nunc egestas arcu at tortor varius viverra. Fusce eu nulla ut nulla interdum consectetuer. Vestibulum gravida. Morbi mattis libero sed est.

Notice, that this solution most probably only works with a chunk creating a single plot. It should be possible to extent that to a chunk containing several figures.

enter image description here

like image 53
Martin Schmelzer Avatar answered Sep 22 '22 13:09

Martin Schmelzer