运用D3.js实现柱状图

该博客展示了如何使用D3.js库创建一个条形图,以显示全球前10个人口最多的国家及其人口数量。通过定义线性比例尺和带状比例尺,将数据映射到SVG元素上,最终生成一个包含X轴和Y轴的可视化图表,X轴表示人口,Y轴表示国家名称。博客还涉及到了数据绑定、矩形绘制以及坐标轴的添加和格式化。
摘要由CSDN通过智能技术生成
<!DOCTYPE html>
<html>

<head>
    <title>Axes</title>
    <script src="https://d3js.org/d3.v5.min.js"></script>
</head>

<body>
    <svg width="960" height="500" id="mainsvg" class="svgs"></svg>
    <script>
        const data = [{
            country: "China",
            population: "1415046"

        }, {
            country: "India",
            population: "1354052"

        }, {
            country: "United States",
            population: "326767"

        }, {
            country: "Indonesia",
            population: "266795"

        }, {
            country: "Brazil",
            population: "210868"

        }, {
            country: "Pakistan",
            population: "200814"

        }, {
            country: "Nigeria",
            population: "195875"

        }, {
            country: "Bangladesh",
            population: "166368"

        }, {
            country: "Russia",
            population: "143965"

        }, {
            country: "Mexico",
            population: "130759"

        }]
        const svg = d3.select('#mainsvg');
        const width = +svg.attr('width');
        const height = +svg.attr('height');
        const margin = {
            top: 60,
            right: 30,
            bottom: 60,
            left: 150
        };
        const innerWidth = width - margin.left - margin.right;
        const innerHeight = height - margin.top - margin.bottom;
        const xValue = (datum) => {
            return datum.population
        };
        const yValue = (datum) => {
            return datum.country
        };

        const render = function(data) {

            // Linear Scale: Data Space -> Screen Space; 
            const xScale = d3.scaleLinear()
                .domain([0, d3.max(data, xValue)])
                .range([0, innerWidth]);

            // Introducing y-Scale; 
            const yScale = d3.scaleBand()
                .domain(data.map(yValue))
                .range([0, innerHeight])
                .padding(0.1);

            // The reason of using group is that nothing is rendered outside svg, so margin of svg is always blank while margin of group is rendered inside svg; 
            const g = svg.append('g')
                .attr('transform', `translate(${margin.left}, ${margin.top})`);

            // Do the data join (Enter)
            g.selectAll('rect')
                .data(data)
                .enter()
                .append('rect')
                .attr('y', datum => yScale(yValue(datum)))
                .attr('width', (datum) => {
                    return xScale(xValue(datum))
                }) // use xSacle to re-scale data space (domain) and return the rescaled population; 
                .attr('height', yScale.bandwidth())
                .attr('fill', 'steelblue')

            // Adding axes; 
            const yAxis = d3.axisLeft(yScale);
            const xAxis = d3.axisBottom(xScale)
                .tickFormat(d3.format('.3s'))
                .tickSize(-innerHeight);

            let yAxisGroup = g.append('g').call(yAxis);

            yAxisGroup.selectAll('.domain, .tick line').remove(); // we can select multiple tags using comma to seperate them and we can use space to signify nesting; 

            let xAxisGroup = g.append('g').call(xAxis)
                .attr('transform', `translate(${0}, ${innerHeight})`);
            xAxisGroup.append('text')
                .attr('y', 50)
                .attr('x', innerWidth / 2)
                .attr('fill', 'black').text('Population')
                .attr('id', 'population');
            xAxisGroup.selectAll('.domain').remove();

            // Adding a title; 
            g.append('text')
                .text('Top 10 Most Populous Countries')
                .attr('y', -10)
                .attr('x', 80);
        }
        render(data);
        // d3.csv('./static/data/population.csv')
        //     .then(function(data) {
        //         data.forEach(datum => {
        //             //datum.population = parseFloat(datum.population);
        //             datum.population = +(datum.population);
        //         })
        //         console.log(data);
        //         console.log(data.map((datum) => {
        //             return datum.country;
        //         }))
        //         render(data);
        //     });
    </script>
</body>

</html>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值