Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
Bar graph with d3 not sorting properly

Im trying to sort student marks in ascending order but when I try to it doesn't sort the first 3 values properly. I tried to sort it later on when I add the data to the chart but then it doesn't work at all so not sure what exactly is going wrong. Anyone know why?

    <!DOCTYPE html>
<meta charset="utf-8">
          
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v6.js"></script>
          
<!-- Create a div where the graph will take place -->
<div id="Studentmarks"></div>
<script>

  // set the dimensions and margins of the graph
  const margin = {top: 20, right: 30, bottom: 40, left: 90},
      width = 460 - margin.left - margin.right,
      height = 400 - margin.top - margin.bottom;
  
  // append the svg object to the body of the page
  const svg = d3.select("#Studentmarks")
    .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})`);
  
  // Parse the Data
  d3.csv("https://raw.githubusercontent.com/sidh4550/321/main/test2.csv").then( function(data) {
    data.sort((a, b) => d3.ascending(a.marks, b.marks));
    // Add X axis
    const x = d3.scaleLinear()
      .domain([0, 100])
      .range([ 0, width]);
    svg.append("g")
      .attr("transform", `translate(0, ${height})`)
      .call(d3.axisBottom(x))
      .selectAll("text")
        .attr("transform", "translate(-10,0)rotate(-45)")
        .style("text-anchor", "end");
  
    // Y axis
    const y = d3.scaleBand()
      .range([ 0, height ])
      .domain(data.map(d => d.Student))
      .padding(.1);
    svg.append("g")
      .call(d3.axisLeft(y))
  
    //Bars
    svg.selectAll("myRect")
      .data(data)
      .join("rect")
      .attr("x", x(0) )
      .attr("y", d => y(d.Student))
      .attr("width", d => x(d.marks))
      .attr("height", y.bandwidth())
      .attr("fill", "#69b3a2")
      
  })
  
  </script>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

your marks are in the string so you need to parse them before sorting

data.sort((a, b) => d3.ascending(parseInt(a.marks), parseInt(b.marks)));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!