The ggplot2 color palette is very common in data visualization, but how can we get a similar palette generated on the web?
At this point, i would consider just manually generating some palettes using R code, and copying the resulting hex codes to a data array in JS, but having an accurate formula for the coloring would be interesting
I am trying the built-in LCH (light chroma hue) support in CSS, but the spectrum that the CSS LCH has seems to just not match what R has. I also tried oklch
and it is a bit better, but still doesn’t match
reference https://developer.mozilla.org/en-US/docs/Web/CSS/hue
// tested and this matches R version of seq
// reproduced from https://stackoverflow.com/questions/8197559/emulate-ggplot2-default-color-palette
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(50, 410, n);
return hues.map((h) => `lch(65% 100% ${h})`).slice(0, n);
}
function ColRow({ n }) {
const cols = gg_color_hue(n);
return (
<div>
{cols.map((c) => (
<div
style={{
display: "inline-block",
width: 100,
height: 100,
background: c,
}}
></div>
))}
</div>
);
}
export default function App() {
return (
<>
<ColRow n={2} />
<ColRow n={3} />
<ColRow n={4} />
<ColRow n={5} />
<ColRow n={6} />
</>
);
}
color palette generated by the JS code
color palette generated by the JS code if lch is replaced with oklch
color palettes generated by R code
code sandbox https://codesandbox.io/p/sandbox/funny-archimedes-jj6h77?file=%2Fsrc%2FApp.js%3A1%2C1-64%2C1