Home > database >  Enter, update, and exit selections in join() from a dropdown menu
Enter, update, and exit selections in join() from a dropdown menu

Time:08-05

I am currently testing out d3's join, enter, update, exit and desiring to produce something like chart update 1 or chart update 2.

To achieve this, I have built a HTML dropdown with select element from a dataset and I expect to wire up the dropdown to the viz to achieve at least updated values as per the dropdown selection. But it is failing.

It is a hard concept to grasp and I am not sure where the code is failing. If any value is selected from the dropdown, the chart does not update at all.

////////////////////////////////////////////////////////////
//////////////////////// 00 BUILD DATA//////// /////////////
////////////////////////////////////////////////////////////

//desired permutation length 
const length = 4;

//build array from the above length
const perm = Array.from(Array(length).keys()).map((d) => d   1);

//generate corresponding alphabets for name
const name = perm.map((x) => String.fromCharCode(x - 1   65));

//permutation function - https://stackoverflow.com/questions/9960908/permutations-in-javascript/24622772#24622772
function permute(permutation) {
    var length = permutation.length,
        result = [permutation.slice()],
        c = new Array(length).fill(0),
        i = 1,
        k, p;

    while (i < length) {
        if (c[i] < i) {
            k = i % 2 && c[i];
            p = permutation[i];
            permutation[i] = permutation[k];
            permutation[k] = p;
              c[i];
            i = 1;
            result.push(permutation.slice());
        } else {
            c[i] = 0;
              i;
        }
    }
    return result;
};

//generate permutations
const permut = permute(perm);

//generate year based on permutation
const year = permut.map((x, i) => i   2000);

//generate a yearly constant based on year to generate final value as per the rank {year-name}
const constant = year.map(d => Math.round(d * Math.random()));

const src =
    year.map((y, i) => {
        return name.map((d, j) => {
            return {
                Name: d,
                Year: y,
                Rank: permut[i][j],
                Const: constant[i],
                Value: Math.round(constant[i] / permut[i][j])
            };
        });
    }).flat();

//console.log(src);

////////////////////////////////////////////////////////////
//////////////////////// 0 BUILD HTML DROPDOWN /////////////
////////////////////////////////////////////////////////////
d3.select('body')
    .append('div', 'dropdown')
    .style('position', 'absolute')
    .style('top', '400px')
    .append('select')
    .attr('name', 'input')
    .classed('Year', true)
    .selectAll('option')
    .data(year)
    .enter()
    .append('option')
    //.join('option')
    .text((d) => d) 
    .attr("value", (d) => d ) 

//get the dropdown value
const filterYr = parseFloat(d3.select('.Year').node().value);


////////////////////////////////////////////////////////////
//////////////////////// 1 DATA WRANGLING //////////////////
////////////////////////////////////////////////////////////

const xAccessor = (d) => d.Year;
const yAccessor = (d) => d.Value;


////////////////////////////////////////////////////////////
//////////////////////// 2 CREATE SVG //////////////////////
////////////////////////////////////////////////////////////
//namespace
//define dimension
const width = 1536;
const height = 720;
const svgns = "http://www.w3.org/2000/svg";
const svg = d3.select("svg");

svg.attr("xmlns", svgns).attr("viewBox", `0 0 ${width} ${height}`);

svg
    .append("rect")
    .attr("class", "vBoxRect")
    //.style("overflow", "visible")
    .attr("width", `${width}`)
    .attr("height", `${height}`)
    .attr("stroke", "black")
    .attr("fill", "white");

////////////////////////////////////////////////////////////
//////////////////////// 3 CREATE BOUND ////////////////////
////////////////////////////////////////////////////////////
const padding = {
    top: 70,
    bottom: 100,
    left: 120,
    right: 120
};
const multiplierH = 1; //controls the height of the visual container
const multiplierW = 1; //controls the width of the visual container

const boundHeight = height * multiplierH - padding.top - padding.bottom;
const boundWidth = width * multiplierW - padding.right - padding.left;

//create BOUND rect -- to be deleted later
svg
    .append("rect")
    .attr("class", "boundRect")
    .attr("x", `${padding.left}`)
    .attr("y", `${padding.top}`)
    .attr("width", `${boundWidth}`)
    .attr("height", `${boundHeight}`)
    .attr("fill", "white");

//create bound element
const bound = svg
    .append("g")
    .attr("class", "bound")
    .style("transform", `translate(${padding.left}px,${padding.top}px)`);


function draw() {

    // filter data as per dropdown
    const data = src.filter(a => a.Year == filterYr);

    ////////////////////////////////////////////////////////////
    //////////////////////// 4 CREATE SCALE ////////////////////
    ////////////////////////////////////////////////////////////

    const scaleX = d3
        .scaleLinear()
        .range([0, boundWidth])
        .domain(d3.extent(data, xAccessor));

    const scaleY = d3
        .scaleLinear()
        .range([boundHeight, 0])
        .domain(d3.extent(data, yAccessor));

    bound.append('g')
        .classed('textContainer', true)
        .selectAll('text')
        .data(data)
        .join(
            enter => enter.append('text')
            .attr('x', (d, i) => scaleX(d.Year))
            .attr('y', (d, i) => i)
            .attr('dy', (d, i) => i * 30)
            .text((d) => d.Year   '-------'   d.Value.toLocaleString())
            .style("fill", "blue"),
            update =>
            update
            .transition()
            .duration(500)
            .attr('x', (d, i) => scaleX(d.Year))
            .attr('y', (d, i) => i)
            .attr('dy', (d, i) => i * 30)
            .text((d) => d.Year   '-------'   d.Value.toLocaleString())
            .style("fill", "red")
            /*,
                        (exit) =>
                        exit
                        .style("fill", "black")
                        .transition()
                        .duration(1000)
                        .attr("transform", (d, i) => `translate(${300},${30   i * 30})`)
                        .remove()*/
        )


}

draw();
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>

<body>
    <svg>       
    </svg>
    <!--d3 script-->
    <script type="text/javascript">
    </script>
</body>

</html>

CodePudding user response:

You have a dropdown, but you're not listening to it. For example:

select.on("change", () => {
    const filterYr = parseFloat(d3.select('.Year').node().value);
    draw(filterYr);
});

Which alternatively can also be:

select.on("change", event => {
    const filterYr =  event.currentTarget.value;
    draw(filterYr);
});

Note that I'm passing filterYr to the draw() function as an argument. Also, do not append the containing <g> inside draw(), otherwise you'll have only the enter selection.

Here's your code with those changes:

////////////////////////////////////////////////////////////
//////////////////////// 00 BUILD DATA//////// /////////////
////////////////////////////////////////////////////////////

//desired permutation length 
const length = 4;

//build array from the above length
const perm = Array.from(Array(length).keys()).map((d) => d   1);

//generate corresponding alphabets for name
const name = perm.map((x) => String.fromCharCode(x - 1   65));

//permutation function - https://stackoverflow.com/questions/9960908/permutations-in-javascript/24622772#24622772
function permute(permutation) {
  var length = permutation.length,
    result = [permutation.slice()],
    c = new Array(length).fill(0),
    i = 1,
    k, p;

  while (i < length) {
    if (c[i] < i) {
      k = i % 2 && c[i];
      p = permutation[i];
      permutation[i] = permutation[k];
      permutation[k] = p;
        c[i];
      i = 1;
      result.push(permutation.slice());
    } else {
      c[i] = 0;
        i;
    }
  }
  return result;
};

//generate permutations
const permut = permute(perm);

//generate year based on permutation
const year = permut.map((x, i) => i   2000);

//generate a yearly constant based on year to generate final value as per the rank {year-name}
const constant = year.map(d => Math.round(d * Math.random()));

const src =
  year.map((y, i) => {
    return name.map((d, j) => {
      return {
        Name: d,
        Year: y,
        Rank: permut[i][j],
        Const: constant[i],
        Value: Math.round(constant[i] / permut[i][j])
      };
    });
  }).flat();

//console.log(src);

////////////////////////////////////////////////////////////
//////////////////////// 0 BUILD HTML DROPDOWN /////////////
////////////////////////////////////////////////////////////
const select = d3.select('body')
  .append('div', 'dropdown')
  .style('position', 'absolute')
  .style('top', '400px')
  .append('select')
  .attr('name', 'input')
  .classed('Year', true);

select.selectAll('option')
  .data(year)
  .enter()
  .append('option')
  //.join('option')
  .text((d) => d)
  .attr("value", (d) => d)

//get the dropdown value
const filterYr = parseFloat(d3.select('.Year').node().value);

select.on("change", event => {
  const filterYr =  event.currentTarget.value;
  draw(filterYr);
});


////////////////////////////////////////////////////////////
//////////////////////// 1 DATA WRANGLING //////////////////
////////////////////////////////////////////////////////////

const xAccessor = (d) => d.Year;
const yAccessor = (d) => d.Value;


////////////////////////////////////////////////////////////
//////////////////////// 2 CREATE SVG //////////////////////
////////////////////////////////////////////////////////////
//namespace
//define dimension
const width = 1536;
const height = 720;
const svgns = "http://www.w3.org/2000/svg";
const svg = d3.select("svg");

svg.attr("xmlns", svgns).attr("viewBox", `0 0 ${width} ${height}`);

svg
  .append("rect")
  .attr("class", "vBoxRect")
  //.style("overflow", "visible")
  .attr("width", `${width}`)
  .attr("height", `${height}`)
  .attr("stroke", "black")
  .attr("fill", "white");

////////////////////////////////////////////////////////////
//////////////////////// 3 CREATE BOUND ////////////////////
////////////////////////////////////////////////////////////
const padding = {
  top: 70,
  bottom: 100,
  left: 120,
  right: 120
};
const multiplierH = 1; //controls the height of the visual container
const multiplierW = 1; //controls the width of the visual container

const boundHeight = height * multiplierH - padding.top - padding.bottom;
const boundWidth = width * multiplierW - padding.right - padding.left;

//create BOUND rect -- to be deleted later
svg
  .append("rect")
  .attr("class", "boundRect")
  .attr("x", `${padding.left}`)
  .attr("y", `${padding.top}`)
  .attr("width", `${boundWidth}`)
  .attr("height", `${boundHeight}`)
  .attr("fill", "white");

//create bound element
const bound = svg
  .append("g")
  .attr("class", "bound")
  .style("transform", `translate(${padding.left}px,${padding.top}px)`);

const g = bound.append('g')
  .classed('textContainer', true);


function draw(filterYr) {

  // filter data as per dropdown
  const data = src.filter(a => a.Year == filterYr);

  ////////////////////////////////////////////////////////////
  //////////////////////// 4 CREATE SCALE ////////////////////
  ////////////////////////////////////////////////////////////

  const scaleX = d3
    .scaleLinear()
    .range([0, boundWidth])
    .domain(d3.extent(data, xAccessor));

  const scaleY = d3
    .scaleLinear()
    .range([boundHeight, 0])
    .domain(d3.extent(data, yAccessor));

  g.selectAll('text')
    .data(data)
    .join(
      enter => enter.append('text')
      .attr('x', (d, i) => scaleX(d.Year))
      .attr('y', (d, i) => i)
      .attr('dy', (d, i) => i * 30)
      .text((d) => d.Year   '-------'   d.Value.toLocaleString())
      .style("fill", "blue"),
      update =>
      update
      .transition()
      .duration(500)
      .attr('x', (d, i) => scaleX(d.Year))
      .attr('y', (d, i) => i)
      .attr('dy', (d, i) => i * 30)
      .text((d) => d.Year   '-------'   d.Value.toLocaleString())
      .style("fill", "red")
      /*,
                  (exit) =>
                  exit
                  .style("fill", "black")
                  .transition()
                  .duration(1000)
                  .attr("transform", (d, i) => `translate(${300},${30   i * 30})`)
                  .remove()*/
    )


}

draw(filterYr);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>

<body>
  <svg>       
    </svg>
  <!--d3 script-->
  <script type="text/javascript">
  </script>
</body>

</html>

  • Related