首頁 web前端 js教程 Ds 的實際應用:進階資料視覺化技術與範例

Ds 的實際應用:進階資料視覺化技術與範例

Dec 30, 2024 am 07:11 AM

Ds in action: advanced data visualization techniques and examples

基礎知識

首先,我們需要一個 HTML 檔案來匯入 D3.js 庫並準備畫布來放置我們的圖表。

<!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>
登入後複製

創建一個簡單的折線圖

// 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);
登入後複製

建立長條圖

// 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); });
登入後複製

創建圓餅圖

// 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; });
登入後複製

互動性和動畫

互動範例:為長條圖新增懸停效果

// 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();
    });
登入後複製

動畫範例:平滑過渡折線圖資料更新

// 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);
登入後複製

複雜圖:力導向圖

力向圖展示了節點和邊之間的關係,非常適合視覺化網路和社交圖等資料。

// 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;
}
登入後複製

地圖視覺化

D3.js 可以使用 GeoJSON 等地理資料格式來建立互動式地圖。這包括國家、州、城市邊界等

基本步驟:

  • 載入地圖資料:使用D3的d3.json或d3.geoJson載入GeoJSON資料。

  • 建立比例:定義地理投影和比例,例如 Mercator 或 Albers USA。

  • 綁定資料並繪製:將 GeoJSON 資料綁定到 SVG 路徑元素並套用投影。

  • 新增互動:如懸停效果、點擊事件等

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");
});
登入後複製

資料綁定和動態更新

基本步驟:

  • 初始化資料綁定:使用 data() 方法將資料綁定到 DOM 元素。

  • 進入、更新、退出模式:處理新資料、更新現有資料、刪除無用資料。

  • 動態更新:監控資料變化,重新執行綁定和渲染過程。

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);
登入後複製

複雜的圖表和先進的技術

進階技巧:

  • 使用 D3 元件庫:D3fc 等函式庫提供進階圖表元件來簡化複雜圖表的建立。

  • 動畫和過渡:使用transition()方法創建流暢的動畫效果。

  • 互動性:新增點擊和懸停事件,並使用畫筆和縮放功能來增強使用者體驗。

  • 效能最佳化:合理使用selectAll()、data()、enter()、exit()減少DOM操作,使用requestAnimationFrame()最佳化動畫效能。

以上是Ds 的實際應用:進階資料視覺化技術與範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1655
14
CakePHP 教程
1414
52
Laravel 教程
1307
25
PHP教程
1253
29
C# 教程
1227
24
前端熱敏紙小票打印遇到亂碼問題怎麼辦? 前端熱敏紙小票打印遇到亂碼問題怎麼辦? Apr 04, 2025 pm 02:42 PM

前端熱敏紙小票打印的常見問題與解決方案在前端開發中,小票打印是一個常見的需求。然而,很多開發者在實...

神秘的JavaScript:它的作用以及為什麼重要 神秘的JavaScript:它的作用以及為什麼重要 Apr 09, 2025 am 12:07 AM

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

誰得到更多的Python或JavaScript? 誰得到更多的Python或JavaScript? Apr 04, 2025 am 12:09 AM

Python和JavaScript開發者的薪資沒有絕對的高低,具體取決於技能和行業需求。 1.Python在數據科學和機器學習領域可能薪資更高。 2.JavaScript在前端和全棧開發中需求大,薪資也可觀。 3.影響因素包括經驗、地理位置、公司規模和特定技能。

如何實現視差滾動和元素動畫效果,像資生堂官網那樣?
或者:
怎樣才能像資生堂官網一樣,實現頁面滾動伴隨的動畫效果? 如何實現視差滾動和元素動畫效果,像資生堂官網那樣? 或者: 怎樣才能像資生堂官網一樣,實現頁面滾動伴隨的動畫效果? Apr 04, 2025 pm 05:36 PM

實現視差滾動和元素動畫效果的探討本文將探討如何實現類似資生堂官網(https://www.shiseido.co.jp/sb/wonderland/)中�...

JavaScript的演變:當前的趨勢和未來前景 JavaScript的演變:當前的趨勢和未來前景 Apr 10, 2025 am 09:33 AM

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

如何使用JavaScript將具有相同ID的數組元素合併到一個對像中? 如何使用JavaScript將具有相同ID的數組元素合併到一個對像中? Apr 04, 2025 pm 05:09 PM

如何在JavaScript中將具有相同ID的數組元素合併到一個對像中?在處理數據時,我們常常會遇到需要將具有相同ID�...

JavaScript引擎:比較實施 JavaScript引擎:比較實施 Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

前端開發中如何實現類似 VSCode 的面板拖拽調整功能? 前端開發中如何實現類似 VSCode 的面板拖拽調整功能? Apr 04, 2025 pm 02:06 PM

探索前端中類似VSCode的面板拖拽調整功能的實現在前端開發中,如何實現類似於VSCode...

See all articles