Tylemaster
Tylemaster

Reputation: 37

d3v4 why are my line elements not appearing?

I am in the process of making a simple set of boxplots on a graph, but for some reason the line elements are not showing up Code is:

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

And my data is of the form

Data CSV

The code is entering the "rect" elements as expected, but the line components aren't showing up anywhere in the html?

Upvotes: 1

Views: 79

Answers (1)

Coola
Coola

Reputation: 3142

The issue is you cannot just use svgBox.selectAll("line") because it will select the axis tick marks as well as the axis lines. Instead, I suggest add a class to your line with attr("class", "line") and use svgBox.selectAll(".line") to specifically select lines to append.

So the line append snippet should be:

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

Here is the working snippet Block: https://bl.ocks.org/akulmehta/4b29fb357ea7f02a1b47b611e03a5468/

Upvotes: 3

Related Questions