如何向此折线图D3添加过渡

时间:2018-07-20 08:52:47

标签: javascript d3.js

我使用D3创建了此折线图,但是我无法在其中添加画线的过渡。我尝试了许多不同的方法,但是每次d3都会引发错误。也许我的画线方法是错误的,这就是为什么无法添加过渡。非常感谢您的帮助。以下是小提琴https://jsfiddle.net/3wsLjfgu/

d3.json("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;

let data = JSON.parse(JSON.stringify(dataArr));

let svg = d3.select("#chart")
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom);

let g = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

let x = d3.scaleTime().rangeRound([0, width - (margin.right)]);

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

let line = d3.line()
    .x(function (d) { return x(d.date); })
    .y(function (d) { return y(d.units); });

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 })
}

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

g.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))
    .select(".domain")

g.append("g")
    .call(d3.axisLeft(y))


g.append("path")
    .datum(all)
    .attr("fill", "none")
    .attr("stroke", "steelblue")
    .attr("stroke-linejoin", "round")
    .attr("stroke-linecap", "round")
    .attr("stroke-width", 1.5)
    .attr("d", line);

g.selectAll("dot")
    .data(all)
    .enter()
    .append("circle")
    .attr("r", 6)
    .attr("cx", function (d) { return x(d.date) })
    .attr("cy", function (d) { return y(d.units) })
    .attr("class", "dot")
    .attr("stroke", "steelblue")
    .on("mouseover", function (d) {
        d3.select(this).transition().duration(100)
            .attr("r", 12)

    })
    .on("mouseout", function (d) {
        d3.select(this).transition().duration(100)
            .attr("r", 6);
    })
    .append("title")
    .append("text")
    .text(d => d.units)

 })

0 个答案:

没有答案