Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Last active August 19, 2021 07:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt-dray/a491a3af1a1b359439947ced07e52fab to your computer and use it in GitHub Desktop.
Save matt-dray/a491a3af1a1b359439947ced07e52fab to your computer and use it in GitHub Desktop.
Print a little square of multicoloured unicode blocks using R, {purrr} and {multicolor}
# Print a square of multicoloured unicode blocks
# Matt Dray, Aug 2021
# Related posts on rostrum.blog:
# https://www.rostrum.blog/2021/06/26/emojiscape/
# https://www.rostrum.blog/2021/06/28/pixel-art/
# https://www.rostrum.blog/2021/08/10/dehex/
# Install if you haven't already
install.packages("purrr") # for function iteration
install.packages("multicolor") # multicoloured console output
# Function: randomly select unicode elements from a provided list, arrange into
# a square, color randomly according to a provided pallette, then print to the
# console
make_squarenicode <- function(unicode_set, # vector of unicode codes
pal = rainbow(7), # colour palette
size = 10, # width and height
col = TRUE) { # FALSE for no color
x_chars <- sample(unicode_set, size ^ 2, replace = TRUE)
x_mat <- matrix(x_chars, nrow = size, ncol = size)
if (!col) {
for (i in 1:nrow(x_mat)) {
cat(x_mat[i, ], "\n")
}
}
if (col) {
for (i in 1:nrow(x_mat)) {
multicolor::multi_color(
paste(x_mat[i, ], collapse = " "),
colors = sample(pal, size, replace = TRUE)
)
}
}
}
# Pass unicode codepoint in the form "\U<code>".
# Here's an example code list for geometric shapes:
# https://en.wikipedia.org/wiki/List_of_Unicode_characters#Geometric_Shapes
# Basic example using the unicode for a heart
make_squarenicode("\U2665")
# Now a more sophisticated example using base::intToUtf8() that will print
# out multiple examples in your console at once
# You can also use the form 0x<code>, which lets you declare multiple consecutive
# codepoints more easily without typing them all out
unicode_sets <- list(
quadrants = 0x2596 + 0:9,
triangles = 0x25E2 + 0:3,
circle_halves = 0x25D0 + 0:3,
shadow_squares = 0x274F + 0:3,
points_shaded = 0x2591 + 0:1,
heavy_light_boxes = 0x2543 + 0:3,
overlaid_crosses = 0x292B + 0:1,
braille = 0x28C0 + 0:6,
corner_brackets = 0x300E + 0:1,
dice = 0x2680 + 0:5,
ellipses = 0x22EE + 0:3,
corners = 0x231C + 0:3,
flags = 0x2690 + 0:1,
hearts = 0x2665
)
# Function: print out squares using each unicode set
present_square <- function(set, set_name = names(set)) {
cat("\n\n", set_name, "\n\n")
make_squarenicode(intToUtf8(set, multiple = TRUE))
}
# Iterate over the code points to print each one consecutively
purrr::iwalk(unicode_sets, present_square)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment