Created
March 13, 2024 15:43
-
-
Save hyunbinseo/62548df23731d36acf5e82436cb35150 to your computer and use it in GitHub Desktop.
D3 in vanilla Svelte
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- https://d3js.org/getting-started#d3-in-vanilla-html --> | |
<script lang="ts"> | |
import * as d3 from 'd3'; | |
import type { Action } from 'svelte/action'; | |
const width = 640; | |
const height = 400; | |
const marginTop = 20; | |
const marginRight = 20; | |
const marginBottom = 30; | |
const marginLeft = 40; | |
const chart: Action = (container) => { | |
// Declare the x (horizontal position) scale. | |
const x = d3 | |
.scaleUtc() | |
.domain([new Date('2024-01-01'), new Date('2025-01-01')]) | |
.range([marginLeft, width - marginRight]); | |
// Declare the y (vertical position) scale. | |
const y = d3 | |
.scaleLinear() | |
.domain([0, 100]) | |
.range([height - marginBottom, marginTop]); | |
// Create the SVG container. | |
const svg = d3.create('svg').attr('width', width).attr('height', height); | |
// Add the x-axis. | |
svg | |
.append('g') | |
.attr('transform', `translate(0,${height - marginBottom})`) | |
.call(d3.axisBottom(x)); | |
// Add the y-axis. | |
svg | |
.append('g') | |
.attr('transform', `translate(${marginLeft},0)`) | |
.call(d3.axisLeft(y)); | |
const node = svg.node(); | |
if (node) container.append(node); | |
}; | |
</script> | |
<div use:chart></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment