<- function(x) readLines(gzcon(url(x))) read_gz
Today I’m working on the final touches of a Shiny app called ShinyDAG. The goal of the app is to help users create DAGs for causal inference with a drag-and-drop interface. Way down deep underneath the hood, the DAG is rendered using TikZ and LaTeX (via the texPreview package), and the app allows the user to tweak the appearance of the DAG without having to learn TikZ.
One of the appearance changes that the user can make is to change the color of the graph’s edges or nodes, using the colors defined in the xcolor LaTeX package. Rather than provide an open-ended text box, I wanted to give the user a dropdown menu containing the available colors.
It turned out to be just a few lines of code to grab the .def
files from the xcolor package page, strip out the non-color related TeX lines, and create a simple tibble of the provided colors.
Quick sidenote: the .def
files are actually .def.gz
(or gzipped files), but we can read these directly into R using url()
inside gzcon()
, which is then passed to readLines()
to read the uncompressed text. I wrapped this up into a simple helper function, read_gz()
.
Now we can grab those files and extract the color definitions.
library(dplyr)
library(purrr)
library(readr)
library(stringr)
<- function(x) readLines(gzcon(url(x)))
read_gz
<-
xcolor list(
svg = "http://www.ukern.de/tex/xcolor/tex/svgnam.def.gz",
x11 = "http://www.ukern.de/tex/xcolor/tex/x11nam.def.gz"
%>%
) map(read_gz) %>%
flatten_chr() %>%
str_subset("^(%%|\\\\| )", negate = TRUE) %>%
str_remove("(;%|\\})$") %>%
paste(collapse = "\n") %>%
read_csv(col_names = c("color", "r", "g", "b")) %>%
arrange(color)
head(xcolor)
# A tibble: 6 × 4
color r g b
<chr> <dbl> <dbl> <dbl>
1 AliceBlue 0.94 0.972 1
2 AntiqueWhite 0.98 0.92 0.844
3 AntiqueWhite1 1 0.936 0.86
4 AntiqueWhite2 0.932 0.875 0.8
5 AntiqueWhite3 0.804 0.752 0.69
6 AntiqueWhite4 0.545 0.512 0.47
A Shiny fixed-color picker
I haven’t finished incorporating this into the app yet, but this is the how the color selector will look when I do.
All of the xcolor
colors
Here are all of the 468 colors in the xcolor package. (And man, it’s hard to sort colors.) If you’re interested, you can download the final list as a csv file.