3

In an R markdown report rendered to both PDF and HTML, I would like to colorize text with different transparencies.
For example, I would like to use the same orange with 3 different alpha values (0.3, 0.6, 1.0).

Nicholas Hamilton provides a function to color text regardless of the output format (PDF/latex or HTML). An updated MWE of the fct. was provided by Mark Neal.

To work with transparent colors, the colFmt() function needs to be adapted somehow as far as I see.

What I tried

gplots::col2hex(color) allows converting color names to hex RGB strings, which can then be used in colFmt(). Unfortunately, the function does not allow for transparencies.

palr::col2hex(color) allows for conversion with transparencies. For PDF output these are "ignored" by colFmt() (the transparency values are simply added as text). For HTML output, they do not resemble the transparent version of the provided color (see figure below)

PDF output of MWE

PDF Output of MWE

HTML output of MWE

HTML Output of MWE

MWE

---
title: "Colored text with transparency"
author: "Test"
output: html_document
#output: pdf_document
header-includes:
  \usepackage[usenames,dvipsnames]{xcolor}
---

```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(echo = TRUE)
```

## Define colorizing function

```{r colFmt}
colFmt = function(x,color){
  outputFormat = opts_knit$get("rmarkdown.pandoc.to")
  if(outputFormat == 'latex')
    paste("\\textcolor[HTML]{",color,"}{",x,"}",sep="")
  else if(outputFormat == 'html')
    paste("<font color='",color,"'>",x,"</font>",sep="")
  else
    x
}
```

## Apply colorizing function

### gplots

```{r include=FALSE}
library(gplots) # to be able to use col2hex() to convert color names to hex RGB strings
hex_color <- str_remove(gplots::col2hex(color),"#") # convert color names to hex RGB strings
```
Some `r colFmt("orange text",hex_color)` 

### palr
```{r include=FALSE}
library(palr) # for col2hex() 
hex_color <- str_remove(palr::col2hex(color),"#")
hex_color_light <- str_remove(palr::col2hex(color, alpha = 0.3),"#")
```
Some `r colFmt("orange text",hex_color)` and some `r colFmt("light orange text", hex_color_light)` 
zx8754
  • 52,746
  • 12
  • 114
  • 209
mavericks
  • 1,005
  • 17
  • 42
  • I don't know the mechanics of hex colours, RGB colours, or other colour specifications such as HSV, but for a lighter orange, can you rescale the numbers in the colfmt function to take **orange HSV** and return **light_orange HSV**. For example, if you google *html colour picker*, and move left from orange (HSV 50degrees, 100%, 100%) to light orange (HSV 50 degrees, 50%, 100%) you are effectively just halving the S value. – Mark Neal Nov 06 '20 at 04:36

0 Answers0