R Markdown Insert Image: The Way of Pictures

R Markdown offers a robust solution for integrating text, code, and figures in a single document. This dynamic report generation tool in R is widely used for creating documents that combine code execution with narrative text and graphics, making it a valuable resource for data analysis and documentation.

It supports various output formats like PDF, HTML, and Word, allowing for broad dissemination across different platforms. By incorporating markdown syntax, users can easily control the layout and format of their output, providing clarity and precision in their documentation.

A laptop open on a desk with a code editor displayed, surrounded by a notebook, pen, and a cup of coffee

Inserting images in R Markdown can significantly enhance the visual appeal and effectiveness of the documentation. Images can convey complex ideas quickly, serve as evidence for data analyses, or simply make documents more engaging.

To insert an image, users can leverage the markdown syntax specifically designed for image embedding. This syntax is straightforward and easy to apply, involving a simple line of text that references the location of the image file relative to the R Markdown file. The syntax also allows for additional attributes such as image size, alignment, and alternative text.

In more complex scenarios, users might resort to R chunks, which are code blocks within the R Markdown document. These chunks can not only process R code but can also be used for generating images dynamically during document rendering.

This integration ensures that the most current outputs are incorporated into the final document, making it an essential tool for reproducible research and dynamic report generation. R chunks offer a high degree of flexibility, enabling users to programmatically control various aspects of image creation and manipulation.

Preparing the Environment

A desk with a laptop, notebook, and pen. A plant in a pot and a cup of coffee on the side. Bright natural light coming in through the window

Before integrating images into an R Markdown document, one must ensure that the environment is properly set up. This process involves configuring the working directory, understanding the specific R Markdown syntax required, and installing any necessary packages.

Setting Up the Working Directory

The working directory acts as a foundational context in which R Markdown operates. It should contain all the files related to the document, including images.

To set or verify the working directory in R, one can use the getwd() function to check the current directory, and setwd() to change it.

# To check the current working directory
getwd()

# To set the working directory to a specific folder
setwd("/path/to/your/directory")

Understanding R Markdown Syntax

R Markdown allows for literate programming by combining markdown text, code chunks, and its own syntax. A basic understanding of markdown is essential, particularly for image insertion using the following syntax: ![Alt text](/path/to/image.png).

YAML (Yet Another Markup Language) headers are also crucial, as they contain metadata, format settings, and other options like the output format.

# Markdown syntax for image insertion
![This is an image](/images/image.jpg)

Installing Required Packages

Some packages need to be present for the efficient operation of R Markdown. The rmarkdown package itself is necessary to knit documents, enabling a mixture of text and R code chunks to be compiled into a cohesive report.

The knitr package is also fundamental, as it processes the code chunks and controls how results are included in the final output.

These packages can be installed using the install.packages function in R.

# To install the rmarkdown package
install.packages("rmarkdown")

# To install the knitr package
install.packages("knitr")

Inserting Images into R Markdown

A hand clicks "Insert Image" in R Markdown. A file dialog opens, allowing selection of an image to insert

Inserting images into an R Markdown document enhances the visual appeal and supports the accompanying text. R Markdown facilitates image inclusion through simple syntax and functions, catering to diverse formatting needs.

Basic Image Insertion

To insert an image in R Markdown, one utilizes the Markdown syntax ![Alt Text](Path_to_image) or uses an R code chunk with the include_graphics() function from the knitr package.

The alt text serves as a description of the figure’s content, which is essential for accessibility.

![Alt Text](Path_to_image)
knitr::include_graphics("Path_to_image")

Image Size and Scaling

Controlling the size and scaling of an image is crucial for layout and readability. R Markdown allows users to set the width and height directly within the image’s Markdown syntax using out.width and out.height options in a code chunk.

![Alt Text](Path_to_image){width=50%}
knitr::include_graphics("Path_to_image")

Image Alignment and Text Wrapping

Aligning images and wrapping text around them can be achieved using HTML tags for direct Markdown insertion or by tweaking chunk options. These customizations dictate how figures are positioned relative to the text.

<img src="Path_to_image" style="display: block; margin: auto;" />
knitr::include_graphics("Path_to_image")

Image Captions and Alt Text

Image captions provide context and are inserted directly under an image using Markdown or by specifying the fig.cap option in a code chunk. Alt text, important for screen readers, is added within the square brackets in Markdown or as the fig.alt option.

![Alt Text](Path_to_image)
*Figure 1: Caption*
knitr::include_graphics("Path_to_image")

Advanced Image Features

A colorful palette of digital image editing tools displayed on a computer screen, with a stylus and tablet nearby for creative input

R Markdown offers several methods for enhancing the presentation of images within documents. These advanced techniques allow users to control image display through external references, incorporate custom HTML and CSS, and dynamically generate images within their markdown files.

External Image References

Users have the ability to reference images hosted elsewhere on the web, rather than storing them directly within their project. This is particularly useful for minimizing file sizes and leveraging hosted media.

They can use the following syntax to display an external image:

![Alt text](URL_to_image "Optional title")
  • Alt text – describes the image if it cannot be displayed.
  • URL_to_image – is the web address where the image is hosted.
  • Optional title – appears as a tooltip on hover (depends on the viewer’s settings).

Embedding HTML and CSS

For greater control over image presentation, HTML and CSS can be directly embedded into R Markdown documents.

This method allows for the customization of image size, borders, and positioning.

<img src="URL_to_image" alt="Alt text" style="width:100px;height:100px;">

By using HTML code for images, users can implement CSS styling directly within the <img> tag or by referencing external CSS files. Pandoc converts the HTML and CSS to the output format specified when the markdown file is rendered.

Dynamic Image Generation

R Markdown integrates seamlessly with Knitr, enabling the dynamic generation of images through R code.

Graphs and plots produced by R code chunks are automatically embedded within the document in real-time.

plot(pressure)
  • {r pressure} – This is a chunk header, with pressure serving as a label for the chunk.
  • echo=FALSE – Ensures that the R code is not displayed in the final document, only the resulting image.
  • fig.cap="A plot of the pressure dataset." – Provides a caption for the generated graph.

Finalizing and Exporting the Document

A computer screen displaying the R markdown interface with an "insert image" button highlighted, ready for finalizing and exporting the document

When finalizing an R Markdown document, users should ensure styles are consistent, navigation is seamless, and the output format meets their needs.

Exporting effectively requires an understanding of the different capabilities of R Markdown and associated tools like Pandoc, Latex, and Knit.

Adjusting Document Styles

Users can customize the appearance of their final document using the YAML header or in-line Markdown code to control the styling of PDF, Word, or HTML documents.

This includes setting fonts, margins, and spacing. For PDF outputs, users may also incorporate Latex commands for advanced styling.

  • Font Styles: Adjust using YAML (e.g., mainfont, sansfont for PDF with Latex).
  • Margins: Define in YAML (e.g., geometry for Latex-styled PDFs).
  • Spacing: Inline markdown can handle line-spacing (e.g., using <br> for HTML).

Table of Contents and Document Navigation

Adding a table of contents (TOC) enhances the document navigation. It can be easily included via the YAML header.

Users can determine the depth of the TOC and whether it appears as a sidebar in HTML documents or at the beginning in Word and PDF formats.

  • TOC Depth: Set using toc_depth in YAML.
  • Sidebar TOC: For HTML outputs, use toc_float.

Compiling to Different Output Formats

R Markdown supports various output formats such as HTML, Word, or PDF.

The Knit button in RStudio invokes the Pandoc utility to convert markdown code into the desired document type.

  • Output Formats: Choose from HTML, Word, PDF, among others.
  • Commands: Use rmarkdown::render() for programmatic document knitting.

The choice of output format determines the availability of certain features.

For instance, advanced Latex customization is exclusive to PDF outputs, while interactive components are primarily for HTML documents.

author avatar
Dean Portfolio Manager
Dean Graham is the founder and editor of 9to5flow.com, a website focused on productivity and work-life balance. Dean's career is in commercial banking where he has held various roles where he has encountered the everyday challenges faced by professionals. In 2022, Dean created 9to5flow.com to share practical advice and resources aimed at helping people achieve their goals while maintaining well-being. He hopes the site can provide readers with relatable insights and straightforward tips, as researching these topics has been a valuable exercise for his own career. Outside of the digital space, Dean enjoys the outdoors, college football, live music and being with his family. He finds happiness in continuous learning and helping others find a balanced approach to work and life.