简体   繁体   中英

why xaxis and yaxis ticks don't appear on axes in D3?

I'm using d3 v5 to create a data visualization of a three column CSV file. The code I've written for the axes draws the axes, but the ticks don't appear. When I directly input integers into domain, the ticks appear, but apparently the domain doesn't get the max value from my data. I need help with this, please.

var dataset = [];

var w = 1000;
var h = 600;
var padding = 30;


d3.csv("nobel-prize.csv", d3.autoType(), function(d) {
    return {
        Year: +d.Year,
        Women: +d.Women,
        Men: +d.Men
    };

}).then(function(data) {

    dataset = data;

    console.log(data);


});

var xScale = d3.scaleLinear()
               .domain([0, d3.max(dataset, d => d.Year)])
               .range([padding, w - padding * 2])
               .nice();


var yScale = d3.scaleLinear()
               .domain([0, d3.max(dataset, d => d.Men)])
               .range([h - padding, padding])
               .nice();


var xAxis = d3.axisBottom()
              .scale(xScale)

var yAxis = d3.axisLeft()
              .scale(yScale)


var svg = d3.select("svg")

            .attr("width", w)
            .attr("height", h);

            svg.append("g")
            .call(xAxis)
            .attr("class", "axis")
            .attr("transform", "translate(0, " + (h - padding) + ")")


         svg.append("g")
            .call(yAxis)
            .attr("class", "axis")
            .attr("transform", "translate(" + padding + ", 0)")

All the code located after the .then function is running before the CSV data is retrieved, hence when dataset is an empty array.

The code defining axes and drawing the chart should be moved accordingly, inside the .then function.

.then(function(data) {

    dataset = data;

    console.log(data);

   // here

});

Other remark: the x scale is currently defined to show all years between 0 and the max of the dataset:

.domain([0, d3.max(dataset, d => d.Year)])

Assuming the chart will display Nobel prize winners,you probably want the chart to start in 1901 (or use the min value found in the dataset).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM