Skip to content

Instantly share code, notes, and snippets.

@slowkow
Last active July 23, 2018 17:38
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 slowkow/22daea426607416bfcd573ce9cbd89ab to your computer and use it in GitHub Desktop.
Save slowkow/22daea426607416bfcd573ce9cbd89ab to your computer and use it in GitHub Desktop.
Call Colorgorical from R http://vrl.cs.brown.edu/color
# install.packages(c("httr", "jsonlite"))

colorgorical <- function(n = 10) {
  post_body <- jsonlite::toJSON(
    auto_unbox = TRUE,
    list(
      'paletteSize' = n,
      'weights' = list(
        'ciede2000' = 0,
        'nameDifference' = 0,
        'nameUniqueness' = 0,
        'pairPreference' = 0
      ),
      'hueFilters' = list(),
      'lightnessRange' = c("25", "85"),
      'startPalette' = list()
    )
  )
  retval <- httr::POST(
    url = 'http://vrl.cs.brown.edu/color/makePalette',
    body = post_body
  )
  retval <- httr::content(retval)
  lab2hex <- function(Lab) rgb(convertColor(Lab, from = "Lab", to = "sRGB"))
  return(sapply(retval$palette, function(x) {
    lab2hex(unlist(x[1:3]))
  }))
}
> pal <- colorgorical(21)
> pal
 [1] "#09C472" "#6C3918" "#C88106" "#C3A0C7" "#269EB3" "#5EE8EF" "#CE3AF6" "#CDDB9B" "#F84F9C"
[10] "#544793" "#B6D320" "#74158E" "#AE301F" "#115305" "#6E8E3B" "#76F013" "#1D4C5E" "#FE7446"
[19] "#668BFB" "#FBD106" "#B471F2"
@strengejacke
Copy link

Nice function! You could add httr:: to the content()-call:

retval <- httr::content(retval)

because you're not loading the libraries, and the namespace-reference is missing here.

@slowkow
Copy link
Author

slowkow commented Apr 27, 2017

Thanks! Fixed.

@Robbie90
Copy link

Would it be possible to extract the HEX codes instead of the RGBs? It is very hard to use RGBs in R when they are negative :/

@slowkow
Copy link
Author

slowkow commented Jul 23, 2018

@strengjacke @Robbie90

I'm sorry for the very late comment, but I just now realized that the API returns Lab values. The new code should work correctly now.

Imgur

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