Skip to content

Instantly share code, notes, and snippets.

@rxw1
Created April 9, 2022 21:26
Show Gist options
  • Save rxw1/a7b0b757df5c1cb2e9ccebbd9d7ae85e to your computer and use it in GitHub Desktop.
Save rxw1/a7b0b757df5c1cb2e9ccebbd9d7ae85e to your computer and use it in GitHub Desktop.
tl
<script>
import { onMount } from 'svelte';
import * as d3 from 'd3';
$: width = 0;
$: height = 0;
$: barGaps = 20;
$: barHeight = 20;
let margin = {top: 50, right: 50, bottom: 50, left: 50};
let el;
let data1 = [
{ v: ["1982-05-31", null], l: "René", },
{ v: ["1955-07-03", null], l: "Irena", },
{ v: ["1952-07-10", null], l: "Carol", },
{ v: ["1935-09-13", null], l: "Elfriede", },
{ v: ["1985-06-13", null], l: "Rada", },
]
let data = [].concat.apply([], [data5]);
//let data = data5;
function render() {
/* Scale */
let svg = d3.select(el)
.append("svg")
.attr("width", width - margin.right)
.attr("height", height - margin.bottom)
.attr("transform", () => {
let x = 0;
let y = margin.left;
return `translate(${x},${y})`;
});
let extent = d3.extent(data.map((d: { v: any; }) => d.v).flat().map((x: string) => new Date(x)));
let scale = d3.scaleTime()
.domain(extent)
.range([width * 0.05, width * 0.95]).nice();
svg.append("g")
.call(d3.axisBottom(scale));
/* Feature Container */
let chart = svg.append("g");
let color = d3.scaleOrdinal(d3.schemeSet2);
let bars = chart.selectAll("g")
.data(data.sort(function(x, y){
return d3.ascending(x.v[0], y.v[0]);
}))
.enter()
.append("g")
.attr("transform", (d, i) => {
let x = scale(new Date(d.v[0]));
let y = i * (barHeight + barGaps) + margin.top;
return `translate(${x},${y})`;
})
bars.append("rect")
.attr("width", (d) => {
let a = d.v.length == 2 ? scale(new Date(d.v[1])) : scale(new Date(d.v[0]));
let b = scale(new Date(d.v[0]));
return Math.max(1, (a - b));
})
.attr("height", barHeight)
.attr("stroke", "#333")
.style("fill", d => {
return color(d.v[0]);
});
bars.append("text")
.attr("text-anchor", "start")
.attr("font-family", "monospace")
.attr("transform", d => {
let a = d.v.length == 2 ? scale(new Date(d.v[1])) : scale(new Date(d.v[0]));
let b = scale(new Date(d.v[0]));
let w = Math.max(1, (a - b));
let x = w + 10;
let y = (barHeight + barGaps) / 2.8;
return `translate(${x},${y})`;
})
.text(d => {
return d.l
})
return svg.node();
}
onMount(() => {
render();
});
</script>
<svelte:window bind:outerWidth={width} bind:outerHeight={height} />
<div class="vis-container" bind:clientWidth={width}>
<div bind:this={el} class="vis" />
</div>
<style>
.vis :global(div) {
font: 10px monospace;
background-color: steelblue;
text-align: right;
padding: 3px;
margin: 1px;
color: white;
}
.vis-container {
display: inline-block;
position: relative;
background-color: white;
overflow: hidden;
width: 100%;
/*
height: 100%;
*/
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment