javascript - d3v4 为什么我的线条元素没有出现?

标签 javascript d3.js graph data-visualization

我正在图表上制作一组简单的箱线图,但由于某种原因,线元素没有显示出来 代码是:

    var margin = {
        top: 10,
        right: 30,
        bottom: 30,
        left: 40
    },
    width = 900 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;
var svgBox = d3.select("#my_dataviz")
    .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 + ")");


var yScale = d3.scaleLinear()
    .range([height, 0]);


var xScale = d3.scaleBand()
    .rangeRound([0, width])
    .paddingInner(0.05)
    .align(0.1);


var center = 200
var width = 100


d3.csv("boxPlotData.csv", function(dataset) {
    var max = d3.max(dataset, function(d) {
        return +d.max;
    });
    yScale.domain([0, max])
    xScale.domain(dataset.map(function(d) {
        return d.borough;
    }));
    svgBox.append("g").call(d3.axisLeft(yScale));
    svgBox.append("g").attr("transform", "translate(0," + height + ")").call(d3.axisBottom(xScale));

    svgBox.selectAll("line").data(dataset).enter()
        .append("line")
        .attr("x1", d => xScale(d.borough) + width / 3.5)
        .attr("x2", d => xScale(d.borough) + width / 3.5)
        .attr("y1", d => yScale(+d.min))
        .attr("y2", d => yScale(+d.max))
        .attr("stroke", "black");


    svgBox.selectAll("rect")
        .data(dataset)
        .enter()
        .append("rect")
        .attr("x", d => xScale(d.borough) + width / 3.5)
        .attr("y", d => yScale(+d.q3))
        .attr("height", d => (yScale(+d.q1) - yScale(+d.q3)))
        .attr("width", width)
        .attr("stroke", "black")
        .style("fill", "#69b3a2");
});

我的数据是这样的

Data CSV

代码按预期输入了“rect”元素,但行组件没有显示在 html 中的任何位置?

最佳答案

问题是您不能只使用 svgBox.selectAll("line"),因为它会选择轴刻度线和轴线。相反,我建议使用 attr("class", "line") 向您的行添加一个类,并使用 svgBox.selectAll(".line") 专门选择行追加。

所以行追加片段应该是:

  svgBox.selectAll(".line")
    .data(dataset)
    .enter()
    .append("line")
    .attr("class", "line")
    .attr("x1", d => xScale(d.borough) + width / 3.5)
    .attr("x2", d => xScale(d.borough) + width / 3.5)
    .attr("y1", d => yScale(+d.min))
    .attr("y2", d => yScale(+d.max))
    .attr("stroke", "black");

这是工作片段 block :https://bl.ocks.org/akulmehta/4b29fb357ea7f02a1b47b611e03a5468/

关于javascript - d3v4 为什么我的线条元素没有出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59041956/

相关文章:

javascript - 使用 localStorage 代替 Cookies 有什么缺点吗?

javascript - 如何将 x、y、y0 以外的属性附加到 d3 中的流图层?

javascript - RaphaelJS 中图论图的标记节点

javascript - javascript附加的DOM错误

javascript - 如何在javascript中获取动态子字符串?

javascript - Adobe DTM 无法将 Angular 变量识别为数据元素

javascript - 更新、退出、更新、进入带有转换的模式

javascript - D3 - 定位边缘抛出 NaN 错误

python - Matplotlib 和 Networkx - 绘制自循环节点

algorithm - 使用什么算法来找到最小生成森林?