0

I am trying to find an easy way to include images in knit pdfs and html. It would be nice to write one set of instructions that are easily converted to either format. I read here:

Insert picture/table in R Markdown

that the best way to include graphics is with a code chunk. It seems like it should work both for knitting pdfs as well as html. However, it only includes the graphics in pdf whereas it is missing from the html. The following is an MWE.

---
title: "a title"
author: "a"
date: "March 3, 2016"

# header-includes: \usepackage{graphicx}
# output:
#   pdf_document:
#     toc: true
#     toc_depth: 3                    # default = 3
#     number_sections: true           # add section numbering to headers

output:
  html_document:                  
    toc: true                     
    toc_float:                    
      collapsed: false              
      toc_depth: 4                  
    number_sections: true         
    highlight: tango              
    theme: simplex
---

### Support Vector Machines (SVMs)

SVM optimal hyperplane:

```{r pressure, echo=FALSE, fig.cap="A caption", out.width = '100%', fig.align = 'center'}
# https://bookdown.org/yihui/bookdown/figures.html
knitr::include_graphics("./All_Figures/Chapter8/8.3.pdf")
```
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
user2205916
  • 3,196
  • 11
  • 54
  • 82

1 Answers1

3

Short answer: your image is a PDF File


It always helps to include a minimal, reproducible example. As the path to your image was not provided, I have created one here which creates a local file cars.pdf:

---
title: Images in Knitr
output: 
  html_document: default
  pdf_document: default
---

```{r}
# Create an example plot
pdf("cars.pdf")
plot(cars)
dev.off()

```

```{r}
knitr::include_graphics("cars.pdf")
```

Comparing the HTML and PDF, we can see the behaviour you report, whereby the images aren't shown in the HTML:

enter image description here

The problem stems from the image being saved as a PDF. From my understanding, HTML has no native way to display such images. It therefore doesn't display the image within the output.

As a workaround, you would be better to save the graphic as a PNG or JPEG.

Michael Harper
  • 14,721
  • 2
  • 60
  • 84