R miscellany

Bits and bobs of R code - useful snippets for reference

A place for snippets of code that are useful for me (or at least they were at some point). Hopefully they may also be useful for you.

Base R plotting characters

A reference chart for base R plotting characters

# Plot all shapes and colours
df <- expand.grid(x=1:7, y=4:1)

plot(df$x, df$y, pch=c(0:25,NA,NA), col=1, bg=24,
     axes=F, cex=2, xlab="", ylab="", xpd=T,
     main="Plotting character (pch) value and shape")

# Add pch value beneath each point
text(df$x, df$y, label=c(0:25,NA,NA), adj=c(0.5,3), xpd=T)

# Add explanation around last 5 shapes
rect(0.5, 0.5, 5.5, 1.5, xpd=T, lty=2)
text(3, 1.3, label="Point outline colour set with 'col'. Point fill set with 'bg'", xpd=T)

Base R colours

A reference chart for base R colours (made with ggplot)


# Construct tibble containing base colours and their RGB/HSV values
# Order by HSV so its a bit more useful...
ordered <-
  tibble(colour_names = colours()) %>%
  mutate(rgb = map(colour_names, col2rgb),
         hsv = map(rgb, rgb2hsv), 
         hue = map_dbl(hsv, ~.x[1]),
         sat = map_dbl(hsv, ~.x[2]),
         val = map_dbl(hsv, ~.x[3])) %>% 
  arrange(hue, sat, val)

# Assign variables for plot
w <- 10 # number of columns in plot
h <- ceiling(nrow(ordered)/w)

# Create plot of colours
crossing(x = 1:w, y = 1:h) %>%
  slice(1:nrow(ordered)) %>% 
  mutate(fill_colour = ordered$colour_names,
         # assign a text colour that will be readable on the background colour
         text_colour = map_chr(fill_colour, 
                               ~ifelse(mean(col2rgb(.x)) > 127, "black", "white"))) %>%
  ggplot(aes(x, y, fill=fill_colour))+
  geom_text(aes(label=fill_colour, col=text_colour), size=2)+

Chris Holmes
Senior Data Scientist

PhD physicist making his way in the world of data science!

comments powered by Disqus