【问题标题】:knitr set Latex definecolor using hooksknitr 使用钩子设置 Latex 定义颜色
【发布时间】:2020-08-10 12:11:58
【问题描述】:

TL;DR

我希望某些乳胶命令(在本例中为 \definecolor)在某些情况下发生更改,因此我想在 R 中为这些命令创建文本并在标记期间将它们写入标记文件。我还不能使用 knitr hooks 让它完美地工作。

更多细节:

我想在.rnw 文件中定义的颜色数量(和样式)各不相同,因此我避免在.rnw 文件中对\definecolor 调用进行硬编码。

看来我可以用 knitr hooks 做到这一点,而且我非常接近。但我对一些事情感到困惑。

这是一个可重现的示例。 R文件优先

library(RColorBrewer)
library(knitr)

colNames <- c("one","two","three")
txtColors <- sub("#","",brewer.pal(6, "Dark2")[1:3])

# set the knitr hook to create color definitions within the rnw file
knitr::knit_hooks$set(setColors = function(before, options, envir) {
  if (!before){
    defs <- vector("list",length(txtColors))
    for(i in 1:length(txtColors)){
      defs[[i]] <- paste0("\\definecolor{",colNames[[i]],"Color}{HTML}{",txtColors[[i]],"}")
    } 
    return(paste0("\\xglobal",unlist(defs), "\n"))
  }   
})

setwd(file.path("G:", "my", "working", "dir"))
knit2pdf("testColors_s.rnw")

这里还有一个 rnw 文件(将其命名为“testColors_s.rnw”)

\documentclass{article}
\usepackage{xcolor}
\begin{document}

<<setColorHook, setColors = TRUE>>=

@

\textcolor{oneColor}{The first color}
\textcolor{twoColor}{The second color}
\textcolor{threeColor}{The third color}

\end{document}

问题 #1。 我必须使用 \xglobal 全局设置颜色,因为(我猜)knitr 将这些调用放在 kframe 中。我可以制作一个避免 kframe 的钩子吗?还是不需要 xglobal 调用?

问题 #2。 我在运行时收到此警告:Warning message: Package xcolor Warning: Incompatible color definition on input line 57. 这是由 knitr 完成的颜色定义,而不是我。这是 tex 文件中的违规行:

\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}

如何避免此警告或阻止 knitr 创建此行?

我们将不胜感激有关执行此操作任何部分的任何提示。 提前致谢。

【问题讨论】:

    标签: r knitr


    【解决方案1】:

    这似乎是一种 hack,但我想出了一个使用文档挂钩而不是块挂钩的解决方案。这解决了这两个问题(不再需要xglobal 并且不会创建额外的definecolor)。欢迎提供更好的解决方案。

    可重现的例子,R 文件:

    library(RColorBrewer)
    library(knitr)
    
    colNames <- c("one","two","three")
    txtColors <- sub("#","",brewer.pal(6, "Dark2")[1:3])
    
    defs <- vector("list",length(txtColors))
    for(i in 1:length(txtColors)){
      defs[[i]] <- paste0("\\\\definecolor{",colNames[[i]],"Color}{HTML}{",txtColors[[i]],"}")
    } 
    
    knit_hooks$set(document = function(x) {
      sub('%CustomColorDefsHere', paste0(unlist(defs), "\n", collapse = ""), x)
    })
    
    
    setwd(file.path("G:", "my", "working", "dir"))
    knit2pdf("testColors_s.rnw")
    

    还有 rnw 文件

    \documentclass{article}
    \usepackage{xcolor}
    %CustomColorDefsHere
    
    \begin{document}
    
    \textcolor{oneColor}{The first color}
    \textcolor{twoColor}{The second color}
    \textcolor{threeColor}{The third color}
    
    \end{document}
    

    我希望这对某人有用...

    【讨论】:

      猜你喜欢
      • 2020-06-03
      • 2021-08-21
      • 1970-01-01
      • 2020-04-21
      • 2017-08-19
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多