d3.js 的使用

这篇文章相当于之前 svg 的补充。

因为 svg 代码肯定不是人为去专门写的。

在这里推荐制作 svg 的第三方库 - D3.js

用于定制数据可视化的JavaScript库 - D3

官网地址: D3 by Observable | The JavaScript library for bespoke data visualization

简单使用

画个坐标轴吧!

<!DOCTYPE html>
<div id="container"></div>
<script type="module">

import * as d3 from "https://cdn.jsdelivr.net/npm/d3@7/+esm";

// Declare the chart dimensions and margins.
const width = 640;
const height = 400;
const marginTop = 20;
const marginRight = 20;
const marginBottom = 30;
const marginLeft = 40;

// Declare the x (horizontal position) scale.
const x = d3.scaleUtc()
    .domain([new Date("2023-01-01"), new Date("2024-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));

// Append the SVG element.
container.append(svg.node());

</script>

效果图:

在这里插入图片描述

posted @ 2023-09-11 18:08  辰梦starDream  阅读(39)  评论(0编辑  收藏  举报  来源