D3 Interaction

COP 4283 syllabus

Lecture 23 · November 10, 2026

Lab 10 · D3 Interaction I

Original lab ZIP

01JavaScript event listeners

JavaScript
async function build() {
  // Click event
  document.getElementById("js-click-btn").addEventListener("click", function (event) {

  });

  // Double-click event
  document.getElementById("js-click-btn").addEventListener("dblclick", function (event) {

  });

  // Hover box events
  const hoverBox = document.getElementById("js-hover-box");

  // Mouseover (triggers when entering the element)
  hoverBox.addEventListener("mouseover", function (event) {

  });

  // Mouseout (triggers when leaving the element)
  hoverBox.addEventListener("mouseout", function (event) {

  });

  // Mousemove (tracks cursor movement)
  hoverBox.addEventListener("mousemove", function (event) {

  });

  // Keypress event
  document.addEventListener("keydown", function (event) {

  });

  // Drag events
  hoverBox.addEventListener("dragstart", function (event) {

  });

  hoverBox.addEventListener("drag", function (event) {

  });

  hoverBox.addEventListener("dragend", function (event) {

  });

  const status = document.getElementById('event-status');
  let clicks = 0;
  document.getElementById('js-click-btn').addEventListener('click', () => {
    status.textContent = 'Click count: ' + (++clicks);
  });
  document.getElementById('js-text-input').addEventListener('input', event => {
    status.textContent = 'Input: ' + event.target.value;
  });
  ['mouseover', 'mouseout', 'mousemove', 'dragstart', 'drag', 'dragend'].forEach(type => {
    hoverBox.addEventListener(type, event => {
      status.textContent = type + ' · x: ' + event.clientX + ', y: ' + event.clientY;
    });
  });
  document.addEventListener('keydown', event => { status.textContent = 'Key: ' + event.key; });
}

build();
Result
Loading…
Data & source

02D3 mouse events

JavaScript
async function build() {
  // Select the tooltip element

  const tooltip = d3.select("#tooltip");

  d3.selectAll("circle")
      .on("click", function (event) {
          d3.select(this).attr("fill", "orange");
          tooltip.html("Clicked!")
              .style("opacity", 1)
              .style("left", (event.pageX + 10) + "px")
              .style("top", (event.pageY + 10) + "px");

      })

      .on("dblclick", function (event) {
          d3.select(this).attr("fill", "limegreen");
          tooltip.html("Double Clicked!")
              .style("opacity", 1)
              .style("left", (event.pageX + 10) + "px")
              .style("top", (event.pageY + 10) + "px");

      })

      .on("mouseover", function (event) {
          d3.select(this).attr("stroke", "white").attr("stroke-width", 3);
          tooltip.html("Mouse Over!")
              .style("opacity", 1)
              .style("left", (event.pageX + 10) + "px")
              .style("top", (event.pageY + 10) + "px");

      })

      // Mouseout event: remove stroke and hide tooltip
      .on("mouseout", function (event) {
          d3.select(this).attr("stroke", null);
          tooltip.style("opacity", 0);

      })

      // Mousemove event: update tooltip position as the mouse moves
      .on("mousemove", function (event) {
          tooltip.style("left", (event.pageX + 10) + "px")
              .style("top", (event.pageY + 10) + "px");

      })

      // Mousedown event: change fill to yellow and show tooltip
      .on("mousedown", function (event) {
          d3.select(this).attr("fill", "yellow");
          tooltip.html("Mouse Down!")
              .style("opacity", 1)
              .style("left", (event.pageX + 10) + "px")
              .style("top", (event.pageY + 10) + "px");

      })

      // Mouseup event: reset fill to lightblue and update tooltip
      .on("mouseup", function (event) {
          d3.select(this).attr("fill", "lightblue");
          tooltip.html("Mouse Up!")
              .style("opacity", 1)
              .style("left", (event.pageX + 10) + "px")
              .style("top", (event.pageY + 10) + "px");

      })

      // Contextmenu (right-click) event: prevent default menu, change fill to red, and update tooltip
      .on("contextmenu", function (event) {
          event.preventDefault();
          d3.select(this).attr("fill", "red");
          tooltip.html("Right Click!")
              .style("opacity", 1)
              .style("left", (event.pageX + 10) + "px")
              .style("top", (event.pageY + 10) + "px");

      });
}

build();
Result
Loading…
Data & source

03Tooltips and highlighting

JavaScript
async function build() {
  const data = [
      { x: 50, y: 100, value: 30 },
      { x: 150, y: 80, value: 50 },
      { x: 250, y: 120, value: 70 }
  ];

  const svg = d3.select("svg");

  // Create a tooltip div that is hidden by default
  const tooltip = d3.select("body").append("div")
      .attr("class", "tooltip")
      .style("position", "absolute")
      .style("opacity", 0)
      .style("background", "black")
      .style("pointer-events", "none"); // Ensures the tooltip doesn't interfere with mouse events

  // Bind data to circles
  svg.selectAll("circle")
      .data(data)
      .enter().append("circle")
      .attr("cx", d => d.x)
      .attr("cy", d => d.y)
      .attr("r", 20)
      .style('opacity', .9)
      .style("fill", "#7c70ce")
      .on("mouseover", function (event, d) {

          tooltip.style("opacity", .9);
          tooltip.html("Value: " + d.value)

          // highlight selected circle

          d3.selectAll('circle')
              .style('opacity', 0.2)  //change all circles' opacity to 0.2

          d3.select(this)
              .style('opacity', 1)  // make the selected one standout

          // add circle in tooltip
          // const tooltipSVG = tooltip.append('svg')
          //     .attr('width', 200)
          //     .attr('height', 200)

          // const tooltipCircle = tooltipSVG.append('circle')
          //     .attr('class', 'tooltipCircle')
          //     .attr("cx", 100)
          //     .attr("cy", 100)

          // tooltipCircle
          //     .attr('r', d.value / 5)
          //     .style("fill", "#7c70ce")

      })
      .on("mouseout", function (d) {
          tooltip
              .style("opacity", 0);

          d3.selectAll('circle')
              .style('opacity', .9) // set all circle opacity to default value
      })
      .on("mousemove", function (event, d) {
          tooltip.style("left", (event.pageX) + "px")
              .style("top", (event.pageY - 28) + "px");
      })
}

build();
Result
Loading…
Data & source

04Highlighting with CSS classes

JavaScript
async function build() {
  const data = [
    {x: 50, y: 100, value: 30}, {x: 150, y: 80, value: 50}, {x: 250, y: 120, value: 70}
  ];
  const svg = d3.select('svg');
  const circles = svg.selectAll('circle').data(data).join('circle')
    .attr('cx', d => d.x).attr('cy', d => d.y).attr('r', 20)
    .attr('class', 'default-circle')
    .on('mouseover', function () {
      circles.classed('faded-circle', true);
      d3.select(this).classed('highlight-circle', true);
    })
    .on('mouseout', function () {
      circles.classed('faded-circle', false).classed('highlight-circle', false);
    });
}

build();
Result
Loading…
Data & source

05Reconfigure a scatterplot

JavaScript
async function build() {
  await d3.csv("./datasets/movies.csv", function (d) {
      // Preprocessing data
      return {
          director_name: d.director_name,
          num_critic_for_reviews: +d.num_critic_for_reviews,
          duration: +d.duration,
          gross: +d.gross,
          genres: d.genres,
          movie_title: d.movie_title.replace(/Â/g, ''),
          num_voted_users: +d.num_voted_users,
          budget: +d.budget >= 500000000 ? 0 : +d.budget,
          title_year: +d.title_year,
          imdb_score: +d.imdb_score,
          movie_facebook_likes: +d.movie_facebook_likes
      };
  }).then(function (data) {

      // Define SVG and its dimensions
      const svg = d3.select("svg"),
          margin = { top: 20, right: 100, bottom: 70, left: 200 },
          width = +svg.attr("width") - margin.left - margin.right,
          height = +svg.attr("height") - margin.top - margin.bottom;

      // Define scales
      const x = d3.scaleLinear(),
          y = d3.scaleLinear();

      // Group for scatter plot
      const scatterGroup = svg.append("g")
          .attr("transform", `translate(${margin.left},${margin.top})`);

      // Define constants for style
      const originalCircleOpacity = 0.7,
          hoveredCircleOpacity = 1,
          originalBarOpacity = 0.9,
          hideBarOpacity = 0.1,
          originalFill = "#7c70ce",
          hoveredFill = "#f588f0";

      // Select elements for controls
      const xSelect = d3.select("#x-select"),
          ySelect = d3.select("#y-select"),
          directorSelect = d3.select("#director-select");

      // Data attributes and directors for dropdowns
      // Populate dropdowns with options
      const attributes = ["num_critic_for_reviews", "duration", "gross", "budget", "imdb_score", "movie_facebook_likes"]

      attributes.forEach(attr => {
          // Append a new option to the xSelect dropdown with the current attribute as both its visible text and value

          xSelect.append("option").text(attr).attr("value", attr);
          ySelect.append("option").text(attr).attr("value", attr);
      });
      // Initial plot configuration
      let xAttribute = "gross",  // initial x attribute
          yAttribute = "budget"; // initial y attribute

      // Set initial values for dropdowns
      xSelect.property("value", xAttribute);
      ySelect.property("value", yAttribute);

      // Function to update scatter plot (implementation not shown)
      updateScatterPlot(data, xAttribute, yAttribute);
      // Event listener for dropdown changes
      xSelect.on("change", function (event) {
          xAttribute = this.value;
          updateScatterPlot(data, xAttribute, yAttribute);
      });

      ySelect.on("change", function (event) {
          yAttribute = this.value;
          updateScatterPlot(data, xAttribute, yAttribute);
      });

      function updateScatterPlot(data, xAttribute, yAttribute) {
          // Clear previous scatter plot elements
          scatterGroup.selectAll('*').remove();

          // Filter data to ensure both x and y attributes are numeric and not null
          data = data.filter(d => +d[xAttribute] && +d[yAttribute]);

          // Add X axis
          x.domain(d3.extent(data, d => +d[xAttribute]))
              .range([0, width])
              .nice();

          let xAxisGroup = scatterGroup.append("g")
              .attr("transform", `translate(0,${height})`)
              .call(d3.axisBottom(x).tickFormat(d3.format(".2s")));

          // Add X axis label
          xAxisGroup.append("text")
              .attr("class", "axis-label")
              .attr("x", width / 2)
              .attr("y", 50)  // you can also use translate
              .style("text-anchor", "middle")
              .attr('fill', 'white')
              .attr('font-size', 30)
              .text(xAttribute);

          // Add Y axis
          y.domain(d3.extent(data, d => +d[yAttribute]))
              .range([height, 0])
              .nice();

          let yAxisGroup = scatterGroup.append("g")
              .call(d3.axisLeft(y).tickFormat(d3.format(".2s")));

          // Add X axis label
          yAxisGroup.append("text")
              .attr("class", "axis-label")
              .attr("transform", "rotate(-90)")
              .attr("x", -height / 2)
              .attr("y", -120)
              .attr("dy", "1em")
              .style("text-anchor", "middle")
              .attr('fill', 'white')
              .attr('font-size', 30)
              .text(yAttribute);

          // Add circles for each data point
          scatterGroup.selectAll("circle")
              .data(data)
              .enter()
              .append("circle")
              .attr('class', 'myCircles')
              .attr("cx", d => x(+d[xAttribute]))
              .attr("cy", d => y(+d[yAttribute]))
              .attr("r", 4)
              .style("fill", originalFill)
              .style('opacity', originalCircleOpacity)
              .style('cursor', 'pointer')
              .on('mouseenter', mouseOverCircle)
              .on('mouseleave', mouseLeaveCircle);

          // Initialize tooltip for circles
          let circleTooltip = d3.select("body").append("div")
              .attr("class", "tooltip")
              .style("opacity", 0);

          // Add guide lines for hovered circle - X line
          let xLine = scatterGroup.append("line")
              .style('stroke', 'white')
              .style('stroke-width', 1)
              .style("visibility", "hidden")
              .style("stroke-dasharray", "3 3")
              .lower(); // Ensures line is behind circles

          // Add guide lines for hovered circle - Y line
          let yLine = scatterGroup.append("line")
              .style('stroke', 'white')
              .style('stroke-width', 1)
              .style("visibility", "hidden")
              .style("stroke-dasharray", "3 3")
              .lower(); // Ensures line is behind circles

          function mouseOverCircle(event, d) {
              // tooltip
              circleTooltip
                  .style('opacity', 0.9)
                  .html(`Movie: ${d.movie_title} <br> ${xAttribute}: ${d[xAttribute]} <br> ${yAttribute}: ${d[yAttribute].toFixed(2)}  <br> Director: ${d.director_name}`)
                  .style("left", (event.pageX + 10) + "px")
                  .style("top", (event.pageY - 20) + "px");
              //highlighting
              d3.selectAll(".myCircles")
                  .style('opacity', 0.1)
              d3.select(this)
                  .style('opacity', 0.9)
                  // .attr('r', 8)
                  .style('stroke', '#fff')
                  .style('stroke-width', 2)
              xLine
                  .style('visibility', 'visible')
                  .attr('x1', x(d[xAttribute]))
                  .attr('x2', x(d[xAttribute]))
                  .attr('y1', y(0))
                  .attr('y2', y(d[yAttribute]))
                  .style('opacity', originalCircleOpacity)
              yLine
                  .style('visibility', 'visible')
                  .attr('x1', x(0))
                  .attr('x2', x(d[xAttribute]))
                  .attr('y1', y(d[yAttribute]))
                  .attr('y2', y(d[yAttribute]))
                  .style('opacity', originalCircleOpacity)
          }
          function mouseLeaveCircle() {
              circleTooltip
                  .style('opacity', 0)
              d3.selectAll('.myCircles')
                  .style('opacity', originalCircleOpacity)
                  .style('stroke', '')
              xLine.style('visibility', 'hidden')
              yLine.style('visibility', 'hidden')
          }

      }

  })
}

build();
Result
Loading…
Data & source

06Linked scatterplot and bars

JavaScript
async function build() {
  // Based on https://d3-graph-gallery.com/graph/barplot_basic.html

  const margin = { top: 30, right: 30, bottom: 70, left: 60 },
      width = 1600 - margin.left - margin.right,
      height = 1200 - margin.top - margin.bottom;

  const circleGroupHeight = 400, circleGroupWidth = 600, barChartWidth = 1000, barChartHeight = 400

  const originalCircleOpacity = 0.7, hoveredCircleOpacity = 1, originalBarOpacity = 0.9, hideBarOpacity = 0.1;
  const originalFill = "#7c70ce", hoveredFill = "#f588f0";
  const originalCircleSize = 8;

  // append the svg object to the body of the page
  const svg = d3.select("#main")
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)

  const circleGroup = svg.append('g')
      .attr('class', 'circleGroup')
      .attr('transform', 'translate(' + 200 + ',' + 50 + ')')

  const barGroup = svg.append('g')
      .attr('class', 'barGroup')
      .attr('transform', 'translate(' + 200 + ',' + 600 + ')')

  let circleBrush, barBrush  //declare these two brushes in a higher scope, so they have access to each other

  await d3.csv("./datasets/countries.csv", d => ({
      continent: d.continent,
      country: d.country,
      gdpPercap: +d.gdpPercap,
      lifeExp: +d.lifeExp,
      pop: +d.pop
  })).then(data => {

      data = data.sort((a, b) => d3.descending(a.pop, b.pop));   // sort data using population, or const sortedData = data.sort((a, b) => b.pop - a.pop);

      data = data.slice(0, 30)

      drawScatterPlot(data); // Add scatter plot
      drawBarChart(data);    // Add bar chart

  });

  function drawScatterPlot(data) {
      let xMax = d3.max(data.map(d => +d.lifeExp))

      const x_scatter = d3.scaleLinear()
          .domain([0, xMax])
          .range([0, circleGroupWidth])
          .nice();

      let yMax = d3.max(data.map(d => +d.gdpPercap))

      const y_scatter = d3.scaleLinear()
          .domain([0, yMax])
          .range([circleGroupHeight, 0])
          .nice();

      const myCircles = circleGroup
          .selectAll(".myCircles")
          .data(data)
          .enter()
          .append("circle")
          .attr('class', 'myCircles')
          .attr("cx", d => x_scatter(d.lifeExp))
          .attr("cy", d => y_scatter(d.gdpPercap))
          .attr("r", originalCircleSize)
          .attr("fill", originalFill)
          .style('opacity', 0.8)

      //add x axis
      circleGroup.append("g")
          .attr("class", "x-axis")
          .attr("transform", `translate(0, ${circleGroupHeight})`)
          .call(d3.axisBottom(x_scatter));

      //add y axis 
      circleGroup.append("g")
          .attr("class", "y-axis")
          .call(d3.axisLeft(y_scatter));

      // Add X axis label
      circleGroup.append("text")
          .attr("class", "axis-label")
          .attr("x", circleGroupWidth / 2)
          .attr("y", circleGroupHeight + 50)
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 20)
          .text("Life Expectancy");

      // Add Y axis label
      circleGroup.append("text")
          .attr("class", "axis-label")
          .attr("transform", "rotate(-90)")
          .attr("x", -circleGroupHeight / 2)
          .attr("y", -80)
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 20)
          .text("GDP per capita");

      let circleTooltip = d3.select("body").append("div")
          .attr("class", "tooltip")
          .style("opacity", 0)

      myCircles
          .style('cursor', 'pointer')
          .on('mouseenter', mouseOverCircle)
          .on('mouseleave', mouseLeaveCircle)

      function mouseOverCircle(event, d) {

          // tooltip
          circleTooltip
              .style('opacity', 0.9)
              .html(`Country: ${d.country} <br> Continent: ${d.continent} <br> GDP per capita: ${d.gdpPercap.toFixed(2)} <br> Life Expectancy: ${d.lifeExp.toFixed(2)}`)
              .style("left", (event.pageX + 10) + "px")
              .style("top", (event.pageY - 20) + "px");

          //highlighting
          d3.selectAll(".myCircles")
              .style('opacity', 0.1)

          d3.select(this)
              .style('opacity', 0.9)
              // .attr('r', 8)
              .style('fill', hoveredFill)
              .style('stroke', '#fff')
              .style('stroke-width', 2)
          d3.selectAll('.myBar')
              .style('opacity', bar_d => bar_d.country === d.country ? originalBarOpacity : hideBarOpacity)
              .style('stroke', bar_d => bar_d.country === d.country ? '#fff' : '')

      }

      function mouseLeaveCircle() {
          circleTooltip
              .style('opacity', 0) //remove highlighting

          d3.selectAll('.myCircles')
              .attr("r", originalCircleSize)
              .style("fill", originalFill)
              .style('opacity', originalCircleOpacity)
              .style('stroke', '')
          d3.selectAll('.myBar')
              .style('opacity', originalBarOpacity)
              .style('stroke', '')

      }

  }

  function drawBarChart(data) {

      const xBar = d3.scaleBand()
          .range([0, barChartWidth])
          .domain(data.map(d => d.country))
          .padding(0.1);

      let yMaxBar = d3.max(data.map(d => +d.pop))

      const yBar = d3.scaleLinear()
          .domain([0, yMaxBar])
          .range([barChartHeight, 0])
          .nice();

      let myBars = barGroup.selectAll(".myBar")
          .data(data)
          .join('rect')
          .attr('class', 'myBar')
          .attr("x", d => xBar(d.country))
          .attr("y", d => yBar(d.pop))
          .attr("width", xBar.bandwidth())
          .attr("height", d => barChartHeight - yBar(d.pop))
          .attr("fill", originalFill)
          .style('cursor', 'pointer')

      // Add X axis label
      barGroup.append("text")
          .attr("class", "axis-label")
          .attr("x", barChartWidth / 2)
          .attr("y", barChartHeight + 80)  // you can also use translate
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 20)
          .text("Country");

      // Add Y axis label
      barGroup.append("text")
          .attr("class", "axis-label")
          .attr("transform", "rotate(-90)")
          .attr("x", -barChartHeight / 2)
          .attr("y", -80)
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 20)
          .text("Population");

      barGroup.append("g")
          .attr("transform", `translate(0, ${barChartHeight})`)
          .call(d3.axisBottom(xBar))
          .selectAll("text")
          .attr("transform", "translate(-10,0)rotate(-45)")
          .style("text-anchor", "end");

      // add y axis

      const yAxis = d3.axisLeft(yBar)
          .tickFormat(d3.format(".2s"));

      barGroup.append("g")
          .call(yAxis);

      let barTooltip = d3.select("body").append("div")
          .attr("class", "tooltip")
          .style("opacity", 0)

      d3.selectAll('.myBar')
          .style('cursor', 'pointer')
          .on('mouseenter', mouseEnterBar)
          .on('mouseleave', mouseLeaveBar)
          .on('mousemove', mouseMoveBar)

      function mouseEnterBar(event, d) {
          d3.select(this)
              .style("opacity", 1)
              // .style('fill', hoveredFill)
              .style('stroke', '#fff')
              .style('stroke-width', 1)
          barTooltip
              .style('opacity', 0.9)
              .html(`Country: ${d.country} <br> Life Expectancy: ${d.lifeExp} <br> Population: ${(+d.pop).toLocaleString()}`)

          // INSERT CODE HERE
          d3.selectAll('.myCircles')
              .style('stroke', t => t.country === d.country ? '#fff' : '')
              .style('opacity', t => t.country === d.country ? 1 : 0.1)
      }

      function mouseLeaveBar() {
          d3.select(this)
              .style('stroke', '')
          barTooltip.style('opacity', 0)
          d3.selectAll('.myCircles')
              .attr("r", originalCircleSize)
              .style("fill", originalFill)
              .style('opacity', originalCircleOpacity)
              .style('stroke', '')
      }

      function mouseMoveBar(event, d) {
          const leftPos = event.pageX - xBar.bandwidth()
          const topPos = event.pageY - 100
          barTooltip
              .style("left", leftPos + "px")
              .style("top", topPos + "px");
      }

  }
}

build();
Result
Loading…
Data & source

07Event listeners solution

JavaScript
async function build() {
  const status = d3.select('#event-status');
  let clicks = 0;
  d3.select('#js-click-btn').on('click', function () {
    status.text('Click count: ' + (++clicks));
    d3.select(this).style('background', clicks % 2 ? '#7c70ce' : '#333');
  });
  d3.select('#js-hover-btn')
    .on('mouseover', function () {
      d3.select(this).style('background', '#7c70ce');
      status.text('Mouse over the button');
    })
    .on('mouseout', function () {
      d3.select(this).style('background', '#333');
      status.text('Mouse left the button');
    });
  d3.selectAll('circle')
    .on('mouseover', function () { d3.select(this).attr('opacity', 1).attr('stroke', 'white'); })
    .on('mouseout', function () { d3.select(this).attr('opacity', 0.5).attr('stroke', null); });
}

build();
Result
Loading…
Data & source

Complete solution; source starter preserved in the lab files.

08Mouse events solution

JavaScript
async function build() {
  const myCircles = d3.selectAll('circle')
  const originalOpacity = 0.5
  const hoverOpacity = 0.9

  myCircles
      .style('cursor', 'pointer')

  myCircles
      .on('mouseover', mouseOver)
      .on('mouseout', mouseOut)
      .on('mousemove', mouseMove)

  const tooltip = d3.select("body").append("div")
      .attr("class", "tooltip")
      .style("opacity", 0);

  function mouseOver(event, d) {
      d3.select(this).style('opacity', hoverOpacity).attr('stroke', 'white').attr('stroke-width', 3);
      tooltip.style('opacity', 1).text('Radius: ' + this.getAttribute('r'));
      mouseMove(event);
  }

  function mouseOut(event, d) {
      d3.select(this).style('opacity', originalOpacity).attr('stroke', null);
      tooltip.style('opacity', 0);
  }

  function mouseMove(event, d) {
      tooltip.style('left', (event.pageX + 12) + 'px').style('top', (event.pageY + 12) + 'px');
  }
}

build();
Result
Loading…
Data & source

Complete solution; source starter preserved in the lab files.

09Chart tooltips solution

JavaScript
async function build() {
  const margin = { top: 20, right: 20, bottom: 20, left: 20 },
      width = 1440 - margin.left - margin.right,
      height = 1080 - margin.top - margin.bottom,
      barGroupMargin = { top: 100, right: 20, bottom: 20, left: 100 },
      barGroupWidth = 600,
      barGroupHeight = 400,
      circleGroupMargin = { top: 100, right: 20, bottom: 20, left: 200 + barGroupWidth },
      circleGroupWidth = 600,
      circleGroupHeight = 400

  const originalOpacity = 0.7, hoveredOpacity = 1

  const originalFill = "#7c70ce", hoveredFill = "#f588f0"

  const svg = d3.select("#main")
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)

  const barGroup = svg.append('g')
      .attr('transform', 'translate(' + barGroupMargin.left + ',' + barGroupMargin.top + ')')

  await d3.csv("./datasets/country-values.csv").then(function (data) {

      const x = d3.scaleBand()
          .range([0, barGroupWidth])
          .domain(data.map(d => d.Country))
          .padding(0.1);

      let yMax = d3.max(data.map(d => +d.Value))

      const y = d3.scaleLinear()
          .domain([0, yMax])
          .range([barGroupHeight, 0])
          .nice();

      let myBars = barGroup.selectAll(".myBar")
          .data(data)
          .enter()
          .append("rect")
          .attr('class', 'myBar')
          .attr("x", d => x(d.Country))
          .attr("y", d => y(d.Value))
          .attr("width", x.bandwidth())
          .attr("height", d => barGroupHeight - y(d.Value))
          .style("fill", originalFill)
          .style('opacity', originalOpacity)
          .style('cursor', 'pointer')

      // add x axis
      barGroup.append("g")
          .attr("transform", `translate(0, ${barGroupHeight})`)
          .call(d3.axisBottom(x))
          .selectAll("text")
          .attr("transform", "translate(-10,0)rotate(-45)")
          .style("text-anchor", "end");

      // add y axis
      barGroup.append("g")
          .call(d3.axisLeft(y));

      let barTooltip = d3.select("body").append("div")
          .attr("class", "tooltip")
          .style("opacity", 0)

      myBars
          .on('mouseenter', mouseEnterBar)
          .on('mouseleave', mouseLeaveBar)
          .on('mousemove', mouseMoveBar)

      function mouseEnterBar(event, d) {
      d3.select(this).style('fill', hoveredFill).style('opacity', hoveredOpacity);
      barTooltip.style('opacity', 1).html('Country: ' + d.Country + '<br>Value: ' + d.Value);
      mouseMoveBar(event);
  }

      function mouseLeaveBar(event, d) {
      d3.select(this).style('fill', originalFill).style('opacity', originalOpacity);
      barTooltip.style('opacity', 0);
  }

      function mouseMoveBar(event, d) {
      barTooltip.style('left', (event.pageX + 12) + 'px').style('top', (event.pageY + 12) + 'px');
  }
  })

  // Practice 2 Scatterplot
  await d3.csv("./datasets/housing.csv").then(function (data) {

      let filteredData = data.filter(d => d.SalePrice <= 500000)  //filter the data by SalePrice, anything above 500000 was filtered out

      const originalCircleSize = 3

      let xMax = d3.max(filteredData.map(d => +d.GrLivArea))

      const x = d3.scaleLinear()
          .domain([0, xMax])
          .range([0, circleGroupWidth])
          .nice();

      let yMax = d3.max(filteredData.map(d => +d.SalePrice))

      const y = d3.scaleLinear()
          .domain([0, yMax])
          .range([circleGroupHeight, 0])
          .nice();

      let circleGroup = svg.append('g')
          .attr('transform', 'translate(' + circleGroupMargin.left + ',' + circleGroupMargin.top + ')')

      let myCircles = circleGroup.append('g')
          .selectAll(".myCircles")
          .data(filteredData)
          .enter()
          .append("circle")
          .attr('class', 'myCircles')
          .attr("cx", d => x(d.GrLivArea))
          .attr("cy", d => y(d.SalePrice))
          .attr("r", originalCircleSize)
          .style("fill", originalFill)
          .style('opacity', originalOpacity)

      //add x axis
      circleGroup.append("g")
          .attr("transform", `translate(0, ${circleGroupHeight})`)
          .call(d3.axisBottom(x));

      //add y axis 
      circleGroup.append("g")
          .call(d3.axisLeft(y));

      //Solution  

      let circleTooltip = d3.select("body").append("div")
          .attr("class", "tooltip")
          .style("opacity", 0)

      let xLine = circleGroup.append("line")
          .style('stroke', 'white')
          .style('stroke-width', 1)
          .style("visibility", "hidden")
          .lower()

      let yLine = circleGroup.append("line")
          .style('stroke', 'white')
          .style('stroke-width', 1)
          .style("visibility", "hidden")
          .lower()

      myCircles
          .style('cursor', 'pointer')
          .on('mouseenter', mouseOverCircle)
          .on('mousemove', mouseOverCircle)
          .on('mouseleave', mouseLeaveCircle)

      function mouseOverCircle(event, d) {
      d3.select(this).attr('r', 6).style('fill', hoveredFill).style('opacity', hoveredOpacity);
      circleTooltip.style('opacity', 1)
        .html('Living area: ' + d.GrLivArea + '<br>Sale price: $' + d3.format(',')(+d.SalePrice))
        .style('left', (event.pageX + 12) + 'px').style('top', (event.pageY + 12) + 'px');
      xLine.style('visibility', 'visible').attr('x1', x(d.GrLivArea)).attr('x2', x(d.GrLivArea))
        .attr('y1', circleGroupHeight).attr('y2', y(d.SalePrice));
      yLine.style('visibility', 'visible').attr('x1', 0).attr('x2', x(d.GrLivArea))
        .attr('y1', y(d.SalePrice)).attr('y2', y(d.SalePrice));
  }

      function mouseLeaveCircle() {
      d3.select(this).attr('r', originalCircleSize).style('fill', originalFill).style('opacity', originalOpacity);
      circleTooltip.style('opacity', 0);
      xLine.style('visibility', 'hidden');
      yLine.style('visibility', 'hidden');
  }
  })
}

build();
Result
Loading…
Data & source

Complete solution; source starter preserved in the lab files.

10Donut tooltips solution

JavaScript
async function build() {
  const MARGIN = { TOP: 20, RIGHT: 150, BOTTOM: 60, LEFT: 150 },
      PADDING = { TOP: 60, RIGHT: 60, BOTTOM: 60, LEFT: 100 },
      WIDTH = 1600,
      HEIGHT = 900,
      OUTER_WIDTH = WIDTH - MARGIN.LEFT - MARGIN.RIGHT,
      OUTER_HEIGHT = HEIGHT - MARGIN.TOP - MARGIN.BOTTOM,
      INNER_WIDTH = OUTER_WIDTH - PADDING.LEFT - PADDING.RIGHT,
      INNER_HEIGHT = OUTER_HEIGHT - PADDING.TOP - PADDING.BOTTOM;

  let outerG, innerG;

  function init() {
      const svg = d3.select("div").append("svg")
          .attr("class", "chart-svg")
          .attr("width", WIDTH)
          .attr("height", HEIGHT);

      outerG = svg.append("g")
          .attr("class", "outer-group")
          .attr("transform", `translate(${MARGIN.LEFT}, ${MARGIN.TOP})`);

      innerG = outerG.append("g")
          .attr("class", "inner-group")
          .attr("transform", `translate(${PADDING.LEFT}, ${PADDING.TOP})`);

      return innerG;
  }

  await d3.csv('./examples/lab10/datasets/Olympic_Participation_Gender.csv').then(data => {
      if (!data) return;

      const svg = init();

      data = data.map(d => ({
          year: new Date(+d.Year, 0, 1),
          proportion: +d["Female Athlete Count"] / (+d["Male Athlete Count"] + +d["Female Athlete Count"]),
          female: +d["Female Athlete Count"],
          male: +d["Male Athlete Count"]
      }));

      const x = d3.scaleTime()
          .domain(d3.extent(data, d => d.year)).nice()
          .range([0, INNER_WIDTH]);

      const y = d3.scaleLinear()
          .domain([0, d3.max(data, d => d.proportion) * 1.1]).nice()
          .range([INNER_HEIGHT, 0]);

      const line = d3.line()
          .x(d => x(d.year))
          .y(d => y(d.proportion));

      svg.append("path")
          .datum(data)
          .attr("class", "female-proportion-line")
          .attr("d", line)
          .attr("fill", "none")
          .attr("stroke", "orange")
          .attr("stroke-width", 2);

      // Donut chart settings
      const donutRadius = 15;
      const arc = d3.arc()
          .innerRadius(donutRadius * 0.6)
          .outerRadius(donutRadius);
      const pie = d3.pie().sort(null).value(d => d.value);
      const tooltip = d3.select('body').append('div').attr('class', 'tooltip');

      // Add donut charts
      const donutGroups = svg.selectAll(".donut")
          .data(data)
          .enter()
          .append("g")
          .attr("class", "donut")
          .attr("transform", d => `translate(${x(d.year)}, ${y(d.proportion)})`);

      donutGroups.each(function(d) {
          const donut = d3.select(this);
          const proportionData = [{label: 'Female', value: d.female}, {label: 'Male', value: d.male}];

          donut.selectAll("path")
              .data(pie(proportionData))
              .enter()
              .append("path")
              .attr("d", arc)
              .attr("fill", (d, i) => i === 0 ? "orange" : "steelblue")
              .on('mouseenter', function (event, slice) {
                d3.select(this).attr('stroke', 'white').attr('stroke-width', 2);
                tooltip.style('opacity', 1).html(
                  d3.timeFormat('%Y')(d.year) + '<br>' + slice.data.label + ': ' +
                  d3.format(',')(slice.data.value) + '<br>Female share: ' + d3.format('.1%')(d.proportion));
              })
              .on('mousemove', event => tooltip.style('left', (event.pageX + 12) + 'px').style('top', (event.pageY + 12) + 'px'))
              .on('mouseleave', function () {
                d3.select(this).attr('stroke', null);
                tooltip.style('opacity', 0);
              }); // Female = orange, Male = steelblue
      });

      // Add X-axis
      svg.append("g")
          .attr("class", "x-axis")
          .attr("transform", `translate(0, ${INNER_HEIGHT})`)
          .call(d3.axisBottom(x).ticks(10))
          .append("text")
          .attr("class", "label x")
          .attr("x", INNER_WIDTH / 2)
          .attr("y", 100)
          .attr("fill", "white")
          .style("text-anchor", "middle")
          .text("Year");

      // Add Y-axis
      svg.append("g")
          .attr("class", "y-axis")
          .call(d3.axisLeft(y).tickFormat(d3.format(".0%")))
          .append("text")
          .attr("class", "label y")
          .attr("transform", "rotate(-90)")
          .attr("y", -100)
          .attr("x", -INNER_HEIGHT / 2)
          .attr("fill", "white")
          .style("text-anchor", "middle")
          .text("Proportion of Female Athletes");

  }).catch(error => console.error('Error loading the data:', error));
}

build();
Result
Loading…
Data & source

Complete solution; source starter preserved in the lab files.

Lab 11 · D3 Interaction II

Original lab ZIP

11Brushing and linking

JavaScript
async function build() {
  // Based on https://d3-graph-gallery.com/graph/barplot_basic.html

  const margin = { top: 30, right: 30, bottom: 70, left: 60 },
      width = 1600 - margin.left - margin.right,
      height = 1200 - margin.top - margin.bottom;

  const circleGroupHeight = 400, circleGroupWidth = 600, barChartWidth = 1000, barChartHeight = 400

  const originalCircleOpacity = 0.7, hoveredCircleOpacity = 1, originalBarOpacity = 0.9, hideBarOpacity = 0.1;
  const originalFill = "#7c70ce", hoveredFill = "#f588f0";
  const originalCircleSize = 8;

  // append the svg object to the body of the page
  const svg = d3.select("#main")
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)

  const circleGroup = svg.append('g')
      .attr('class', 'circleGroup')
      .attr('transform', 'translate(' + 150 + ',' + 50 + ')')

  const barGroup = svg.append('g')
      .attr('class', 'barGroup')
      .attr('transform', 'translate(' + 150 + ',' + 600 + ')')

  let circleBrush, barBrush  //declare these two brushes in a higher scope, so they have access to each other

  await d3.csv("./datasets/countries.csv", d => ({
      continent: d.continent,
      country: d.country,
      gdpPercap: +d.gdpPercap,
      lifeExp: +d.lifeExp,
      pop: +d.pop
  })).then(data => {

      data = data.sort((a, b) => d3.descending(a.pop, b.pop));   // sort data using population, or const sortedData = data.sort((a, b) => b.pop - a.pop);

      data = data.slice(0, 30)

      drawScatterPlot(data); // Add scatter plot
      drawBarChart(data);    // Add bar chart

  });

  function drawScatterPlot(data) {
      let xMax = d3.max(data.map(d => +d.lifeExp))

      const x_scatter = d3.scaleLinear()
          .domain([0, xMax])
          .range([0, circleGroupWidth])
          .nice();

      let yMax = d3.max(data.map(d => +d.gdpPercap))

      const y_scatter = d3.scaleLinear()
          .domain([0, yMax])
          .range([circleGroupHeight, 0])
          .nice();

      const myCircles = circleGroup
          .selectAll(".myCircles")
          .data(data)
          .enter()
          .append("circle")
          .attr('class', 'myCircles')
          .attr("cx", d => x_scatter(d.lifeExp))
          .attr("cy", d => y_scatter(d.gdpPercap))
          .attr("r", originalCircleSize)
          .attr("fill", originalFill)
          .style('opacity', 0.8)

      //add x axis
      circleGroup.append("g")
          .attr("class", "x-axis")
          .attr("transform", `translate(0, ${circleGroupHeight})`)
          .call(d3.axisBottom(x_scatter));

      //add y axis 
      circleGroup.append("g")
          .attr("class", "y-axis")
          .call(d3.axisLeft(y_scatter));

      // Add X axis label
      circleGroup.append("text")
          .attr("class", "axis-label")
          .attr("x", circleGroupWidth / 2)
          .attr("y", circleGroupHeight + 50)
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 20)
          .text("Life Expectancy");

      // Add Y axis label
      circleGroup.append("text")
          .attr("class", "axis-label")
          .attr("transform", "rotate(-90)")
          .attr("x", -barChartHeight / 2)
          .attr("y", -80)
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 20)
          .text("GDP per capita");

      //add brush for scatter plot
      circleBrush = d3.brush()
          .extent([[0, 0], [circleGroupWidth, circleGroupHeight]])
          .on('start', function (event) {
              if (!event.sourceEvent) return;
              barGroup.call(barBrush.move, null);
          })
          .on('brush end', function (event) {

              let brushedArea = event.selection

              d3.selectAll('.myCircles')
                  .classed('selected', d => isBrushed(brushedArea, x_scatter(d.lifeExp), y_scatter(d.gdpPercap)))

              //  connect with bars by country
              d3.selectAll('.myBar')
                  .classed('selected', d => isBrushed(brushedArea, x_scatter(d.lifeExp), y_scatter(d.gdpPercap)))
          })

      circleGroup.call(circleBrush) // calling a d3 brush

      myCircles.style('pointer-events', 'none').raise()

      function isBrushed(brush_coords, cx, cy) {
          if (brush_coords) {
              let x0 = brush_coords[0][0],
                  x1 = brush_coords[1][0],
                  y0 = brush_coords[0][1],
                  y1 = brush_coords[1][1];
              return x0 <= cx && cx <= x1 && y0 <= cy && cy <= y1;
          }
      }

  }

  function drawBarChart(data) {

      const xBar = d3.scaleBand()
          .range([0, barChartWidth])
          .domain(data.map(d => d.country))
          .padding(0.1);

      let yMaxBar = d3.max(data.map(d => +d.pop))

      const yBar = d3.scaleLinear()
          .domain([0, yMaxBar])
          .range([barChartHeight, 0])
          .nice();

      let myBars = barGroup.selectAll(".myBar")
          .data(data)
          .join('rect')
          .attr('class', 'myBar')
          .attr("x", d => xBar(d.country))
          .attr("y", d => yBar(d.pop))
          .attr("width", xBar.bandwidth())
          .attr("height", d => barChartHeight - yBar(d.pop))
          .attr("fill", originalFill)
          .style('cursor', 'pointer')

      // Add X axis label
      barGroup.append("text")
          .attr("class", "axis-label")
          .attr("x", barChartWidth / 2)
          .attr("y", barChartHeight + 80)  // you can also use translate
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 20)
          .text("Country");

      // Add Y axis label
      barGroup.append("text")
          .attr("class", "axis-label")
          .attr("transform", "rotate(-90)")
          .attr("x", -barChartHeight / 2)
          .attr("y", -80)
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 20)
          .text("Population");

      barGroup.append("g")
          .attr("transform", `translate(0, ${barChartHeight})`)
          .call(d3.axisBottom(xBar))
          .selectAll("text")
          .attr("transform", "translate(-10,0)rotate(-45)")
          .style("text-anchor", "end");

      const yAxis = d3.axisLeft(yBar)
          .tickFormat(d3.format(".2s"));

      barGroup.append("g")
          .call(yAxis);

      // Initialize brush functionality for the bar chart with specific dimensions.
      barBrush = d3.brushX()
          .extent([[0, 0], [barChartWidth, barChartHeight]]) // Set the brushable area size.
          .on('start', function (event) {
              if (!event.sourceEvent) return;
              // Clear existing brushes on scatter plot when starting a new brush on bar chart.
              circleGroup.call(circleBrush.move, null);
          })
          .on('brush end', function (event) {

              let brushedArea = event.selection; // Get the current brush selection coordinates.
              // Highlight circles in circle chart based on brush selection in bar chart.
              d3.selectAll('.myCircles')
                  .classed('selected', d => isBrushedX(brushedArea, xBar(d.country)));

              // Highlight bars in bar chart based on brush selection.
              d3.selectAll('.myBar')
                  .classed('selected', d => isBrushedX(brushedArea, xBar(d.country)));
          })

      // Apply the brush to the bar chart group element.
      barGroup.call(barBrush)

      // Raise the bars to ensure they are visible above other elements (if any).
      myBars.style('pointer-events', 'none').raise()

      // Define a helper function to check if an element's position falls within the brushed area.
      function isBrushedX(brush_coords, x) {
          if (brush_coords) {
              let x0 = brush_coords[0], // Start of the brushed area on x-axis.
                  x1 = brush_coords[1]; // End of the brushed area on x-axis.

              // Return true if the element's position is within the brushed area.
              return x0 <= x && x <= x1;
          }
      }

  }
}

build();
Result
Loading…
Data & source

12Transitions

JavaScript
async function build() {
  // this lab is based on https://www.d3indepth.com/transitions/

  // update without transition
  let data = [];

  function updateData() {  // create new data
      data = [];
      for (let i = 0; i < 5; i++) {
          data.push(Math.random() * 800);  //generate five random number and push them to an array
      }
  }

  function update() {

      d3.select('#svg0')
          .selectAll('.noTransitionCircle')
          .data(data)
          .join('circle')  //join the number with the circles already on the screen
          .attr('class', 'noTransitionCircle')
          .style('fill', "#7c70ce")
          .style('opacity', 0.75)
          .attr('cy', 50)
          .attr('r', 40)
          .attr('cx', d=>d);
  }

  function updateAll() {

      updateData();  
      update();     
  }

  updateAll();  

  // update with transition

  let data1 = [];

  function updateData1() {
      data1 = [];
      for (let i = 0; i < 5; i++) {
          data1.push(Math.random() * 800);  //same
      }
  }

  function update1() {

      d3.select('#svg1')
          .selectAll('.transitionCircle1')
          .data(data1)
          .join('circle')
          .attr('class', 'transitionCircle1')
          .style('fill', "#7c70ce")
          .style('opacity', 0.75)
          .attr('cy', 50)
          .attr('r', 40)
          .transition() 
          .duration(500)
          .attr('cx', d => d)
  }

  function updateAll1() {
      updateData1();
      update1();
  }

  updateAll1();

  // update with new array
  let data2 = [];

  function updateData2() {
      data2 = [];
      let numItems = Math.ceil(Math.random() * 10);
      for (let i = 0; i < numItems; i++) {
          data2.push(Math.random() * 800);
      }
  }

  function update2() {

      d3.select('#svg2')
          .selectAll('.transitionCircle2')
          .data(data2)
          .join(
              enter => enter
                  .append('circle')
                  .attr('class', 'transitionCircle2')
                  .style('fill', "#7c70ce")
                  .attr('r', 40)
                  .style('opacity', 0.75)
                  .attr('cy', 50)
                  .transition()
                  .duration(1000)
                  .attr('cx', d => d)
              ,
              update => update.transition()
                  .duration(1000)
                  .attr('cx', d => d),
              exit => exit
                  .transition()
                  .duration(1000)
                  .attr('cy', 500)
                  .remove(),
          )
  }

  function updateAll2() {
      updateData2();
      update2();
  }

  updateAll2();

  // staggered transition

  let data3 = [], side = 'right';

  function updateData3() {
      data3 = []
      side = side === 'left' ? 'right' : 'left';
      for (let i = 0; i < 10; i++) {
          data3.push(side === "left" ? 250 - i * 25 : 775 - i * 25);
      }
  }

  function update3() {

      d3.select('#svg3')
          .selectAll('.transitionCircle3')
          .data(data3)
          .join('circle')
          .attr('class', 'transitionCircle3')
          .attr('cy', 50)
          .attr('r', 40)
          .style('opacity', 0.75)
          .transition()
          .delay((d,i)=> i * 100)
          .duration(1000)
          .ease(d3.easeCubicInOut) 
          // .ease(d3.easeBounce)
          .attr('cx', d => d)
          .style('fill', side === 'left' ? "#7c70ce" : "#f588f0")
          ;
  }

  function updateAll3() {
      updateData3();
      update3();
  }

  updateAll3();

  Object.assign(window, {updateAll, updateAll1, updateAll2, updateAll3});
}

build();
Result
Loading…
Data & source

13Zoom and pan

JavaScript
async function build() {
  // Constants for the spiral calculation
  const goldenAngle = Math.PI * (3 - Math.sqrt(5)); // Golden angle in radians
  const pointRadius = 6; // Radius for each point
  const spacingBetweenPoints = pointRadius * 2; // Calculated step based on point radius

  // Select the SVG element
  const svg = d3.select('svg');

  // Retrieve the width and height attributes from the SVG element
  const width = +svg.attr('width');
  const height = +svg.attr('height');

  // Generate data for 2000 points positioned in a spiral pattern
  const data = Array.from({ length: 2000 }, (_, i) => {
    i += 0.5;
    const effectiveRadius = spacingBetweenPoints * Math.sqrt(i); // Calculate the radius from the center
    const angle = goldenAngle * i; // Calculate the angle for the current point

    const x = width / 2 + effectiveRadius * Math.cos(angle);
    const y = height / 2 + effectiveRadius * Math.sin(angle);

    return [x, y];
  });

  const g = svg.append("g");

  g.selectAll("circle")
    .data(data)
    .join("circle")
    .attr("cx", d => d[0])
    .attr("cy", d => d[1])
    .attr("r", pointRadius)
    .attr("fill", (d, i) => d3.interpolateRainbow(i / 360))
    .on("click", clicked);

  const zoom = d3.zoom()
    .scaleExtent([1, 40])
    .on("zoom", zoomed);

  function zoomed({ transform }) {
    g.attr("transform", transform); // Apply zoom transform to the group
  }

  // Function to double the current zoom level.
  function zoomIn() {
    svg.transition().call(zoom.scaleBy, 2);
  }

  // Function to halve the current zoom level.
  function zoomOut() {
    svg.transition().call(zoom.scaleBy, 0.5);
  }

  // Function to zoom into a random point in the data.
  function random() {
    const [x, y] = data[Math.floor(Math.random() * data.length)];
    svg.transition().duration(2500).call(
      zoom.transform,
      d3.zoomIdentity.translate(width / 2, height / 2).scale(40).translate(-x, -y)
    );
  }

  // Function to reset the zoom level to the initial state.
  function reset() {
    svg.transition().duration(750).call(
      zoom.transform,
      d3.zoomIdentity,
      d3.zoomTransform(svg.node()).invert([width / 2, height / 2])
    );
  }

  // Function to handle click events on points in the plot, zooming into the clicked point.
  function clicked(event, d) {
    event.stopPropagation();
    svg.transition().duration(750).call(
      zoom.transform,
      d3.zoomIdentity.translate(width / 2, height / 2).scale(40).translate(-d[0], -d[1]),
      d3.pointer(event)
    );
  }

  svg.call(zoom)

  d3.select("#zoomin-btn").on("click", zoomIn);
  d3.select("#zoomout-btn").on("click", zoomOut);
  d3.select("#random-btn").on("click", random);
  d3.select("#reset-btn").on("click", reset);
}

build();
Result
Loading…
Data & source

14Lasso selection

JavaScript
async function build() {
  await d3.csv("./datasets/movies.csv", function (d, i) {
      return {
          director_name: d.director_name,
          num_critic_for_reviews: +d.num_critic_for_reviews,
          duration: +d.duration,
          gross: +d.gross,
          genres: d.genres,
          movie_title: d.movie_title.replace(/Â/g, ''),
          num_voted_users: +d.num_voted_users,
          budget: +d.budget >= 500000000 ? 0 : +d.budget,
          title_year: +d.title_year,
          imdb_score: +d.imdb_score,
          movie_facebook_likes: +d.movie_facebook_likes,
          id: `${i}`
      };
  }).then(function (data) {
      const svg = d3.select("svg"),
          margin = { top: 20, right: 100, bottom: 70, left: 200 },
          width = +svg.attr("width") - margin.left - margin.right,
          height = +svg.attr("height") - margin.top - margin.bottom;

      const originalCircleOpacity = 0.7,
          hoveredCircleOpacity = 1,
          originalBarOpacity = 0.9,
          hideBarOpacity = 0.1,
          originalFill = "#7c70ce",
          hoveredFill = "#f588f0";
      const scatterGroup = svg.append("g")
          .attr("transform", `translate(${margin.left},${margin.top})`)
          .style('cursor', 'crosshair');

      scatterGroup.append("rect")
          .attr("width", width)
          .attr("height", height)
          .style("fill", "none") // Make it invisible
          .style("pointer-events", "all"); // Capture all mouse events

      const xAxisGroup = scatterGroup.append("g")
          .attr("class", "x-axis")
          .attr("transform", `translate(0,${height})`);

      const yAxisGroup = scatterGroup.append("g")
          .attr("class", "y-axis");

      const xAxisLabel = scatterGroup.append("text")
          .attr("class", "axis-label")
          .attr("x", width / 2)
          .attr("y", height + 50)
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 30);

      const yAxisLabel = scatterGroup.append("text")
          .attr("class", "axis-label")
          .attr("transform", "rotate(-90)")
          .attr("x", -height / 2)
          .attr("y", -120)
          .attr("dy", "1em")
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 30);

      const circleTooltip = d3.select("body").append("div")
          .attr("class", "tooltip")
          .style("opacity", 0);

      const xScale = d3.scaleLinear().range([0, width]);
      const yScale = d3.scaleLinear().range([height, 0]);

      const attributes = ["num_critic_for_reviews", "duration", "gross", "budget", "imdb_score", "movie_facebook_likes"];
      const directors = [...new Set(data.map(d => d.director_name))].sort();

      const xSelect = d3.select("#x-select"),
          ySelect = d3.select("#y-select"),
          directorSelect = d3.select("#director-select");

      attributes.forEach(attr => {
          xSelect.append("option").text(attr).attr("value", attr);
          ySelect.append("option").text(attr).attr("value", attr);
      });

      directors.forEach(director => {
          directorSelect.append("option").text(director).attr("value", director);
      });

      let xAttribute = "gross",
          yAttribute = "budget";

      xSelect.property("value", xAttribute);
      ySelect.property("value", yAttribute);

      updateScatterPlot(data, xAttribute, yAttribute);

      xSelect.on("change", function (event) {
          xAttribute = this.value;
          updateScatterPlot(data, xAttribute, yAttribute);
      });

      ySelect.on("change", function (event) {
          yAttribute = this.value;
          updateScatterPlot(data, xAttribute, yAttribute);
      });

      directorSelect.on("change", function (event) {
          const directorName = this.value
          highlightMovies(directorName)
      })

      function updateScatterPlot(data, xAttribute, yAttribute) {
          data = data.filter(d => +d[xAttribute] && +d[yAttribute]);

          xScale.domain(d3.extent(data, d => d[xAttribute])).nice();
          yScale.domain(d3.extent(data, d => d[yAttribute])).nice();

          xAxisGroup.transition().duration(500).call(d3.axisBottom(xScale).tickFormat(d3.format(".2s")));;
          yAxisGroup.transition().duration(500).call(d3.axisLeft(yScale).tickFormat(d3.format(".2s")));

          xAxisLabel.text(xAttribute);
          yAxisLabel.text(yAttribute);

          let circles = scatterGroup.selectAll(".myCircles")
              .data(data, d => d.id);

          circles.join(
              enter => enter.append("circle")
                  .attr('class', 'myCircles')
                  .attr("r", 4)
                  .attr("cx", d => xScale(+d[xAttribute]))
                  .attr("cy", d => yScale(+d[yAttribute]))
                  .style("fill", originalFill)
                  .style('opacity', originalCircleOpacity)
                  .style('cursor', 'pointer')
                  .on('mouseenter', mouseOverCircle)
                  .on('mouseleave', mouseLeaveCircle),
              update => update
                  .transition()
                  .duration(500)
                  .attr("cx", d => xScale(+d[xAttribute]))
                  .attr("cy", d => yScale(+d[yAttribute])),
              exit => exit
                  .transition()
                  .duration(500)
                  .style('opacity', 0)
                  .remove()
          );

          function mouseOverCircle(event, d) {
              circleTooltip
                  .style('opacity', 0.9)
                  .html(`Movie: ${d.movie_title} <br> ${xAttribute}: ${d[xAttribute]} <br> ${yAttribute}: ${d[yAttribute].toFixed(2)}  <br> Director: ${d.director_name}`)
                  .style("left", (event.pageX + 10) + "px")
                  .style("top", (event.pageY - 20) + "px");
              d3.selectAll(".myCircles")
                  .style('opacity', 0.1)
              d3.select(this)
                  .style('opacity', 0.9)
                  .style('stroke', '#fff')
                  .style('stroke-width', 2)
          }
          function mouseLeaveCircle() {
              circleTooltip
                  .style('opacity', 0)
              d3.selectAll('.myCircles')
                  .style('opacity', originalCircleOpacity)
                  .style('stroke', '')
          }
      }

      // Add Lasso Path (now with proper styling)
      const lassoPath = scatterGroup.append("path")
          .attr("class", "lasso-path")
          .style("stroke", "#f588f0")  // Stroke color for the lasso path
          .style("stroke-width", 2)    // Make the line thicker for visibility
          .style("fill", "rgba(245, 136, 240, 0.2)") // Fill the lasso with light opacity
          .style("opacity", 0)         // Initially hidden
          .style("pointer-events", "none");  // Avoid interfering with circle events

      let lassoPoints = [];
      let lassoActive = false;

      scatterGroup
          .on("mousedown", function (event) {

              lassoActive = true;
              lassoPoints = [d3.pointer(event, scatterGroup.node())];
              lassoPath
                  .attr("d", `M${lassoPoints[0][0]},${lassoPoints[0][1]}`)
                  .style("opacity", 1)
                  .raise(); // Bring it to the front

              // Set cursor to crosshair when drawing starts
              svg.style("cursor", "crosshair");
            
          })
          .on("mousemove", function (event) {

              if (lassoActive) {
              const point = d3.pointer(event, scatterGroup.node());
              lassoPoints.push(point);
              lassoPath
                  .attr("d", `M${lassoPoints.map(p => p.join(",")).join("L")}`)
                  .raise(); // Keep the lasso path on top

              // Temporarily disable pointer events on circles to prevent hover effects
              scatterGroup.selectAll(".myCircles")
                  .style("pointer-events", "none");
              }
          })
          .on("mouseup", function (event) {
              // Re-enable pointer events on circles after lasso selection
              scatterGroup.selectAll(".myCircles")
              .style("pointer-events", "all");
              if (lassoActive) {
                  lassoActive = false;
                  lassoPoints.push(lassoPoints[0]); // Close the path
                  highlightLassoSelection();

              }
          });

      function highlightLassoSelection() {
          const isPointInPolygon = (point, vs) => {
              let x = point[0], y = point[1];
              let inside = false;
              for (let i = 0, j = vs.length - 1; i < vs.length; j = i++) {
                  let xi = vs[i][0], yi = vs[i][1];
                  let xj = vs[j][0], yj = vs[j][1];

                  let intersect = ((yi > y) !== (yj > y)) &&
                      (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
                  if (intersect) inside = !inside;
              }
              return inside;
          };

          // Reset fill for all circles
          scatterGroup.selectAll(".myCircles")
              .style("fill", originalFill);

          // Highlight circles inside the lasso
          scatterGroup.selectAll(".myCircles")
              .filter(d => {
                  const point = [xScale(d[xAttribute]), yScale(d[yAttribute])];
                  return isPointInPolygon(point, lassoPoints);
              })
              .style("fill", "gold")
              .raise(); 
      }

      function highlightMovies(directorName) {
          d3.selectAll('.myCircles')
              .each(function (d) {
                  if (directorName === "all") {
                      d3.select(this).style('fill', originalFill);
                  } else {
                      if (d.director_name === directorName) {
                          d3.select(this)
                              .style('fill', 'gold')
                              .raise();
                      } else {
                          d3.select(this).style('fill', originalFill);
                      }
                  }
              });
      }
  })
}

build();
Result
Loading…
Data & source

15Brush reconfiguration solution

JavaScript
async function build() {
  // Based on https://d3-graph-gallery.com/graph/barplot_basic.html

  const margin = { top: 30, right: 30, bottom: 70, left: 60 },
      width = 1600 - margin.left - margin.right,
      height = 1000 - margin.top - margin.bottom;

  const circleGroupHeight = 400, circleGroupWidth = 600, originalCircleSize = 6, barChartWidth = 600, barChartHeight = 400

  const originalFill = "#7c70ce", hoveredFill = "#f588f0";

  // append the svg object to the body of the page
  const svg = d3.select("#main")
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)

  const circleGroup = svg.append('g')
      .attr('class', 'circleGroup')
      .attr('transform', 'translate(' + 150 + ',' + 100 + ')')

  const barGroup = svg.append('g')
      .attr('class', 'barGroup')
      .attr('transform', 'translate(' + 850 + ',' + 100 + ')')

  let circleBrush, barBrush  //declare these two brushes in a higher scope, so they have access to each other

  await d3.csv("./datasets/countries.csv", d => ({
      continent: d.continent,
      country: d.country,
      gdpPercap: +d.gdpPercap,
      lifeExp: +d.lifeExp,
      pop: +d.pop
  })).then(data => {

      drawScatterPlot(data); // Add scatter plot
      drawBarChart(data);    // Add bar chart

  });

  function drawScatterPlot(data) {
      let xMax = d3.max(data.map(d => +d.lifeExp))

      const x_scatter = d3.scaleLinear()
          .domain([0, xMax])
          .range([0, circleGroupWidth])
          .nice();

      let yMax = d3.max(data.map(d => +d.gdpPercap))

      const y_scatter = d3.scaleLinear()
          .domain([0, yMax])
          .range([circleGroupHeight, 0])
          .nice();

      const myCircles = circleGroup
          .selectAll(".myCircles")
          .data(data)
          .enter()
          .append("circle")
          .attr('class', 'myCircles')
          .attr("cx", d => x_scatter(d.lifeExp))
          .attr("cy", d => y_scatter(d.gdpPercap))
          .attr("r", originalCircleSize)
          .attr("fill", originalFill)
          .style('opacity', 0.8)

      //add x axis
      circleGroup.append("g")
          .attr("transform", `translate(0, ${circleGroupHeight})`)
          .call(d3.axisBottom(x_scatter));

      //add y axis 
      circleGroup.append("g")
          .call(d3.axisLeft(y_scatter));

      //add brush for scatter plot
      circleBrush = d3.brush().extent([[0, 0], [circleGroupWidth, circleGroupHeight]])
          .on('end', function (event) {

              let brushedArea = event.selection
              d3.selectAll('.myCircles')
                  .classed('selected', d => isBrushed(brushedArea, x_scatter(d.lifeExp), y_scatter(d.gdpPercap)))

              let newBarData = brushedArea ? data.filter(d => isBrushed(brushedArea, x_scatter(d.lifeExp), y_scatter(d.gdpPercap))) : data
              // console.log('newBarData::: ', newBarData);
              drawBarChart(newBarData)
          })
      circleGroup.call(circleBrush) // calling a d3 brush
      myCircles.style('pointer-events', 'none').raise()

      function isBrushed(brush_coords, cx, cy) {
          if (brush_coords) {
              var x0 = brush_coords[0][0],
                  x1 = brush_coords[1][0],
                  y0 = brush_coords[0][1],
                  y1 = brush_coords[1][1];
              return x0 <= cx && cx <= x1 && y0 <= cy && cy <= y1;
          }
      }

  }

  function drawBarChart(newData) {

      barGroup.selectAll('*').remove()

      let continentData = d3.rollups(newData, v => d3.mean(v, d => d.lifeExp), d => d.continent)
      // console.log('continentData::: ', continentData);

      const xBar = d3.scaleBand()
          .range([0, barChartWidth])
          .domain(continentData.map(d => d[0]))
          .padding(0.5);

      let yMaxBar = d3.max(continentData, d => +d[1]) || 1

      const yBar = d3.scaleLinear()
          .domain([0, yMaxBar])
          .range([barChartHeight, 0]);

      let xAxis = barGroup.append("g")
          .attr("transform", `translate(0, ${barChartHeight})`)
          .call(d3.axisBottom(xBar))

      // add y axis

      let yAxis = barGroup.append("g")
          .call(d3.axisLeft(yBar));

      xBar.domain(continentData.map(d => d[0]))

      yBar.domain([0, yMaxBar])

      let myBars = barGroup.selectAll(".myBar")
          .data(continentData)
          .join('rect')
          .attr('class', 'myBar')
          .style('cursor', 'pointer')
          // .transition()
          // .duration(1000)
          .attr("x", d => xBar(d[0]))
          .attr("y", d => yBar(d[1]))
          .attr("width", xBar.bandwidth())
          .attr("height", d => barChartHeight - yBar(d[1]))
          .attr("fill", originalFill)

      xAxis.call(d3.axisBottom(xBar))
          .selectAll("text")
          .attr("transform", "translate(-10,0)rotate(-45)")
          .style("text-anchor", "end")
          .attr('font-size', 15);

      // add y axis

      yAxis.call(d3.axisLeft(yBar));

      barGroup.append('rect')
          .attr('id', 'addOnBar')
          .attr('x', 0)
          .attr("y", 0)
          .attr('width', 20)
          .attr("height", 0)
          .attr("fill", "#0aa0f6")
          .style('visibility', 'hidden')

  }
}

build();
Result
Loading…
Data & source

Uses the supplied solution.js, adapted to the editor and bundled data.

16Animated reconfiguration solution

JavaScript
async function build() {
  await d3.csv("./datasets/movies.csv", function (d, i) {
      // Preprocessing data
      return {
          director_name: d.director_name,
          num_critic_for_reviews: +d.num_critic_for_reviews,
          duration: +d.duration,
          gross: +d.gross,
          genres: d.genres,
          movie_title: d.movie_title.replace(/Â/g, ''),
          num_voted_users: +d.num_voted_users,
          budget: +d.budget >= 500000000 ? 0 : +d.budget,
          title_year: +d.title_year,
          imdb_score: +d.imdb_score,
          movie_facebook_likes: +d.movie_facebook_likes,
          id: `${i}`
      };
  }).then(function (data) {

      const svg = d3.select("svg"),
          margin = { top: 20, right: 100, bottom: 70, left: 200 },
          width = +svg.attr("width") - margin.left - margin.right,
          height = +svg.attr("height") - margin.top - margin.bottom;

      const originalCircleOpacity = 0.7,
          hoveredCircleOpacity = 1,
          originalBarOpacity = 0.9,
          hideBarOpacity = 0.1,
          originalFill = "#7c70ce",
          hoveredFill = "#f588f0";

      // Append scatter plot group
      const scatterGroup = svg.append("g")
          .attr("transform", `translate(${margin.left},${margin.top})`);

      // Append X and Y axis groups once
      const xAxisGroup = scatterGroup.append("g")
          .attr("class", "x-axis")
          .attr("transform", `translate(0,${height})`);

      const yAxisGroup = scatterGroup.append("g")
          .attr("class", "y-axis");

      // Append axis labels once
      const xAxisLabel = scatterGroup.append("text")
          .attr("class", "axis-label")
          .attr("x", width / 2)
          .attr("y", height + 50)
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 30);

      const yAxisLabel = scatterGroup.append("text")
          .attr("class", "axis-label")
          .attr("transform", "rotate(-90)")
          .attr("x", -height / 2)
          .attr("y", -120)
          .attr("dy", "1em")
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 30);

      // Tooltip for hover info
      const circleTooltip = d3.select("body").append("div")
          .attr("class", "tooltip")
          .style("opacity", 0);

      // Define scales - These will be updated in the updateScatterPlot function
      const xScale = d3.scaleLinear().range([0, width]);
      const yScale = d3.scaleLinear().range([height, 0]);

      const attributes = ["num_critic_for_reviews", "duration", "gross", "budget", "imdb_score", "movie_facebook_likes"];
      const directors = [...new Set(data.map(d => d.director_name))].sort();

      const xSelect = d3.select("#x-select"),
          ySelect = d3.select("#y-select"),
          directorSelect = d3.select("#director-select");

      attributes.forEach(attr => {
          // Append a new option to the xSelect dropdown with the current attribute as both its visible text and value

          xSelect.append("option").text(attr).attr("value", attr);
          ySelect.append("option").text(attr).attr("value", attr);
      });

      directors.forEach(director => {
          directorSelect.append("option").text(director).attr("value", director);
      });
      // Initial plot configuration
      let xAttribute = "gross",  // initial x attribute
          yAttribute = "budget"; // initial y attribute

      // Set initial values for dropdowns
      xSelect.property("value", xAttribute);
      ySelect.property("value", yAttribute);

      // Function to update scatter plot 
      updateScatterPlot(data, xAttribute, yAttribute);
      // Event listener for dropdown changes
      xSelect.on("change", function (event) {
          xAttribute = this.value;
          updateScatterPlot(data, xAttribute, yAttribute);
      });

      ySelect.on("change", function (event) {
          yAttribute = this.value;
          updateScatterPlot(data, xAttribute, yAttribute);
      });

      directorSelect.on("change", function (event) {
          const directorName = this.value
          highlightMovies(directorName)
      })

      function updateScatterPlot(data, xAttribute, yAttribute) {

          // Filter data to ensure both x and y attributes are numeric and not null
          data = data.filter(d => +d[xAttribute] && +d[yAttribute]);

          xScale.domain(d3.extent(data, d => +d[xAttribute])).nice();
          yScale.domain(d3.extent(data, d => +d[yAttribute])).nice();

          xAxisGroup.transition().duration(500).call(d3.axisBottom(xScale).tickFormat(d3.format(".2s")));;
          yAxisGroup.transition().duration(500).call(d3.axisLeft(yScale).tickFormat(d3.format(".2s")));

          xAxisLabel.text(xAttribute);
          yAxisLabel.text(yAttribute);

          let circles = scatterGroup.selectAll(".myCircles")
              .data(data, d => d.id);

          circles.join(
              // Enter selection: append new circles for new data
              enter => enter.append("circle")
                  .attr('class', 'myCircles')
                  .attr("r", 4)
                  .attr("cx", d => xScale(+d[xAttribute])) // Initial position set immediately
                  .attr("cy", d => yScale(+d[yAttribute]))
                  .style("fill", originalFill)
                  .style('opacity', originalCircleOpacity)
                  .style('cursor', 'pointer')
                  .on('mouseenter', mouseOverCircle)
                  .on('mouseleave', mouseLeaveCircle),
              // Update selection: Apply immediate changes and transition position
              update => update
                  .transition()
                  .duration(500) // Duration in milliseconds
                  .attr("cx", d => xScale(+d[xAttribute]))
                  .attr("cy", d => yScale(+d[yAttribute])),
              // Exit selection: remove circles that no longer have data bound
              exit => exit
                  .transition() // Transition opacity for smooth fading
                  .duration(500)
                  .style('opacity', 0) // Fade to transparent
                  .remove() // Then remove from the DOM
          );

          function mouseOverCircle(event, d) {
              // tooltip
              circleTooltip
                  .style('opacity', 0.9)
                  .html(`Movie: ${d.movie_title} <br> ${xAttribute}: ${d[xAttribute]} <br> ${yAttribute}: ${d[yAttribute].toFixed(2)}  <br> Director: ${d.director_name}`)
                  .style("left", (event.pageX + 10) + "px")
                  .style("top", (event.pageY - 20) + "px");
              //highlighting
              d3.selectAll(".myCircles")
                  .style('opacity', 0.1)
              d3.select(this)
                  .style('opacity', 0.9)
                  // .attr('r', 8)
                  .style('stroke', '#fff')
                  .style('stroke-width', 2)

          }
          function mouseLeaveCircle() {
              circleTooltip
                  .style('opacity', 0)
              d3.selectAll('.myCircles')
                  .style('opacity', originalCircleOpacity)
                  .style('stroke', '')

          }

      }

      function highlightMovies(directorName) {
          d3.selectAll('.myCircles')
              .each(function (d) { // Use .each to iterate over each circle
                  if (directorName === "all") {
                      d3.select(this).style('fill', originalFill); // Reset fill color for "all"
                  } else {
                      // Check if the current circle's director matches the selected director
                      if (d.director_name === directorName) {
                          d3.select(this)
                              .style('fill', 'gold') // Highlight in gold
                              .raise(); // Bring to the front
                      } else {
                          d3.select(this).style('fill', originalFill); // Use original fill for others
                      }
                  }
              });
      }

  })
}

build();
Result
Loading…
Data & source

Uses the supplied solution.js, adapted to the editor and bundled data.

17Zoomable scatterplot solution

JavaScript
async function build() {
  await d3.csv("./datasets/movies.csv", function (d, i) {
      // Preprocessing data
      return {
          director_name: d.director_name,
          num_critic_for_reviews: +d.num_critic_for_reviews,
          duration: +d.duration,
          gross: +d.gross,
          genres: d.genres,
          movie_title: d.movie_title.replace(/Â/g, ''),
          num_voted_users: +d.num_voted_users,
          budget: +d.budget >= 500000000 ? 0 : +d.budget,
          title_year: +d.title_year,
          imdb_score: +d.imdb_score,
          movie_facebook_likes: +d.movie_facebook_likes,
          id: `${i}`
      };
  }).then(function (data) {

      const svg = d3.select("svg"),
          margin = { top: 20, right: 100, bottom: 70, left: 150 },
          width = +svg.attr("width") - margin.left - margin.right,
          height = +svg.attr("height") - margin.top - margin.bottom;

      const originalCircleOpacity = 0.7,
          hoveredCircleOpacity = 1,
          originalBarOpacity = 0.9,
          hideBarOpacity = 0.1,
          originalFill = "#7c70ce",
          hoveredFill = "#f588f0",
          originalRadius = 5;

      // Append scatter plot group
      const scatterGroup = svg.append("g")
          .attr("transform", `translate(${margin.left},${margin.top})`)

      // Append X and Y axis groups once
      const xAxisGroup = scatterGroup.append("g")
          .attr("class", "x-axis")
          .attr("transform", `translate(0,${height})`);

      const yAxisGroup = scatterGroup.append("g")
          .attr("class", "y-axis");

      // Append axis labels once
      const xAxisLabel = scatterGroup.append("text")
          .attr("class", "axis-label")
          .attr("x", width / 2)
          .attr("y", height + 50)
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 30);

      const yAxisLabel = scatterGroup.append("text")
          .attr("class", "axis-label")
          .attr("transform", "rotate(-90)")
          .attr("x", -height / 2)
          .attr("y", -120)
          .attr("dy", "1em")
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 30);

      // Tooltip for hover info
      const circleTooltip = d3.select("body").append("div")
          .attr("class", "tooltip")
          .style("opacity", 0);

      let xAttribute = "gross",  // initial x attribute
          yAttribute = "budget"; // initial y attribute

      data = data.filter(d => +d[xAttribute] && +d[yAttribute]);

      // Define scales - These will be updated in the updateScatterPlot function
      const xScale = d3.scaleLinear().range([0, width]).domain(d3.extent(data, d => d[xAttribute])).nice();
      const yScale = d3.scaleLinear().range([height, 0]).domain(d3.extent(data, d => d[yAttribute])).nice();

      xAxisGroup.call(d3.axisBottom(xScale).tickFormat(d3.format(".2s")));
      yAxisGroup.call(d3.axisLeft(yScale).tickFormat(d3.format(".2s")));

      xAxisLabel.text(xAttribute);
      yAxisLabel.text(yAttribute);

      let circles = scatterGroup.selectAll(".myCircles")
          .data(data, d => d.id);

      circles.join("circle")
          .attr('class', 'myCircles')
          .attr("r", originalRadius)
          .attr("cx", d => xScale(+d[xAttribute])) // Initial position set immediately
          .attr("cy", d => yScale(+d[yAttribute]))
          .style("fill", originalFill)
          .style('opacity', originalCircleOpacity)
          .style('cursor', 'pointer')
          .on('mouseenter', mouseOverCircle)
          .on('mouseleave', mouseLeaveCircle)
          .on('click', clicked)
      /* -------------------------------------------------------------------------- */
      /*                                 Zoom starts                                */
      /* -------------------------------------------------------------------------- */
      const zoom = d3.zoom()
          .scaleExtent([1, 32])
          .on("zoom", zoomed);

      svg.call(zoom)

      function zoomed(event) {
          const transform = event.transform;
          // Create new scales transformed by the zoom event
          const newXScale = transform.rescaleX(xScale);
          const newYScale = transform.rescaleY(yScale);
          // Apply the new scales to the axes
          xAxisGroup.call(d3.axisBottom(newXScale).tickFormat(d3.format(".2s")));
          yAxisGroup.call(d3.axisLeft(newYScale).tickFormat(d3.format(".2s")));
          // Update the positions of the circles using the new scales
          scatterGroup.selectAll(".myCircles")
              .attr("cx", d => newXScale(+d[xAttribute]))
              .attr("cy", d => newYScale(+d[yAttribute]))
              .attr('r', originalRadius * Math.sqrt(transform.k))
              .style("visibility", function (d) {
                  return newXScale(+d[xAttribute]) >= 0 && newXScale(+d[xAttribute]) <= width &&
                      newYScale(+d[yAttribute]) >= 0 && newYScale(+d[yAttribute]) <= height ? 'visible' : "hidden";
              });;
      }

      function zoomIn() {
          svg.transition().call(zoom.scaleBy, 2)
      }

      function zoomOut() {
          svg.transition().call(zoom.scaleBy, 0.5)
      }

      function random() {

          const point = data[Math.floor(Math.random() * data.length)]
          const [x, y] = [xScale(+point[xAttribute]), yScale(+point[yAttribute])]

          svg.transition().duration(2500).call(
              zoom.transform,
              d3.zoomIdentity.translate(width / 2, height / 2).scale(16).translate(-x, -y)
          );
      }

      function reset() {
          d3.selectAll('.myCircles')
              .style('stroke', '')

          svg.transition().duration(750).call(
              zoom.transform,
              d3.zoomIdentity,
              d3.zoomTransform(svg.node()).invert([width / 2, height / 2])
          );
      }
      function clicked(event, d) {

          const x = xScale(d[xAttribute])
          const y = yScale(d[yAttribute])

          event.stopPropagation();
          svg.transition().duration(750).call(
              zoom.transform,
              d3.zoomIdentity.translate(width / 2, height / 2).scale(16).translate(-x, -y),
              d3.pointer(event)
          );
      }
      d3.select("#zoomin-btn").on("click", zoomIn);
      d3.select("#zoomout-btn").on("click", zoomOut);
      d3.select("#random-btn").on("click", random);
      d3.select("#reset-btn").on("click", reset);

      function mouseOverCircle(event, d) {
          // tooltip
          circleTooltip
              .style('opacity', 0.9)
              .html(`Movie: ${d.movie_title} <br> ${xAttribute}: ${d[xAttribute]} <br> ${yAttribute}: ${d[yAttribute].toFixed(2)}  <br> Director: ${d.director_name}`)
              .style("left", (event.pageX + 10) + "px")
              .style("top", (event.pageY - 20) + "px");

          d3.select(this)
              // .attr('r', 8)
              .style('stroke', '#fff')
              .style('stroke-width', 2)

      }
      function mouseLeaveCircle() {
          circleTooltip
              .style('opacity', 0)
          d3.selectAll('.myCircles')
              .style('opacity', originalCircleOpacity)
              .style('stroke', '')

      }
  })
}

build();
Result
Loading…
Data & source

Uses the supplied solution.js, adapted to the editor and bundled data.

18Lasso reconfiguration solution

JavaScript
async function build() {
  await d3.csv("./datasets/movies.csv", function (d, i) {
      return {
          director_name: d.director_name,
          num_critic_for_reviews: +d.num_critic_for_reviews,
          duration: +d.duration,
          gross: +d.gross,
          genres: d.genres,
          movie_title: d.movie_title.replace(/Â/g, ''),
          num_voted_users: +d.num_voted_users,
          budget: +d.budget >= 500000000 ? 0 : +d.budget,
          title_year: +d.title_year,
          imdb_score: +d.imdb_score,
          movie_facebook_likes: +d.movie_facebook_likes,
          id: `${i}`
      };
  }).then(function (rawdata) {

      const data = Array.from(new Map(rawdata.map(item => [item.movie_title, item])).values());

      const svg = d3.select("svg"),
          margin = { top: 20, right: 500, bottom: 200, left: 200 },
          width = +svg.attr("width") - margin.left - margin.right,
          height = +svg.attr("height") - margin.top - margin.bottom;

      const originalCircleOpacity = 0.7,
          hoveredCircleOpacity = 1,
          originalBarOpacity = 0.9,
          hideBarOpacity = 0.1,
          originalFill = "#7c70ce",
          hoveredFill = "#f588f0";
      const scatterGroup = svg.append("g")
          .attr("transform", `translate(${margin.left},${margin.top})`)
          .style('cursor', 'crosshair');

      scatterGroup.append("rect")
          .attr("width", width)
          .attr("height", height)
          .style("fill", "none") // Make it invisible
          .style("pointer-events", "all"); // Capture all mouse events

      const xAxisGroup = scatterGroup.append("g")
          .attr("class", "x-axis")
          .attr("transform", `translate(0,${height})`);

      const yAxisGroup = scatterGroup.append("g")
          .attr("class", "y-axis");

      const xAxisLabel = scatterGroup.append("text")
          .attr("class", "axis-label")
          .attr("x", width / 2)
          .attr("y", height + 50)
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 30);

      const yAxisLabel = scatterGroup.append("text")
          .attr("class", "axis-label")
          .attr("transform", "rotate(-90)")
          .attr("x", -height / 2)
          .attr("y", -120)
          .attr("dy", "1em")
          .style("text-anchor", "middle")
          .attr('fill', 'white')
          .attr('font-size', 30);

      const circleTooltip = d3.select("body").append("div")
          .attr("class", "tooltip")
          .style("opacity", 0);

      const xScale = d3.scaleLinear().range([0, width]);
      const yScale = d3.scaleLinear().range([height, 0]);

      const attributes = ["num_critic_for_reviews", "duration", "gross", "budget", "imdb_score", "movie_facebook_likes"];
      const directors = [...new Set(data.map(d => d.director_name))].sort();

      const xSelect = d3.select("#x-select"),
          ySelect = d3.select("#y-select"),
          directorSelect = d3.select("#director-select");

      attributes.forEach(attr => {
          xSelect.append("option").text(attr).attr("value", attr);
          ySelect.append("option").text(attr).attr("value", attr);
      });

      directors.forEach(director => {
          directorSelect.append("option").text(director).attr("value", director);
      });

      let xAttribute = "gross",
          yAttribute = "budget";

      xSelect.property("value", xAttribute);
      ySelect.property("value", yAttribute);

      updateScatterPlot(data, xAttribute, yAttribute);

      xSelect.on("change", function (event) {
          xAttribute = this.value;
          updateScatterPlot(data, xAttribute, yAttribute);
      });

      ySelect.on("change", function (event) {
          yAttribute = this.value;
          updateScatterPlot(data, xAttribute, yAttribute);
      });

      directorSelect.on("change", function (event) {
          const directorName = this.value
          highlightMovies(directorName)
      })

      function updateScatterPlot(data, xAttribute, yAttribute) {
          data = data.filter(d => +d[xAttribute] && +d[yAttribute]);

          xScale.domain(d3.extent(data, d => d[xAttribute])).nice();
          yScale.domain(d3.extent(data, d => d[yAttribute])).nice();

          xAxisGroup.transition().duration(500).call(d3.axisBottom(xScale).tickFormat(d3.format(".2s")));;
          yAxisGroup.transition().duration(500).call(d3.axisLeft(yScale).tickFormat(d3.format(".2s")));

          xAxisLabel.text(xAttribute);
          yAxisLabel.text(yAttribute);

          let circles = scatterGroup.selectAll(".myCircles")
              .data(data, d => d.id);

          circles.join(
              enter => enter.append("circle")
                  .attr('class', 'myCircles')
                  .attr("r", 4)
                  .attr("cx", d => xScale(+d[xAttribute]))
                  .attr("cy", d => yScale(+d[yAttribute]))
                  .style("fill", originalFill)
                  .style('opacity', originalCircleOpacity)
                  .style('cursor', 'pointer')
                  .on('mouseenter', mouseOverCircle)
                  .on('mouseleave', mouseLeaveCircle),
              update => update
                  .transition()
                  .duration(500)
                  .attr("cx", d => xScale(+d[xAttribute]))
                  .attr("cy", d => yScale(+d[yAttribute])),
              exit => exit
                  .transition()
                  .duration(500)
                  .style('opacity', 0)
                  .remove()
          );

          function mouseOverCircle(event, d) {
              circleTooltip
                  .style('opacity', 0.9)
                  .html(`Movie: ${d.movie_title} <br> ${xAttribute}: ${d[xAttribute]} <br> ${yAttribute}: ${d[yAttribute].toFixed(2)}  <br> Director: ${d.director_name}`)
                  .style("left", (event.pageX + 10) + "px")
                  .style("top", (event.pageY - 20) + "px");
              d3.selectAll(".myCircles")
                  .style('opacity', 0.1)
              d3.select(this)
                  .style('opacity', 0.9)
                  .style('stroke', '#fff')
                  .style('stroke-width', 2)
          }
          function mouseLeaveCircle() {
              circleTooltip
                  .style('opacity', 0)
              d3.selectAll('.myCircles')
                  .style('opacity', originalCircleOpacity)
                  .style('stroke', '')
          }
      }

      // Add Lasso Path (now with proper styling)
      const lassoPath = scatterGroup.append("path")
          .attr("class", "lasso-path")
          .style("stroke", "#f588f0")  // Stroke color for the lasso path
          .style("stroke-width", 2)    // Make the line thicker for visibility
          .style("fill", "rgba(245, 136, 240, 0.2)") // Fill the lasso with light opacity
          .style("opacity", 0)         // Initially hidden
          .style("pointer-events", "none");  // Avoid interfering with circle events

      let lassoPoints = [];
      let lassoActive = false;

      scatterGroup
          .on("mousedown", function (event) {
              lassoActive = true;
              lassoPoints = [d3.pointer(event, scatterGroup.node())];
              lassoPath
                  .attr("d", `M${lassoPoints[0][0]},${lassoPoints[0][1]}`)
                  .style("opacity", 1)
                  .style("fill", "rgba(245, 136, 240, 0.2)")
                  .raise(); // Bring it to the front

              // Set cursor to crosshair when drawing starts
              svg.style("cursor", "crosshair");

          })
          .on("mousemove", function (event) {
              if (lassoActive) {
                  const point = d3.pointer(event, scatterGroup.node());
                  lassoPoints.push(point);
                  lassoPath
                      .attr("d", `M${lassoPoints.map(p => p.join(",")).join("L")}`)
                      .raise(); // Keep the lasso path on top

                  // Temporarily disable pointer events on circles to prevent hover effects
                  scatterGroup.selectAll(".myCircles")
                      .style("pointer-events", "none");
              }
          })
          .on("mouseup", function (event) {
              // Re-enable pointer events on circles after lasso selection
              scatterGroup.selectAll(".myCircles")
                  .style("pointer-events", "all");
              if (lassoActive) {
                  lassoActive = false;
                  lassoPoints.push(lassoPoints[0]); // Close the path
                  highlightLassoSelection();

              }
          });

      function highlightLassoSelection() {
          const isPointInPolygon = (point, vs) => {
              let x = point[0], y = point[1];
              let inside = false;
              for (let i = 0, j = vs.length - 1; i < vs.length; j = i++) {
                  let xi = vs[i][0], yi = vs[i][1];
                  let xj = vs[j][0], yj = vs[j][1];

                  let intersect = ((yi > y) !== (yj > y)) &&
                      (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
                  if (intersect) inside = !inside;
              }
              return inside;
          };

          // Reset fill for all circles
          scatterGroup.selectAll(".myCircles")
              .style("fill", originalFill);

          // Highlight circles inside the lasso
          const selectedCircles = scatterGroup.selectAll(".myCircles")
              .filter(d => {
                  const point = [xScale(d[xAttribute]), yScale(d[yAttribute])];
                  return isPointInPolygon(point, lassoPoints);
              });

          selectedCircles
              .style("fill", "gold")
              .raise();

          // Get the data of selected circles
          const selectedData = selectedCircles.data();

          if (selectedData.length > 0) {
              changeLassoFill(selectedData);
              updateBarChart(selectedData);
              d3.selectAll(".avg-imdb-score").style('visibility', 'visible');
              d3.select('.bar-group').style('visibility', 'visible');
          }
          else {
              d3.selectAll(".avg-imdb-score").style('visibility', 'hidden');
              d3.select('.bar-group').style('visibility', 'hidden');
          }
      }

      function changeLassoFill(selectedData) {
          const imdbScores = selectedData.map(d => d.imdb_score);
          const avgImdbScore = d3.mean(imdbScores);

          const colorScale = d3.scaleSequential(d3.interpolateBuGn)
              .domain([5, 10]);

          lassoPath
              .style("fill", colorScale(avgImdbScore))
              .style("opacity", 1);

          // Add text near the lasso area to display the average IMDb score
          scatterGroup.selectAll(".avg-imdb-score").remove(); // Remove any existing text
          const lassoCentroid = d3.polygonCentroid(lassoPoints);
          scatterGroup.append("text")
              .attr("class", "avg-imdb-score")
              .attr("x", lassoCentroid[0])
              .attr("y", lassoCentroid[1])
              .attr("fill", "white")
              .attr("font-size", 14)
              .attr("text-anchor", "middle")
              .text(`Avg IMDb Score: ${avgImdbScore.toFixed(2)}`);
      }

      const barGroup = scatterGroup.append("g")
          .attr("class", "bar-group")

      function updateBarChart(selectedData) {
          const directorCounts = d3.rollup(selectedData, v => v.length, d => d.director_name);
          const directors = Array.from(directorCounts.keys());
          const counts = Array.from(directorCounts.values());

          const barMargin = { top: 20, right: 30, bottom: 40, left: 100 };
          const barWidth = 300;
          const barHeight = 300 - barMargin.top - barMargin.bottom;

          const xBarScale = d3.scaleLinear()
              .domain([0, d3.max(counts)])
              .range([0, barWidth]);

          const yBarScale = d3.scaleBand()
              .domain(directors)
              .range([0, barHeight])
              .padding(0.1);

          const lassoCentroid = d3.polygonCentroid(lassoPoints);
          const lassoBottom = d3.max(lassoPoints, p => p[1]);

          barGroup.transition().duration(1000).attr("transform", `translate(${Math.max(110, Math.min(width - barWidth, lassoCentroid[0]))},${Math.max(0, Math.min(height - barHeight - 45, lassoBottom + 20))})`);

          barGroup.selectAll(".x-axis").remove();
          barGroup.selectAll(".y-axis").remove();

          let bars = barGroup.selectAll(".bar")
              .data(directorCounts, d => d[0]);

          bars.join(
              enter => enter.append("rect")
                  .attr("class", "bar")
                  .attr("y", d => yBarScale(d[0]))
                  .attr("height", yBarScale.bandwidth())
                  .attr("x", 0)
                  .attr("width", 0)
                  .style("fill", originalFill)
                  .transition()
                  .duration(500)
                  .attr("width", d => xBarScale(d[1])),
              update => update
                  .transition()
                  .duration(500)
                  .attr("y", d => yBarScale(d[0]))
                  .attr("height", yBarScale.bandwidth())
                  .attr("x", 0)
                  .attr("width", d => xBarScale(d[1])),
              exit => exit
                  .transition()
                  .duration(500)
                  .attr("width", 0)
                  .remove()
          );

          // Add new axes
          barGroup.append("g")
              .attr("class", "x-axis")
              .attr("transform", `translate(0,${barHeight})`)
              .call(d3.axisBottom(xBarScale).ticks(5));

          barGroup.append("g")
              .attr("class", "y-axis")
              .call(d3.axisLeft(yBarScale));
      }

      function highlightMovies(directorName) {
          d3.selectAll('.myCircles')
              .each(function (d) {
                  if (directorName === "all") {
                      d3.select(this).style('fill', originalFill);
                  } else {
                      if (d.director_name === directorName) {
                          d3.select(this)
                              .style('fill', 'gold')
                              .raise();
                      } else {
                          d3.select(this).style('fill', originalFill);
                      }
                  }
              });
      }
  })
}

build();
Result
Loading…
Data & source

Uses the supplied solution.js, adapted to the editor and bundled data.