Home Web Front-end JS Tutorial Ds in action: advanced data visualization techniques and examples

Ds in action: advanced data visualization techniques and examples

Dec 30, 2024 am 07:11 AM

Ds in action: advanced data visualization techniques and examples

Basics

First, we need an HTML file to import the D3.js library and prepare a canvas to place our chart.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Getting Started with D3.js Example</title>
  <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
  <svg width="500" height="500"></svg>
</body>
</html>
Copy after login

Create a simple line graph

// Assume we have the following data
var data = [4, 8, 15, 16, 23, 42];

// Create an SVG canvas
var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom;

// Create x and y scales
var x = d3.scaleLinear()
    .domain(d3.extent(data, d => d))
    .range([0, width]);

var y = d3.scaleLinear()
    .domain([0, d3.max(data)])
    .range([height, 0]);

// Create the x and y axes
var xAxis = d3.axisBottom(x),
    yAxis = d3.axisLeft(y);

// Add axis
svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

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

// Draw the polyline
var line = d3.line()
    .x(d => x(d))
    .y(d => y(d));

svg.append("path")
    .datum(data)
    .attr("class", "line")
    .attr("d", line);
Copy after login

Creating a Bar Chart

// Suppose we have the following data
var data = [4, 8, 15, 16, 23, 42];

// Creating the SVG canvas and scale
var svg = d3.select("svg").attr("width", 500).attr("height", 500);
var margin = {top: 20, right: 20, bottom: 30, left: 40};
var width = +svg.attr("width") - margin.left - margin.right;
var height = +svg.attr("height") - margin.top - margin.bottom;
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1);
var y = d3.scaleLinear().rangeRound([height, 0]);

// Mapping data to scale
x.domain(data.map(function(d) { return d; }));
y.domain([0, d3.max(data)]);

// Creating an SVG g Element
var g = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// Adding x and y axes
g.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

g.append("g")
    .call(d3.axisLeft(y));

// Draw a bar chart
g.selectAll(".bar")
    .data(data)
    .enter().append("rect")
    .attr("class", "bar")
    .attr("x", function(d) { return x(d); })
    .attr("y", function(d) { return y(d); })
    .attr("width", x.bandwidth())
    .attr("height", function(d) { return height - y(d); });
Copy after login

Create a pie chart

// Suppose we have the following data
var data = [4, 8, 15, 16, 23, 42];

// Creating the SVG canvas and scale
var svg = d3.select("svg").attr("width", 500).attr("height", 500);
var radius = Math.min(svg.attr("width"), svg.attr("height")) / 2;

// Creating an arc scale
var arc = d3.arc().outerRadius(radius).innerRadius(0);
var pie = d3.pie().value(function(d) { return d; });

// Draw a pie chart
var g = svg.append("g")
    .attr("transform", "translate(" + radius + "," + radius + ")");

var arcs = g.selectAll("arc")
    .data(pie(data))
    .enter().append("g")
    .attr("class", "arc");

arcs.append("path")
    .attr("d", arc)
    .attr("fill", function(d, i) { return d3.schemeCategory10[i]; });

arcs.append("text")
    .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
    .attr("dy", ".35em")
    .text(function(d) { return d.data; });
Copy after login

Interactivity and animation

Interactivity example: adding hover effects to a bar chart

// Assuming that the bar chart base code already exists
// ...

// Add hover effects
g.selectAll(".bar")
    .on("mouseover", function(event, d) {
        d3.select(this)
            .transition()
            .duration(200)
            .attr("fill", "orange"); // Mouseover color change

        // Show Data Tips
        var tooltip = g.append("text")
            .attr("class", "tooltip")
            .attr("x", x(d) + x.bandwidth() / 2)
            .attr("y", y(d) - 10)
            .text(d);
    })
    .on("mouseout", function(event, d) {
        d3.select(this)
            .transition()
            .duration(200)
            .attr("fill", "steelblue"); // Restore original color

        // Remove data tips
        g.selectAll(".tooltip").remove();
    });
Copy after login

Animation example: Smooth transition line chart data update

// Assume that there is already a line chart basic code
// ...

// Update data
var newData = [8, 15, 16, 23, 42, 45];

// Update scale domain
x.domain(d3.extent(newData));
y.domain([0, d3.max(newData)]);

// Update axis
g.select(".axis--x").transition().duration(750).call(xAxis);
g.select(".axis--y").transition().duration(750).call(yAxis);

// Update path
var path = g.select(".line");
path.datum(newData).transition().duration(750).attr("d", line);
Copy after login

Complex graphs: force-directed graphs

Force-directed graphs show the relationship between nodes and edges, which is very suitable for visualizing data such as networks and social graphs.

// Assume we have data on nodes and edges
var nodes = [{id: "A"}, {id: "B"}, {id: "C"}];
var links = [{source: nodes[0], target: nodes[1]}, {source: nodes[1], target: nodes[2]}];

// Creating the SVG Canvas
var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

// Creating a Force Simulation
var simulation = d3.forceSimulation(nodes)
    .force("link", d3.forceLink(links).id(function(d) { return d.id; }))
    .force("charge", d3.forceManyBody())
    .force("center", d3.forceCenter(width / 2, height / 2));

// Creating links and nodes
var link = svg.append("g")
    .attr("stroke", "#999")
    .attr("stroke-opacity", 0.6)
  .selectAll("line")
  .data(links)
  .join("line")
    .attr("stroke-width", 2);

var node = svg.append("g")
    .attr("stroke", "#fff")
    .attr("stroke-width", 1.5)
  .selectAll("circle")
  .data(nodes)
  .join("circle")
    .attr("r", 5)
    .call(d3.drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended));

node.append("title")
    .text(function(d) { return d.id; });

simulation.on("tick", ticked);

function ticked() {
  link
      .attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });

  node
      .attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; });
}

// Drag event handling function
function dragstarted(event, d) {
  if (!event.active) simulation.alphaTarget(0.3).restart();
  d.fx = d.x;
  d.fy = d.y;
}

function dragged(event, d) {
  d.fx = event.x;
  d.fy = event.y;
}

function dragended(event, d) {
  if (!event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}
Copy after login

Map Visualization

D3.js can work with geographic data formats such as GeoJSON to create interactive maps. This includes countries, states, city boundaries, etc.

Basic steps:

  • Load map data: Use D3's d3.json or d3.geoJson to load GeoJSON data.

  • Create scale: Define a geographic projection and scale, such as Mercator or Albers USA.

  • Bind data and draw: Bind GeoJSON data to SVG path elements and apply a projection.

  • Add interactions: Such as hover effects, click events, etc.

d3.json("world.geojson").then(function(geoData) {
  var svg = d3.select("svg"),
      projection = d3.geoMercator().scale(130).translate([400, 250]),
      path = d3.geoPath().projection(projection);

  svg.selectAll("path")
    .data(geoData.features)
    .enter().append("path")
    .attr("d", path)
    .attr("fill", "#ccc")
    .attr("stroke", "#fff");
});
Copy after login

Data binding and dynamic update

Basic steps:

  • Initialize data binding: Use the data() method to bind data to DOM elements.

  • Enter, Update, Exit mode: process new data, update existing data, and remove useless data.

  • Dynamic update: monitor data changes, re-execute binding and rendering processes.

var svg = d3.select("svg"),
    data = [4, 8, 15, 16, 23, 42];

// Initialize the bar chart
var bars = svg.selectAll("rect").data(data);

bars.enter().append("rect")
    .attr("x", function(d, i) { return i * 50; })
    .attr("y", function(d) { return 300 - d; })
    .attr("width", 40)
    .attr("height", function(d) { return d; });

// Dynamic Updates
setInterval(function() {
  data = data.map(function(d) { return Math.max(0, Math.random() * 50); });

  bars.data(data)
    .transition()
    .duration(500)
    .attr("y", function(d) { return 300 - d; })
    .attr("height", function(d) { return d; });
}, 2000);
Copy after login

Complex charts and advanced techniques

Advanced techniques:

  • Use D3 component libraries: Libraries like D3fc provide advanced chart components to simplify the creation of complex charts.

  • Animation and transition: Use the transition() method to create smooth animation effects.

  • Interactivity: Add click and hover events, and use brush and zoom functions to enhance user experience.

  • Performance optimization: Use selectAll(), data(), enter(), exit() reasonably to reduce DOM operations, and use requestAnimationFrame() to optimize animation performance.

The above is the detailed content of Ds in action: advanced data visualization techniques and examples. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles