d3成神之路(二):第二个柱状图

2022-01-24 15:00:19 浏览数 (1)

核心代码是理解 data(data) join("rect") .attr("height", d => yScale(0) - yScale(d.value))

代码语言:javascript复制
const yScale = d3.scaleLinear()
                 .domain([0, d3.max(data, x => x.value)])
                 .range([innerHeight, 0])
代码语言:javascript复制
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>先做一个柱状图</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1" />
</head>

<body>
    <svg width="800" height="800" id="main" class="svg"></svg>

    <script src="https://cdn.jsdelivr.net/npm/d3@7.0.1/dist/d3.min.js"></script>
    <script>
        const data = [
            { name: 'a', value: 1 },
            { name: 'b', value: 2 },
            { name: 'c', value: 3 },
            { name: 'd', value: 4 },
            { name: 'e', value: 5 },
        ]

        const svg = d3.select('#main');
        const width = svg.attr('width');
        const height = svg.attr('height');
        const margin = { top: 60, right: 30, bottom: 60, left: 50 }
        const innerWidth = width - margin.right - margin.left
        const innerHeight = height - margin.top - margin.bottom

        const xScale = d3.scaleBand()
            .domain(data.map(x => x.name))
            .range([0, innerWidth])
            .padding(0.5)

        const yScale = d3.scaleLinear()
            .domain([0, d3.max(data, x => x.value)])
            .range([innerHeight, 0])


        const g = svg.append('g').attr('id', 'maingroup').attr('transform', `translate(${margin.left},${margin.top})`)
        const yAxis = d3.axisLeft(yScale)
        g.append('g').call(yAxis)

        const xAxis = d3.axisBottom(xScale)
        g.append('g').call(xAxis).attr('transform', `translate(0, ${innerHeight})`)


        const bar = g.append("g")
            .attr("fill", "steelblue")
            .selectAll("rect")
            .data(data)
            .join("rect")
            .style("mix-blend-mode", "multiply")
            .attr("x", d => xScale(d.name))
            .attr("y", d => yScale(d.value))
            .attr("height", d => yScale(0) - yScale(d.value))
            .attr("width", xScale.bandwidth());



    </script>
</body>

</html>

0 人点赞