Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

word_document2 "multiple labels on one line" error #538

Closed
mdlincoln opened this issue Feb 25, 2018 · 16 comments
Closed

word_document2 "multiple labels on one line" error #538

mdlincoln opened this issue Feb 25, 2018 · 16 comments
Labels
bug an unexpected problem or unintended behavior
Milestone

Comments

@mdlincoln
Copy link
Contributor

I'm encountering an error when trying to render a word_document2 with more than one figure in a single chunk. Both #249 and #483 suggested this issue had been fixed, and should just result in a warning, but I'm getting it with the latest version of bookdown right now.

Sample document:

```{r figs, fig.cap = "Figure caption.", fig.show = "hold"}
plot(iris)
plot(mtcars)
```

Building with bookdown::pdf_document2 works fine. However, I get the following error if trying to use word_document2:

> bookdown::render_book("figures.Rmd", "bookdown::word_document2")


processing file: _main.Rmd
  |......................                                           |  33%
  ordinary text without R code

  |...........................................                      |  67%
label: figs (with options) 
List of 2
 $ fig.cap : chr "Figure caption."
 $ fig.show: chr "hold"

  |.................................................................| 100%
  ordinary text without R code


output file: _main.knit.md

Error in parse_fig_labels(x, global) : 
  There are multiple labels on one line: (#fig:figs), (#fig:figs)
In addition: Warning messages:
1: In (knit_hooks$get("plot"))(file, reduce_plot_opts(options)) :
  The chunk option fig.show="hold" is not supported for Word output
2: In (knit_hooks$get("plot"))(file, reduce_plot_opts(options)) :
 
 Show Traceback
 
 Rerun with Debug
 Error in parse_fig_labels(x, global) : 
  There are multiple labels on one line: (#fig:figs), (#fig:figs) Please delete _main.Rmd after you finish debugging the error.

While I expected the warning about fig.show="hold" for Word, I did not expect the error.

Session info -----------------------------------------------------------------------------------------------------------------------------
 setting  value                       
 version  R version 3.4.2 (2017-09-28)
 system   x86_64, darwin15.6.0        
 ui       RStudio (1.1.383)           
 language (EN)                        
 collate  en_US.UTF-8                 
 tz       America/Los_Angeles         
 date     2018-02-25                  

Packages ---------------------------------------------------------------------------------------------------------------------------------
 package   * version date       source                            
 backports   1.1.2   2017-12-13 CRAN (R 3.4.3)                    
 base64enc   0.1-3   2015-07-28 CRAN (R 3.4.0)                    
 bookdown    0.7.1   2018-02-25 Github (rstudio/bookdown@06bd619) 
 digest      0.6.15  2018-01-28 CRAN (R 3.4.3)                    
 evaluate    0.10.1  2017-06-24 CRAN (R 3.4.1)                    
 glue        1.2.0   2017-10-29 cran (@1.2.0)                     
 graphics  * 3.4.2   2017-10-04 local                             
 grDevices * 3.4.2   2017-10-04 local                             
 highr       0.6     2016-05-09 CRAN (R 3.4.0)                    
 htmltools   0.3.6   2017-04-28 CRAN (R 3.4.0)                    
 jsonlite    1.5     2017-06-01 CRAN (R 3.4.0)                    
 knitr     * 1.20    2018-02-20 CRAN (R 3.4.3)                    
 magrittr    1.5     2014-11-22 CRAN (R 3.4.0)                    
 markdown    0.8     2017-04-20 CRAN (R 3.4.0)                    
 methods   * 3.4.2   2017-10-04 local                             
 mime        0.5     2016-07-07 CRAN (R 3.4.0)                    
 Rcpp        0.12.15 2018-01-20 CRAN (R 3.4.3)                    
 rmarkdown   1.8.10  2018-02-25 Github (rstudio/rmarkdown@1ccf6a0)
 rprojroot   1.3-2   2018-01-03 CRAN (R 3.4.2)                    
 stats     * 3.4.2   2017-10-04 local                             
 stringi     1.1.6   2017-11-17 CRAN (R 3.4.2)                    
 stringr     1.3.0   2018-02-19 CRAN (R 3.4.3)                    
 tinytex     0.3     2018-01-22 CRAN (R 3.4.3)                    
 tools       3.4.2   2017-10-04 local                             
 utils     * 3.4.2   2017-10-04 local                             
 xfun        0.1     2018-01-22 CRAN (R 3.4.3)                    
 yaml        2.1.16  2017-12-12 CRAN (R 3.4.2)                    
> rmarkdown::pandoc_version()
[1] ‘2.1.1’
> system('pdflatex --version')
pdfTeX 3.14159265-2.6-1.40.18 (TeX Live 2017)
kpathsea version 6.2.3
Copyright 2017 Han The Thanh (pdfTeX) et al.
There is NO warranty.  Redistribution of this software is
covered by the terms of both the pdfTeX copyright and
the Lesser GNU General Public License.
For more information about these matters, see the file
named COPYING and the pdfTeX source.
Primary author of pdfTeX: Han The Thanh (pdfTeX) et al.
Compiled with libpng 1.6.29; using libpng 1.6.29
Compiled with zlib 1.2.11; using zlib 1.2.11
Compiled with xpdf version 3.04
@mdlincoln mdlincoln changed the title word_document2 "multipel labels on one line" error word_document2 "multiple labels on one line" error Feb 25, 2018
@yihui
Copy link
Member

yihui commented Feb 26, 2018

Looks like a regression, but I don't have time to fix it perhaps until 6 months later. If anyone wants to help, a pull request is welcome!

@Syntanx
Copy link

Syntanx commented Jul 26, 2018

I'm seeing the same thing with include_graphics() and word_document2. No problem with html_document2 or pdf_document2. Hope you get a chance to get around to it soon! And thank you for the great package @yihui!

Code:

```{r OriginalxGrowthxCurvesxMe, fig.cap="My Growth Curves"}
include_graphics(c("Images/WT_Growth_Curve.png","Images/WT_Growth_Curve_log.png"))
```

Result:

Error in parse_fig_labels(x, global) : 
  There are multiple labels on one line: (#fig:OriginalxGrowthxCurvesxMe), (#fig:OriginalxGrowthxCurvesxMe)
Calls: <Anonymous> ... <Anonymous> -> process_markdown -> parse_fig_labels
Execution halted

@yihui yihui added this to the v0.8 milestone Jul 26, 2018
@yihui
Copy link
Member

yihui commented Jul 26, 2018

@Syntanx I have scheduled it in the next release of bookdown, which does not have an ETA yet (perhaps in one month or two). Before I have time to look into it, I guess you have to use two separate include_graphics() calls in two separate code chunks.

@Syntanx
Copy link

Syntanx commented Jul 26, 2018

I guess another option is to pre-combine your images into one figure and render just that figure like shown here: https://sebastiansauer.github.io/two-plots-rmd/

comb2pngs <- function(imgs, bottom_text = NULL){
  img1 <-  grid::rasterGrob(as.raster(readPNG(imgs[1])),
                            interpolate = FALSE)
  img2 <-  grid::rasterGrob(as.raster(readPNG(imgs[2])),
                            interpolate = FALSE)
  grid.arrange(img1, img2, ncol = 2, bottom = bottom_text)
}

@raiphilibert
Copy link

raiphilibert commented Aug 3, 2018

@yihui I am also seeing the same problem even though I am calling my plots in separate code chunks. I was trying to include them for a loop and child document. Worked with pdf_document2 but not with word_document2

Main rmarkdnown document has the following code:

---
title: "Minimal"
output: 
  bookdown::word_document2:
    fig_caption: yes
  bookdown::pdf_document2:
    fig_caption: yes
    keep_md: yes
---
library(knitr)
library(ggplot2)
knitr::opts_chunk$set(echo = TRUE)
out <- NULL
for (i in 1:5){
env=new.env()
chunkLabel = paste0('minGraph',as.character(i))
out = c(out, knit_expand('child.Rmd',envir = env))
}
`r paste(knit(text = out), collapse = '\n')`

The child document has the following example:


```{r {{chunkLabel}}, echo=FALSE, fig.cap=figcap,fig.align='left',eval=TRUE,results="asis",eval.after=TRUE}

print(ggplot(mtcars) + geom_point(aes(x=mpg,y=disp,fill=gear)))
figcap="test"
cat(sprintf('Here is a reference to the plot below \\@ref(fig:%s). This plot is in the child document',"{{chunkLabel}}"))
cat("\n")

@hokkwan
Copy link

hokkwan commented Aug 11, 2018

I was able to workaround this issue by adding a newline between the two plots as follows:

```{r figstest, fig.cap = "Figure caption.", echo = FALSE}
plot(iris)
cat("\n\n")
plot(mtcars)
```

@CLRafaelR
Copy link

CLRafaelR commented Aug 12, 2018

The same problem @mdlincoln pointed out occurred, when I tried to insert different images in one chunk or in one include_graphics(), though my images were produced from GIMP, not from any R related package (like ggplot2). Although I managed to put them into .docx file by applying multiple chunks with include_graphics() as @yihui suggested, I would like to insert some pictures in one chunk when I produce .docx file in the same way as I produce .pdf file.

The following chunk runs well when the output option in YAML is bookdown::pdf_document2 but gives me an error when the output is bookdown::word_document2.

 {r scratch, out.width='0.3\\textwidth', fig.ncol = 3,  fig.cap='Main caption', fig.subcap = c("subcap1","subcap2", "subcap3"), fig.align='center', fig.show = "hold"}
  knitr::include_graphics(c("stimuli/20180708-targets/AgentL/scratch-ha-L.PNG", "stimuli/20180708-targets/AgentL/scratch-ah-L.PNG", "stimuli/20180708-targets/AgentL/scratch-aa-L.PNG"))

This is my YAML header for bookdown::word_document2:

---
title: "My title"
author: "My name"
date: "`r format(Sys.time(), '%Y年 %B %d日')`"
output: 
  bookdown::word_document2:
    toc: yes
    reference_docx: word-styles-reference-01.docx
    fig_caption: true
bibliography: myref.bib
always_allow_html: yes
editor_options:
  chunk_output_type: console
---

The R chunk above goes well with this YAML for bookdown::pdf_document2:

---
title: "My title"
author: "My name"
date: "`r format(Sys.time(), '%Y年 %B %d日')`"
output:
  bookdown::pdf_document2:
    latex_engine: lualatex
    keep_tex: yes
    toc: TRUE
    toc_depth: 2
    number_sections: TRUE
    fig_caption: TRUE
    dev: cairo_pdf
    extra_dependencies: subfig
    #citation_package: natbib
always_allow_html: yes
documentclass: ltjsarticle
header-includes:
   - \RequirePackage{luatexja}
   - \usepackage{graphicx}
   - \usepackage{float}
   - \DeclareGraphicsExtensions{.pdf,.PNG}
   - \usepackage{luatexja-fontspec}
   - \setmainjfont{YuMincho}[UprightFont=YuMincho-Regular,BoldFont=YuMincho-Demibold]
   - \setmainfont{TeX Gyre Termes}
   - \setsansjfont{YuGothic-Medium}[BoldFont=YuGothic-Bold]
   - \setsansfont{TeX Gyre Heros}
   - \setlength\parskip{0mm}
   - \setlength\parindent{1\Cwd}
   - \usepackage[japanese]{babel}
   - \captionsjapanese
   - \newdimen\bibindent
   - \setlength\bibindent{3\Cwd}
      #- \newenvironment{hangall}[1]{\hangindent = #1\zw\everypar{\hangindent = #1\zw}}{}
bibliography: myref20180613.bib
#biblio-style: jep.bst
editor_options:
  chunk_output_type: console

@hokkwan
Copy link

hokkwan commented Aug 12, 2018

Word output does not support fig.subcap and fig.show.

I think the following chunk should work

``` {r scratch1, out.width='0.3\\textwidth', fig.ncol = 3,  fig.cap=c("subcap1","subcap2", "subcap3"), fig.align='center'}
knitr::include_graphics("stimuli/20180708-targets/AgentL/scratch-ha-L.PNG")
knitr::include_graphics("stimuli/20180708-targets/AgentL/scratch-ah-L.PNG")
knitr::include_graphics("stimuli/20180708-targets/AgentL/scratch-aa-L.PNG")
```

Note that if echo = FALSE, then newlines need to be added in between

``` {r scratch2, out.width='0.3\\textwidth', fig.ncol = 3,  fig.cap=c("subcap1","subcap2", "subcap3"), fig.align='center', echo=FALSE}
knitr::include_graphics("stimuli/20180708-targets/AgentL/scratch-ha-L.PNG")
cat("\n\n")
knitr::include_graphics("stimuli/20180708-targets/AgentL/scratch-ah-L.PNG")
cat("\n\n")
knitr::include_graphics("stimuli/20180708-targets/AgentL/scratch-aa-L.PNG")
```

@CLRafaelR
Copy link

CLRafaelR commented Aug 13, 2018

@h-k-kan
Thank you for your helpful comment. I confirmed that both of your code chunks work successfully. However, when I add the following chunk (especially, opts_chunk$set()) in order to configure the global chunk options, I encountered the error: Error in parse_fig_labels(x, global) : There are multiple labels on one line: (#fig:scratch1), (#fig:scratch1), (#fig:scratch1).

{r echo=FALSE, cache=FALSE}
library(knitr)
opts_chunk$set(fig.path = "figure/ja-fig-win-utf8-", fig.height=5, fig.width=5, fig.align="center", echo=FALSE, warning = FALSE, message = FALSE)

Therefore, your solution is effective if the global chunk configuration is not set (or if the chunk I added above is ignored when knitting with eval = FALSE option). What should I do to make your code and opts_chunk$set() really compatible?

@CLRafaelR
Copy link

BTW, in fact, I would like to transcribe the code chunks I write in an .Rmd file for bookdown::pdf_document2 seamlessly onto other .Rmd file for word_document2. Some colleagues and professors insist on my submitting docx outputs, so that they can add their comments on the files easily. I usually give them docx version for their annotation and PDF (processed with LaTeX) for legibility's sake. Therefore, I hope that the chunks I use with pdf_document2 can be knitted straightforwardly even with word_document2, if possible.

@ChHaeni
Copy link

ChHaeni commented Aug 28, 2018

Sorry, I'm new to GitHub, knitr and bookdown, that's why I'm a bit scared with posting to this issue.
I think that I have a related issue when using bookdown::word_document2 in an .Rmd file and table labelling (e.g. with knitr::kable) in a for-loop. The code below does work correctly for bookdown::pdf_document2 but not for bookdown::word_document2:

---
output: bookdown::word_document2
# output: bookdown::pdf_document2
---

```{r, results='asis'}
library(knitr)
for(i in 1:2){
  print(
    kable(head(iris),booktabs=TRUE,caption=paste0("Table-",i))
  )
}
```

Is there a any solution or workaround to make bookdown::word_document2 label the tables continuously?

@raiphilibert
Copy link

Hello,

You can use the knit_expand function and a child markdown document. I think that the table numbering is being changed in the print function.

 ---
 output: bookdown::word_document2
  ---
```{r, results='asis'}
library(knitr)
out=NULL

for(i in 1:2){
  env=new.env()
  out = c(out,knit_expand('table_text.Rmd',envir=env))
}
 ` ``
Can write anything text here.
 \`r paste(knit(text = out), collapse = '\n\n')` #inline r code

And then in a separate rmd file called: 'table_text.Rmd', you put:

```{r, results='asis'}
kable(head(iris),booktabs=TRUE,caption=paste0("Table-",{{i}}))
`` `        

@ChHaeni
Copy link

ChHaeni commented Aug 29, 2018

Thank you! Didn't know about the knit_expand function... Though, I prefer to use its text argument instead of sourcing a seperate file. Btw., instead of inline r code, cat at the end of the code chunk (outside the for loop of course) does work as well.

@yihui yihui removed this from the v0.8 milestone Dec 3, 2018
@brooksambrose
Copy link

brooksambrose commented Jan 11, 2019

Hi @yihui!

Looks like a regression, but I don't have time to fix it perhaps until 6 months later. If anyone wants to help, a pull request is welcome!

I noticed you took this off any milestone but hoping it makes its way back on the agenda. It still would be great for dealing with our academic advisors / baby boomers / deep-in-Word luddites!

I didn't want to just beg without attempting a PR. Sadly, debugging bookdown and knitr is tough for me, but I gave it a try. I thought a solution could be to add an exception for docx in knitr:::.img.cap to write a blank caption for everything but the last figure in a chunk. To wit, add the following line:

# .img.cap = function(options, alt = FALSE) {
#   cap = options$fig.cap %n% {
#     if (is.null(pandoc_to())) sprintf('plot of chunk %s', options$label) else ''
#   }
#   if (length(cap) == 0) cap = ''
    if (pandoc_to() == 'docx' && options$fig.cur != options$fig.cur) cap = ''
#   if (is_blank(cap)) return(cap)
#   if (alt) return(escape_html(cap))
#   paste0(create_label(
#     options$fig.lp, options$label,
#     if (options$fig.num > 1L && options$fig.show == 'asis') options$fig.cur
#   ), cap)
# }

Which works for writing out each plot on the same line without throwing op's error. Only the last figure is given the caption and label reference. So markdown output was:

![(\#fig:foo-1)Test Foo](test_files/figure-docx/foo-1.png)<!-- -->![(\#fig:foo-2)Test Foo](test_files/figure-docx/foo-2.png)<!-- -->![(\#fig:foo-3)Test Foo](test_files/figure-docx/foo-3.png)

And with that new line would be:

![](test_files/figure-docx/foo-1.png)<!-- -->![](test_files/figure-docx/foo-2.png)<!-- -->![(\#fig:foo-3)Test Foo](test_files/figure-docx/foo-3.png)

Thought this would work, but it is still broken so not PR worthy. The figure title underneath is never written when setting:

output:
    bookdown::word_document2:
      fig_caption: true

Is the wrong way to hack a fix? Happy to take another stab at it if you have any advice about how you would proceed.

@yihui yihui added this to the v0.9 milestone Jan 11, 2019
@yihui yihui modified the milestones: v0.9, v0.10 Mar 7, 2019
@yihui yihui closed this as completed in b17b0fb May 10, 2019
@yihui
Copy link
Member

yihui commented May 10, 2019

Should be fixed now. Thanks for the report as well as your attempt to fix it! I also apologize for the long delay. I guess my "R package orbit" is too long now and it is hard to circle back... 😟

Please note that figure captions won't be rendered (even with the fix) unless you use @h-k-kan's cat("\n\n") trick above: #538 (comment).

@yihui yihui added the bug an unexpected problem or unintended behavior label May 10, 2019
@github-actions
Copy link

github-actions bot commented Nov 6, 2020

This old thread has been automatically locked. If you think you have found something related to this, please open a new issue by following the issue guide (https://yihui.org/issue/), and link to this old issue if necessary.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Nov 6, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug an unexpected problem or unintended behavior
Projects
None yet
Development

No branches or pull requests

8 participants