Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New component: Color scale legend #121

Draft
wants to merge 19 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 24 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"d3-hierarchy": "^3.1.1",
"d3-quadtree": "^3.0.1",
"d3-sankey": "^0.12.3",
"d3-scale-chromatic": "^3.0.0",
"d3-time": "^3.0.0",
"d3-time-format": "^4.1.0",
"degit": "^2.8.4",
Expand Down
191 changes: 191 additions & 0 deletions src/_components/ColorBar.html.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
<!--
@component
Creates a color bar key for chromatic scales on `zScale`.
-->
<script>
import { getContext } from 'svelte';

const { zScale } = getContext('LayerCake');

/** @type {string | null} [label=null] - Text label to show next to the color bar */
export let label = null;

/** @type {string} [labelSide='left'] - Position of the label. Can be 'top', 'right', 'bottom', or 'left
* text label relative to the gradient bar */
export let labelSide = `left`;

/** @type {Number|Array|Function} [ticks=4] - If this is a number, it passes that along to the [d3Scale.ticks](https://github.com/d3/d3-scale) function. If this is an array, hardcodes the ticks to those values. If it's a function, passes along the default tick values and expects an array of tick values in return. */
export let ticks = 3;

/** @type {Boolean} [tickMarks=false] - Show a vertical mark for each tick. */
export let tickMarks = false;

/** @type {Function} [formatTick=d => d] - A function that passes the current tick value and expects a nicely formatted value in return. */
export let formatTick = (d) => d;

/** @type {Boolean} [snapTicks=true] - Instead of centering the text on the first and the last items, align them to the edges of the chart. */
export let snapTicks = true;

/** @type {string} [tickSide='bottom'] - Position of tick labels. Can be 'top' or 'bottom' */
export let tickSide = `bottom`;

/** @type {Number} [steps=100] - Number of samples to take of the color ramp to create the linear gradient */
export let steps = 100;

$: tickVals = Array.isArray(ticks)
? ticks
: typeof ticks === 'function'
? ticks($zScale.ticks())
: $zScale.ticks(ticks);

$: ramped = [...Array(steps).keys()].map((i) => $zScale(i / steps));
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@janosh I think the gradient creation needs some tweaks. I was testing it out with scaleDiverging using a domain of [-1, 0, 1] and because the gradient uses i here, it will always start at 0 and never get negative values. It should instead use the tick values. This should be a good example to work from: https://observablehq.com/@d3/color-legend


$: labelFlexDir = {
left: `row`,
right: `row-reverse`,
'top-left': `column`,
'top-right': `column`,
'bottom-left': `column-reverse`,
'bottom-right': `column-reverse`
}[labelSide];

$: tickFlexDir = {
top: `column-reverse`,
bottom: `column`
}[tickSide];

$: tickPos = tickMarks
? {
bottom: `top: 4px`,
top: `bottom: 4px`
}[tickSide]
: {
bottom: `top: 0`,
top: `bottom: 0`
}[tickSide];

$: tickPosMark = {
bottom: `top: 0`,
top: `bottom: 0`
}[tickSide];
</script>

<div style:flex-direction={labelFlexDir} class="colorbar" class:snapTicks class:tickMarks>
{#if label}<span class="cbar-label" data-labelside={labelSide} data-tickside={tickSide}
>{label}</span
>{/if}
<div
class="bar-container"
style:flex={labelSide === 'left' || labelSide === 'right' ? '1' : null}
style:flex-direction={tickFlexDir}
>
<div class="gradient-bar" style:background="linear-gradient(to right, {ramped})" />
<div class="tick-container">
{#each tickVals as tick_label, i}
{#if tickMarks === true}
<div
class="tick-mark"
style="left: calc(100% * {i} / {tickVals?.length - 1});{tickPosMark}; {i ===
tickVals?.length - 1
? 'transform: translateX(-1px)'
: i
? 'transform: translateX(-0.5px)'
: ''}"
/>
{/if}
<span
class="tick tick-{i}"
style="left: calc(100% * {i} / {tickVals?.length - 1}); {tickPos}"
>
{formatTick(tick_label)}
</span>
{/each}
</div>
</div>
</div>

<style>
div.colorbar {
display: flex;
box-sizing: border-box;
align-items: baseline;
position: relative;
margin: var(--cbar-margin);
padding: var(--cbar-padding);
font-size: var(--cbar-font-size, 12px);
width: var(--cbar-width);
}
div.colorbar > div {
position: relative;
width: 100%;
height: var(--cbar-height, 2em);
border-radius: var(--cbar-border-radius, 0);
}
.tick-container > span {
position: absolute;
transform: translate(-50%);
font-weight: var(--cbar-tick-label-font-weight, lighter);
font-size: var(--cbar-tick-label-font-size, --cbar-font-size);
color: var(--cbar-tick-label-color);
background: var(--cbar-tick-label-bg);
}
.bar-container,
.tick-container {
display: flex;
}
.tick-container {
position: relative;
}
.gradient-bar,
.tick-container {
flex: 1;
}

.cbar-label[data-labelside='right'][data-tickside='top'],
.cbar-label[data-labelside='left'][data-tickside='top'] {
transform: translateY(4px);
align-self: end;
}
.cbar-label[data-labelside='right'][data-tickside='bottom'],
.cbar-label[data-labelside='left'][data-tickside='bottom'] {
transform: translateY(-1px);
}
.cbar-label[data-labelside*='top-'] {
padding-bottom: 2px;
}
.cbar-label[data-labelside*='bottom-'] {
padding-top: 2px;
}
.cbar-label[data-labelside*='bottom-'][data-tickside='bottom'] {
padding-top: 5px;
}
.cbar-label[data-labelside*='top-'][data-tickside='top'] {
padding-bottom: 5px;
}
.cbar-label[data-labelside*='-right'] {
align-self: flex-end;
}
.cbar-label[data-labelside*='-left'] {
align-self: flex-start;
}
.cbar-label[data-labelside='left'] {
padding-right: 4px;
}
.cbar-label[data-labelside='right'] {
padding-left: 4px;
}

.colorbar.snapTicks .tick:last-child {
transform: translateX(-100%);
}
.colorbar.snapTicks .tick.tick-0 {
transform: translateX(0);
}
.tick-mark {
position: absolute;
border-left: 1px solid #aaa;
--length: 6px;
height: var(--length);
bottom: calc(-1 * var(--length));
}
</style>
2 changes: 2 additions & 0 deletions src/routes/_components.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import CirclePack from './_components/CirclePack.svelte';
import CirclePackForce from './_components/CirclePackForce.svelte';
import ClevelandDotPlot from './_components/ClevelandDotPlot.svelte';
import ClevelandDotPlotHtml from './_components/ClevelandDotPlot.html.svelte';
import ColorBar from './_components_ssr/ColorBar.html.svelte';
import Column from './_components/Column.svelte';
import ColumnStacked from './_components/ColumnStacked.svelte';
import Line from './_components/Line.svelte';
Expand Down Expand Up @@ -115,5 +116,6 @@ export default [
{ slug: 'Key.html.svelte', component: Key },
{ slug: 'Labels.html.svelte', component: Labels },
{ slug: 'GroupLabels.html.svelte', component: GroupLabels },
{ slug: 'ColorBar.html.svelte', component: ColorBar },
] }
];
112 changes: 112 additions & 0 deletions src/routes/_components_ssr/ColorBar.html.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<script>
import { LayerCake, Html } from 'layercake';
import { scaleSequential } from 'd3-scale';
import * as d3ScaleChromatic from 'd3-scale-chromatic';

