avimhael
avimhael

Reputation: 105

Displaying values from JSON along an axis

I have created a graph here https://i.sstatic.net/jYisP.jpg, but am having issues displaying the JSON values along the end of the bars. They print - as you can see - at the top, but not in the correct place. How would I make them align to their corresponding bars?


const margin2 = {top: 20, right: 30, bottom: 60, left: 250}
const width2 = 1000 - margin2.left - margin2.right
const graphWidth2 = 600-margin2.left - margin2.right
const graphHeight2 = 900 - margin2.top - margin2.bottom
const height2 = 370 - margin2.top - margin2.bottom


const svg2 = d3.select(".line").append("svg").attr("width", width2 + margin2.left + margin2.right)
.attr("height", height2 + margin2.top + margin2.bottom)
.append("g").attr("transform", `translate(${margin.left+148},${margin.top})`)


d3.json("./data/linedata.json").then(function(data) {

    const x2 = d3.scaleLinear().domain([0, 100]).range([ 0, width2])

    svg2.append("g").attr("transform", "translate(0," + height2 + ")")
    .call(d3.axisBottom(x2)
    .tickFormat(d => d + "%"))
    .selectAll("text")
    .attr('class', 'xaxis')
    .attr("transform", "translate(12,0)")
    .style("text-anchor", "end")

    const y2 = d3.scaleBand().range([ 0, height2 ])
    .domain(data.map(function(d) { return d.desc; })).padding(.2)

    svg2.append("g").attr('class', 'xaxis')
    .call(d3.axisLeft(y2)).style("font-family","Pluto Sans").style("font-size","16").style("fill","#4F5552")  
    
    const deleteline = svg2.selectAll("path,line").remove();

    svg2.selectAll(".line1").data(data).enter().append("rect")
    .attr("x",x2(0))
    .attr("y", function(d) { return y2(d.desc)})
    .attr("width", function(d) { return x2(d.total)})
    .attr("height", y2.bandwidth())

    svg2.selectAll(".line1").data(data).enter().append("text")
    .text((d) => { return d.total + "%"})
    .attr("x", (d) => x2(d.total + 15) +9)
    .attr("y", (d) => y2(d.desc + y2.bandwidth()))
    .style("font-size",30)

})

Upvotes: 1

Views: 48

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102218

When you do this:

.attr("y", (d) => y2(d.desc + y2.bandwidth()))

You are just concatenating a categorical variable with a number (like "foo" + 42 is "foo42"). For a band scale, that will return undefined, and your text will be at the top of the <g>.

What you want is:

.attr("y", d => y2(d.desc) + y2.bandwidth())

Upvotes: 1

Related Questions