Get startedGet started for free

Images in RMarkdown files

1. Images in RMarkdown files

Good job! Now you know how to format text sections and to customize how R code is handled in your RMarkdown report. There's one very important thing we haven't touched yet though: images and figures.

2. <<<New Slide>>>

A lot of code chunks result in images, for example ggplot2 graphics like shown here. These images are embedded into the resulting HTML file, and they are responsive, meaning they change their width based on how wide the current window is.

3. Adjusting figure options in RMarkdown

But sometimes, you still need to adjust the width or the height of images, because you want to have a different aspect ratio. Without specifying figure options, the image is usually displayed with a certain, predefined aspect ratio. In this case, it's suboptimal, because the image should be taller.

4. Adjusting figure options in RMarkdown

With the R chunk option fig.height we can customize the actual size in the resulting HTML file. The unit here is inches, so we specify the image to be 6 inches tall. More often than not, setting the right dimensions is a matter of trying different values. Here, our image becomes a bit more readable, as the labels are less cluttered, but the result is still far from perfect. You are going to try to solve this problem in the exercises later on.

5. Figure options

Here are a couple of options for customizing image output. fig.height and fig.width are self-explaining. Fig.align allows you to position an image. For instance, giving it the value "center" will position the image in the center of the report. As with other R chunk options, there are many many more figure settings. Check them out in the help page of the knitr package.

6. External images in RMarkdown reports

There's one last thing I'd like to touch on in this chapter, external images. Sometimes, you want to include images in your report that are not generated with R. You can load any external image by using Markdown syntax as shown above. Image commands are very similar to links. They are started with an exclamation mark, followed by square brackets, where a caption to the image can be given. This is optional. After this, the URL to the image is placed within normal parentheses. This can be a URL pointing to a resource on the world wide web, but can also be a path to a local file.

7. Let's practice!

Let's conclude this chapter with some exercises!