import ColorBar from '../../_components/ColorBar.html.svelte';

const data = [{ myZ: [0, 0.25, 0.5, 0.75, 1] }];

const colorScales = Object.fromEntries(Object.entries(d3ScaleChromatic).map(([k, v]) => {
if (k.startsWith('interpolate')) {
return [k, v];
}
return null;
}).filter(Boolean));

const zKey = 'myZ';
let cbarWidth = 100;
// let cbarHeight = 1;
let nTicks = 3;
let snapTicks = true;
let tickMarks = true;
let tickSide = 'bottom';
let labelSide = 'left';
let scaleName = 'interpolateViridis';
</script>

<div class="chart-container">
<LayerCake ssr={true} z={zKey} zScale={scaleSequential(colorScales[scaleName])} {data}>
<Html>
<ColorBar label="Label one" {labelSide} formatTick={d => d * 100} {tickSide} {snapTicks} {tickMarks} ticks={nTicks} --cbar-width="{cbarWidth}%" />
</Html>
</LayerCake>
</div>

<div class="controls-container">
<div class="row">
<label class="form-label" for="cbar-width">width:</label>
<input type="range" bind:value={cbarWidth} min="50" max="100" /> <span style="display:inline-block;width:25px;text-align:right;">{cbarWidth}%</span>
</div>
<!-- <div class="row">
<label class="form-label" for="n-ticks">ticks:</label>
<input type="range" bind:value={nTicks} min="1" max="10" /> {nTicks}
</div> -->

<div class="row">
<label class="form-label" for="snap-ticks">snap ticks</label>
<input id="snap-ticks" type="checkbox" bind:checked={snapTicks} />
</div>
<div class="row">
<label class="form-label" for="tick-marks">tick marks</label>
<input id="tick-marks" type="checkbox" bind:checked={tickMarks} />
</div>

<div class="row">
<div class="form-label">tick side:</div>
<select bind:value={tickSide}>
<option value="top">top</option>
<option value="bottom">bottom</option>
</select>
</div>

<div class="row">
<div class="form-label">label side:</div>
<select bind:value={labelSide}>
<option value="top-left">top-left</option>
<option value="top-right">top-right</option>
<option value="right">right</option>
<option value="bottom-left">bottom-left</option>
<option value="bottom-right">bottom-right</option>
<option value="left">left</option>
</select>
</div>
<div class="row">
<div class="form-label">scale:</div>
<select bind:value={scaleName}>
{#each Object.keys(colorScales) as n}
<option value={n}>{n}</option>
{/each}
</select>
</div>
</div>


<style>
/*
The wrapper div needs to have an explicit width and height in CSS.
It can also be a flexbox child or CSS grid element.
The point being it needs dimensions since the <LayerCake> element will
expand to fill it.
*/
.chart-container {
width: 100%;
height: 50px;
margin-top: 5px;
}
.controls-container {
margin-bottom: 21px;
max-width: 325px;
text-align: right;
}
.row {
display: flex;
justify-content: space-between;
margin-bottom: 2px;
font-size: 0.8em;
font-family: Consolas, monaco, monospace;
}
.row input[type="range"]{
height: 15px;
}
</style>
1 change: 1 addition & 0 deletions src/routes/_components_ssr/Key.html.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@

<div class="chart-container">
<LayerCake
ssr={true}
padding={{ top: 10 }}
x={xKey}
y={yKey}
Expand Down