RMarkdown:如何更改字体颜色?

89

在RMarkdown中有没有办法指定字体颜色?

通过浏览代码块选项,似乎没有这个选项。

9个回答

108

@Ben Bolker提供的链接中给出的答案:

Roses are <span style="color:red">red</span>, 
violets are <span style="color:blue">blue</span>.

如果您选择 HTML (ioslides) 作为输出格式,则此方法可用。

但是,如果您选择 pdf (beamer) 作为输出格式,则此方法无效。如果您想创建一个 pdf,请使用 LaTeX 语法:

    Roses are \textcolor{red}{red}, violets are \textcolor{blue}{blue}.

3
你能否澄清一下 PDF 的部分 - 我无法使它工作:undefined control sequence \textcolor。命令是 pandoc ./main.md -o ./main.pdf。主文本中的内容最简单的是 \textcolor{red}{red}。你使用什么翻译命令? 请问您能否解释PDF部分——我无法让它起作用:“undefined control sequence \textcolor”。命令为“pandoc ./main.md -o ./main.pdf”。主文本中的文本是最简单的\textcolor{red}{red}。您使用的翻译命令是什么? - Ayrat
亲爱的Ayrat,我正在RStudio中使用markdown,所以我不太熟悉pandoc命令。这可能与颜色命令无关,而是与您的系统设置有关。例如,请参见此处:http://stackoverflow.com/questions/37156696/undefined-control-sequence-error-while-converting-from-markdown-to-pdf-with-pand - Nadja Simons
3
如果您正在使用 R Markdown 并出现类似错误,请在导言区添加 header-includes: \usepackage{xcolor} - aldo_tapia
在这里,您还可以找到有关如何使用LaTeX添加颜色的完整示例:https://dr-harper.github.io/rmarkdown-cookbook/changing-font-colour.html。 - user1682960

49

我创建了一个像这样的函数:

## Color Format
colFmt <- function(x,color) {
  
  outputFormat <- knitr::opts_knit$get("rmarkdown.pandoc.to")
  
  if(outputFormat == 'latex') {
    ret <- paste("\\textcolor{",color,"}{",x,"}",sep="")
  } else if(outputFormat == 'html') {
    ret <- paste("<font color='",color,"'>",x,"</font>",sep="")
  } else {
    ret <- x
  }

  return(ret)
}

然后,您可以像这样内联使用它:`r colFmt("MY RED TEXT",'red')`。无论是在LaTeX文档还是HTML文档中工作,都将呈现彩色文本。


使用最新的Rstudio和rmarkdown::render进行pdf输出时,我发现它会在tex文件中转换为$\backslash$。因此,它会直接打印字符串而不是将其解释为latex。非常令人恼火。你有什么想法吗? - Midnighter
这是否发生在使用xtable的表中? - Nicholas Hamilton
正如你所发现的那样,确实是在我的答案中提到的 xtable 内部。 - Midnighter
请注意,HTML的<font>标签现已过时。浏览器随时可能停止支持它。 - RLesur
@Nicholas Hamilton:感谢您提供非常有用的fct! 如果我想要它与透明颜色配合使用,我需要如何调整它?请参见我的SO问题 - mavericks

27

这似乎在输出格式pdf和html中都非常有效:

Roses are $\color{red}{\text{beautiful red}}$, 
violets are $\color{blue}{\text{lovely blue}}$.

希望能对你有所帮助。


那对我来说可以用于在行内更改文本颜色。感谢您的建议。仅供其他人参考,这是LaTex语法而不是R。 - SubstantiaN
这对我也起作用了!我想指出的是,它利用了 LaTeX 的功能,这可能并不总是可行的。例如,如果您为文本使用特定字体,则可能会导致字体问题。 - Garini
在Jupyter中也能很好地工作,因为它支持MathJax(Tex和LaTex的子集)https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Typesetting%20Equations.html - prusswan

20

一种与输出格式无关的解决方案是使用kableExtra包中的专用text_spec()函数:

Roses are `r kableExtra::text_spec("red", color = "red")`,

violets are `r kableExtra::text_spec("blue", color = "blue")`

10

其他人已经提供了输出Word以外的答案。对于Word文档,你可以使用Pandoc自定义样式语法来实现这一点,并借助参考Word文档做到这一点。首先,在你的reference.docx模板中,创建一个具有简短而明显名称的新的Word样式。如果你想要字体颜色应用于整个段落,那么你可以使用默认的“链接段落和字符”样式类型。如果你只想用颜色强调段落中的某些单词,则需要选择“字符”样式类型。更改字体颜色(和任何其他所需的样式),然后保存reference.docx文件。

接下来,在你的.Rmd文件中,你可以使用以下标记:

<div custom-style=“DivCol”>Whole paragraph of colored text</div>

Just a <span custom-style=“SpanCol”>few words</span> of colored text
关于样式名称的说明 - 出于我不理解的原因,“Span_Add” 样式名称无法使用此方法,但“SpanAdd”是可以的。

