Skip to content

Instantly share code, notes, and snippets.

@lgatto
Last active November 7, 2015 13:37
Show Gist options
  • Save lgatto/40dc73363b3359ea437a to your computer and use it in GitHub Desktop.
Save lgatto/40dc73363b3359ea437a to your computer and use it in GitHub Desktop.
A simple interface to select colours
colour_picker <- function() {
n <- length(colours())
i <- ceiling(sqrt(n))
m <- matrix(c(1:n, rep(NA, i^2 - n)),
ncol = i, nrow = i)
## plotting
image(m, col = colours(),
xaxt = "n", yaxt = "n")
k <- seq(0, 1, length.out = i)
kk <- expand.grid(k, k)
kk <- kk[1:n, ]
## points(kk)
## choosing
identifycol <- function(x, y = NULL, n = length(x), pch = 19) {
## from ?identify
k <- 1
xy <- xy.coords(x, y); x <- xy$x; y <- xy$y
sel <- rep(FALSE, length(x)); res <- integer(0)
while(sum(sel) < n) {
ans <- identify(x[!sel], y[!sel], n = 1, plot = FALSE)
if (!length(ans)) break
ans <- which(!sel)[ans]
text(x[ans], y[ans], k, cex = 1.5)
k <- k + 1
sel[ans] <- TRUE
res <- c(res, ans)
}
res
}
ans <- identifycol(kk)
ans <- scales::col2hcl(colours()[ans])
return(ans)
}
@daattali
Copy link

daattali commented Jun 3, 2015

Nice, very useful, I'm going to use this. I especially like the "colour" vs "color" :)

And if I want to know what the name of the colour is, this works very nicely with my closest_colour_hex gist. (closest_colour_hex(colour_picker()))

@daattali
Copy link

daattali commented Jun 3, 2015

Do you mind making a few tiny edits so that I don't have to fork it into my own gist? The above didn't work for me out of the box, had to make these small adjustments:

  • replace i <- 26 with i <- ceiling(sqrt(n))
  • replace rep(NA, m) with rep(NA, i^2 - n) (m is not defined)
  • change the call to col2hcl to scales::col2hcl (or add a library(scales))

@lgatto
Copy link
Author

lgatto commented Nov 7, 2015

Sorry, I missed you comments. Thank you very much for your suggestions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment