如何在中心JavaScript中制作D3标签

时间:2018-07-19 08:40:10

标签: javascript d3.js

我需要将条形图放置在x轴标签的中心。由于这是scaleTime(),因此无法正确显示。我尝试使用scaleLinear和scaleBand,然后时间变得很麻烦。我是d3的新手,我们将不胜感激。这里是小提琴https://jsfiddle.net/a7yw2Lsr/6/

$.get("https://cors.io/?https://canvasjs.com/data/gallery/javascript/daily-sales-data.json", 
function (dataArr) {

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

// set the ranges
let x = d3.scaleTime().range([0, width - margin.right]);

let y = d3.scaleLinear()
    .range([height, 0]);

let 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 + ")");

let data = JSON.parse(dataArr);
let all = [];
for (let i = 0; i < data.length; i++) {
    let stringDate = new Date(data[i].date);
    all.push({ date: stringDate, units: data[i].units })
}
console.log(data)

x.domain(d3.extent(all, function (d) { return d.date; }));
y.domain([0, d3.max(all, function (d) { return d.units; })]);

// append the rectangles for the bar chart
svg.selectAll(".bar")
    .data(all)
    .enter().append("rect")
    .attr("class", "bar")
    .attr("x", function (d) { return x(d.date); })
    .attr("width", (d, i) => 50)
    .attr("y", function (d) { return y(d.units); })
    .attr("height", function (d) { return height - y(d.units); });

// add the x Axis
svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x)
        .ticks(5));

// add the y Axis
svg.append("g")
    .call(d3.axisLeft(y));
});

0 个答案:

没有答案