Skip to content

Instantly share code, notes, and snippets.

@cmdcolin
Created March 15, 2024 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmdcolin/816da3899505c1e51f6da122ad7c90f5 to your computer and use it in GitHub Desktop.
Save cmdcolin/816da3899505c1e51f6da122ad7c90f5 to your computer and use it in GitHub Desktop.
ggplot2 vs css lch colors
@cmdcolin
Copy link
Author

cmdcolin commented Mar 15, 2024

the R color palette

image

code

gg_color_hue <- function(n) {
  hues = seq(15, 375, length = n + 1)
  hcl(h = hues, l = 65, c = 100)[1:n]
}


n = 4
cols = gg_color_hue(n)

dev.new(width = 4, height = 4)
plot(1:n, pch = 16, cex = 2, col = cols)

alternatively this which should do the same math https://scales.r-lib.org/reference/hue_pal.html

library(scales)
show_col(hue_pal()(4))

@cmdcolin
Copy link
Author

the JS color palette using the same thing, with "LCH" color from CSS https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/lch

function seq(start, end, n) {
  return Array.from(
    { length: n + 1 },
    (_, i) => start + (i * (end - start)) / n
  );
}
function gg_color_hue(n) {
  const hues = seq(15, 375, n);
  return hues.map((h) => `lch(65% 100 ${h})`).slice(0, n);
}

function ColRow({ n }) {
  const cols = gg_color_hue(n);
  return (
    <>
      {cols.map((c) => (
        <div
          style={{
            display: "inline-block",
            width: 100,
            height: 100,
            background: c,
          }}
        ></div>
      ))}
    </>
  );
}

export default function App() {
  return <ColRow n={4} />;
}

image

@cmdcolin
Copy link
Author

palettes 2-6

out 2
out 3
out 4
out 5
out 6

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