ikashnitsky
ikashnitsky

Reputation: 3111

How to refer a figure as a table?

I know, this is probably not the wisest idea anyways, but I need to insert a table as figure/screenshot (.png) but refer to it as a table in the caption. Is it possible?

My gaol is basically the same as here with the only difference that I am working in RStudio with rmarkdown, knitr and bookdown. Ideally, the solution should work for both PDF and HTML output (though, PDF is more important for me now).

Upvotes: 3

Views: 632

Answers (2)

Ben S.
Ben S.

Reputation: 3545

I had this same issue and didn't see this question at the time. If you're OK with still having having the horizontal lines at top and bottom, what you can do is make a table that contains nothing but an image of the table you want to display, like this:

```{r echo=F, warning=F}
temp.df <- data.frame(image="![](mytable.png)")
temp.mat <- as.matrix(temp.df)
colnames(temp.mat) <- NULL
knitr::kable(temp.mat, caption="This is my caption")

```

Still a hack but a little less work than the currently accepted answer.

Upvotes: 1

eipi10
eipi10

Reputation: 93791

As a hack, you could create a dummy table that's printed with a miniscule fontsize, just to get the table caption, and then in the same chunk add the actual table image that you want printed. For example:

---
title: Document Title
output: 
  bookdown::pdf_document2:
    toc: no
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(xtable)
options(xtable.include.rownames=FALSE, xtable.comment=FALSE)

# Dummy table function
dt = function(label, caption=NULL) {
  print(xtable(setNames(data.frame(x=numeric()), " "),
               caption=caption,
               label=paste0("tab:", label)), 
        hline.after=NULL,
        booktabs=FALSE,
        size="\\fontsize{0.1pt}{0.1pt}\\selectfont")
}
```

Lorem Ipsum is simply dummy text of the printing and typesetting industry. As you can see, Table \@ref(tab:lab1) shows something. It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. 

```{r, lab1, results="asis", fig.align="center", out.width="6in"}
dt("lab1", "This is table 1")
include_graphics("tab1.png")
```

Now for some more text and then here is Table \@ref(tab:lab2).

```{r, lab2, results="asis", fig.align="center", out.width="4.5in"}
dt("lab2", "This is table 2")
include_graphics("tab2.png")
```

Below, you can see what the output document looks like. As you can see, there some extra space between the caption and the table, due to the small amount of vertical space taken up by the invisible dummy table. Hopefully, some with better knowledge of latex can suggest how to get rid of that space.


enter image description here

Upvotes: 1

Related Questions