Get started with d3-time CDN

BSD-3-Clause licensed

D3-time: library for time scales, intervals in D3.js data visualizations.

Tags:
  • d3
  • d3-module
  • time
  • interval
  • calendar

Stable version

Copied!

How to start using d3-time CDN


<!DOCTYPE html>
<html>
<head>
    <title>Get started with d3-time CDN - cdnhub.io</title>
    <script src="https://d3js.org/d3.v6.min.js"></script>
    <script src="https://cdn.cdnhub.io/d3-time/3.1.0/d3-time.min.js"></script>
    <style>
        .axis path,
        .axis line {
            fill: none;
            stroke: black;
            shape-rendering: crispEdges;
        }
    </style>
</head>
<body>
    <div id="chart"></div>
    <script>
        const data = [
            { date: new Date("2022-01-01"), value: 10 },
            { date: new Date("2022-01-15"), value: 20 },
            { date: new Date("2022-02-01"), value: 15 },
            { date: new Date("2022-02-15"), value: 25 },
        ];

        const margin = { top: 20, right: 20, bottom: 30, left: 50 };
        const width = 960 - margin.left - margin.right;
        const height = 500 - margin.top - margin.bottom;

        const x = d3.timeScaleDay()
            .domain(d3.extent(data, d => d.date))
            .range([0, width]);

        const y = d3.scaleLinear()
            .domain([0, d3.max(data, d => d.value)])
            .range([height, 0]);

        const svg = d3.select("#chart")
            .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .append("g")
            .attr("transform", `translate(${margin.left}, ${margin.top})`);

        svg.append("g")
            .attr("transform", `translate(0, ${height})`)
            .call(d3.axisBottom(x));

        svg.append("g")
            .call(d3.axisLeft(y));

        svg.selectAll(".bar")
            .data(data)
            .enter()
            .append("rect")
            .attr("class", "bar")
            .attr("x", d => x(d.date))
            .attr("y", d => y(d.value))
            .attr("width", x.bandwidth())
            .attr("height", d => height - y(d.value));
    </script>
</body>
</html>

All versions