我在其他地方读到下划线可能会在块名称等方面引起问题,所以我认为这就是原因。他们建议在这些情况下使用破折号“-”而不是下划线“_”: https://github.com/rstudio/bookdown/issues/313, https://bookdown.org/yihui/rmarkdown/r-code.html - hugh-allan
刚刚确认了这个解决方案也适用于常规的 .md 文件。Pandoc 可以将其转换为 .docx,而无需使用 R 的 knittr。 - Clokman
这对我似乎不起作用。我需要做些什么才能启用 span 标签的使用? - Magnus

5

我基本上使用了Nicholas Hamilton的答案,但由于我使用了xtableprint,所以在某些latex序列被转义时出现了一些问题。具体来说,\\textcolor被转换为$\backslash$textcolor。通过以下方式避免清理,我成功地解决了这个问题:

```{r results='asis'}
tbl = data.frame(a = letters[1:10], b = 1:10 / 10)
tbl$b = ifelse(tbl$b < 0.5, colFmt(tbl$b, "red"), colFmt(tbl$b, "green"))
print(xtable(tbl), sanitize.text.function = identity)
```

然后我不得不手动清理一些字符,比如%,但至少\textcolor被正确应用了。当然,这可以通过扩展自己的清理函数来避免。


正如我所料。print(xtable(tbl), sanitize.text.function = identity) - Nicholas Hamilton
sanitize.text.function = identity 可以避免你创建一个微不足道的内联函数。 - Nicholas Hamilton
我认为你之前的评论已经足够了,但我已经编辑了我的答案以反映更好的实践。 - Midnighter

1

使用sass轻松更改字体颜色

R Markdown中有一种新的更好的指定颜色或字体的方法:

  • 下载包sass
  • 在您的RMarkdown文档中创建一个块,并使用以下选项{sass, echo = FALSE}
  • 在该块中包含以下SASS代码:
// This chunk contains SASS-code to specify font color

h1, h2, h3, h4, h5
  color: blue // Color for the headers

body
  color: red // Color for the text in the main part of your document

// The colors are only examples. You can change them to anything. You could also use hex codes.

您还可以更改的不仅仅是字体颜色

通常,我在我的文档中包含类似以下内容的代码,以便同时更改字体类型、大小、链接颜色等:

// These are variables, and are easy to change
$color: blue
$color2: red
$font: "Arial"
$font-size: 16px

h1, h2, h3, h4, h5
  color: $color
  font-family: $font
  font-weight: bold

body
  background-color: white
  color: black
  font-family: $font
  font-size: $font-size

a
  color: $color

a:link
  color: $color

a:hover
  background-color: $color2


你可以通过这种方式更改任何HTML标签。 在这里阅读更多关于SASS的信息。

1

对于 PDF 和 HTML,要获取带有 markdown 高亮的可修改彩色文本:请查看 rmarkdown 书籍。Pandoc 过滤器是最好的选择。

对于 Microsoft Word,您首先需要创建一个包含自定义样式的 Template_MS.docx 文件。警告:为段落(段落样式)和少量单词(字符样式)着色创建不同的样式。这是在创建新样式时的一个选项。

在 YAML 中添加:

---      
output:   
 word_document:   
    reference_docx: Template_MS.docx   
---   

接下来:

For <span custom-style="Character1">few words</span> of colored text.

段落文本。

<div custom-style="Paragraph1">Paragraph of colored text. Blabla. Blabla.</div>   

注意事项:
+ 不要在段落和少数词语中使用相同的样式,这会导致错误。
+ 如果不起作用,请检查您在 MS 中的样式是段落还是字符。
+ 如果不起作用,请安装更新版本的 pandoc。

这对我没有起作用。相反,我不得不根据此链接(https://www.andreashandel.com/post/word-formatting-rmarkdown/)向我的YAML添加以下内容(请注意,大间隔是因为我无法在注释中添加换行符):output: bookdown::word_document2: reference_docx: Template_MS.docx - LMc

0
使用lua过滤器在渲染PDF时,包括beamer演示文稿和包括reveal.js的HTML时。 lua过滤器使您能够以非常简单和类似于markdown的格式指定RMarkdown、Quarto Markdown(.qmd)和纯Pandoc Markdown中的字体颜色。您只需通过颜色名称指定字体颜色,例如[red]{color="red"},甚至可以通过十六进制整数(hex)指定,例如[red]{color="#FF6347"}。
输出
PDFs

enter image description here

beamer

enter image description here

HTMLs

enter image description here

reveal.js

enter image description here

MWEs

color-text.lua

使用lua过滤器来更改字体颜色最初是在《R Markdown Cookbook》的5.1 Font color中介绍的。这个GitHub评论进一步详细说明了lua过滤器的用法,使我们能够使用十六进制代码设置字体颜色。
下面的lua过滤器是我之前提到的GitHub评论中介绍的lua过滤器的修改版本。当前版本使您能够在渲染beamerreveal.js演示格式时使用符号([red]{color="red"}[red]{color="#FF6347"})。
Span = function(span)
  color = span.attributes['color']
  -- if no color attribute, return unchange
  if color == nil then return span end

  -- tranform to <span style="color: red;"></span>
  if FORMAT:match 'html' or FORMAT:match 'revealjs' then -- Also available for revealjs
    -- remove color attributes
    span.attributes['color'] = nil
    -- use style attribute instead
    span.attributes['style'] = 'color: ' .. color .. ';'
    -- return full span element
    return span
  elseif FORMAT:match 'latex' or FORMAT:match 'beamer' then -- Also available for beamer
    -- remove color attributes
    span.attributes['color'] = nil
    -- encapsulate in latex code
    if string.sub(color, 1, 1) == "#" and #color == 7 then
      -- TODO: requires xcolor
      local R = tostring(tonumber(string.sub(color, 2, 3), 16))
      local G = tostring(tonumber(string.sub(color, 4, 5), 16))
      local B = tostring(tonumber(string.sub(color, 6, 7), 16))
      table.insert(
        span.content, 1,
        pandoc.RawInline('latex', '\\textcolor[RGB]{'..R..','..G..','..B..'}{')
      )
    elseif string.sub(color, 1, 1) == "#" and #color == 4 then
      -- TODO: requires xcolor
      local R = tostring(tonumber(string.sub(color, 2, 2), 16) * 0x11)
      local G = tostring(tonumber(string.sub(color, 3, 3), 16) * 0x11)
      local B = tostring(tonumber(string.sub(color, 4, 4), 16) * 0x11)
      table.insert(
        span.content, 1,
        pandoc.RawInline('latex', '\\textcolor[RGB]{'..R..','..G..','..B..'}{')
      )
    else
      table.insert(
        span.content, 1,
        pandoc.RawInline('latex', '\\textcolor{'..color..'}{')
      )
    end
    table.insert(
      span.content,
      pandoc.RawInline('latex', '}')
    )
    -- returns only span content
    return span.content
  else
    -- for other format return unchanged
    return span
  end
end

MWE
---
title: "Changing the font color"
output: 
  ## PDFs
  bookdown::pdf_document2:
    pandoc_args: 
      - "--lua-filter=color-text.lua"
  bookdown::beamer_presentation2:
    pandoc_args: 
      - "--lua-filter=color-text.lua"
  ## HTMLs
  bookdown::html_document2:
    # base_format: "function(..., number_sections) revealjs::revealjs_presentation(...)" # comment this line when creating ordinary HTMLs
    pandoc_args: 
      - "--lua-filter=color-text.lua"
    self_contained: false
always_allow_html: yes
link-citations: yes
---

## First

we define a Lua filter and write it to
the file `color-text.lua`.

```{cat, engine.opts = list(file = "color-text.lua")}
Span = function(span)
  color = span.attributes['color']
  -- if no color attribute, return unchange
  if color == nil then return span end

  -- tranform to <span style="color: red;"></span>
  if FORMAT:match 'html' or FORMAT:match 'revealjs' then -- Also available for revealjs
    -- remove color attributes
    span.attributes['color'] = nil
    -- use style attribute instead
    span.attributes['style'] = 'color: ' .. color .. ';'
    -- return full span element
    return span
  elseif FORMAT:match 'latex' or FORMAT:match 'beamer' then -- Also available for beamer
    -- remove color attributes
    span.attributes['color'] = nil
    -- encapsulate in latex code
    if string.sub(color, 1, 1) == "#" and #color == 7 then
      -- TODO: requires xcolor
      local R = tostring(tonumber(string.sub(color, 2, 3), 16))
      local G = tostring(tonumber(string.sub(color, 4, 5), 16))
      local B = tostring(tonumber(string.sub(color, 6, 7), 16))
      table.insert(
        span.content, 1,
        pandoc.RawInline('latex', '\\textcolor[RGB]{'..R..','..G..','..B..'}{')
      )
    elseif string.sub(color, 1, 1) == "#" and #color == 4 then
      -- TODO: requires xcolor
      local R = tostring(tonumber(string.sub(color, 2, 2), 16) * 0x11)
      local G = tostring(tonumber(string.sub(color, 3, 3), 16) * 0x11)
      local B = tostring(tonumber(string.sub(color, 4, 4), 16) * 0x11)
      table.insert(
        span.content, 1,
        pandoc.RawInline('latex', '\\textcolor[RGB]{'..R..','..G..','..B..'}{')
      )
    else
      table.insert(
        span.content, 1,
        pandoc.RawInline('latex', '\\textcolor{'..color..'}{')
      )
    end
    table.insert(
      span.content,
      pandoc.RawInline('latex', '}')
    )
    -- returns only span content
    return span.content
  else
    -- for other format return unchanged
    return span
  end
end
```

Now we can test the filter with some text in brackets with
the `color` attribute, e.g.,

> Roses are [red and **bold**]{color="red"} and
> violets are [blue]{color="blue"}.

> Roses are [red and **bold**]{color="#FF6347"} and
> violets are [blue]{color="#6a5acd"}.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接