国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 web前端 js教程 Ds 的實(shí)際應(yīng)用:進(jìn)階資料視覺化技術(shù)與範(fàn)例

Ds 的實(shí)際應(yīng)用:進(jìn)階資料視覺化技術(shù)與範(fàn)例

Dec 30, 2024 am 07:11 AM

Ds in action: advanced data visualization techniques and examples

基礎(chǔ)知識(shí)

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

<!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>

創(chuàng)建一個(gè)簡(jiǎn)單的折線圖

// 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);

建立長(zhǎng)條圖

// 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); });

創(chuàng)建圓餅圖

// 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; });

互動(dòng)性和動(dòng)畫

互動(dòng)範(fàn)例:為長(zhǎng)條圖新增懸停效果

// 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();
    });

動(dòng)畫範(fàn)例:平滑過渡折線圖資料更新

// 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);

複雜圖:力導(dǎo)向圖

力向圖展示了節(jié)點(diǎn)和邊之間的關(guān)係,非常適合視覺化網(wǎng)路和社交圖等資料。

// 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 等地理資料格式來建立互動(dòng)式地圖。這包括國家、州、城市邊界等

基本步驟:

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

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

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

  • 新增互動(dòng):如懸停效果、點(diǎn)擊事件等

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");
});

資料綁定和動(dòng)態(tài)更新

基本步驟:

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

  • 進(jìn)入、更新、退出模式:處理新資料、更新現(xiàn)有資料、刪除無用資料。

  • 動(dòng)態(tài)更新:監(jiān)控資料變化,重新執(zhí)行綁定和渲染過程。

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);

複雜的圖表和先進(jìn)的技術(shù)

進(jìn)階技巧:

  • 使用 D3 元件庫:D3fc 等函式庫提供進(jìn)階圖表元件來簡(jiǎn)化複雜圖表的建立。

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

  • 互動(dòng)性:新增點(diǎn)擊和懸停事件,並使用畫筆和縮放功能來增強(qiáng)使用者體驗(yàn)。

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

以上是Ds 的實(shí)際應(yīng)用:進(jìn)階資料視覺化技術(shù)與範(fàn)例的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

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

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

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

Java vs. JavaScript:清除混亂 Java vs. JavaScript:清除混亂 Jun 20, 2025 am 12:27 AM

Java和JavaScript是不同的編程語言,各自適用於不同的應(yīng)用場(chǎng)景。 Java用於大型企業(yè)和移動(dòng)應(yīng)用開發(fā),而JavaScript主要用於網(wǎng)頁開發(fā)。

如何在JS中與日期和時(shí)間合作? 如何在JS中與日期和時(shí)間合作? Jul 01, 2025 am 01:27 AM

JavaScript中的日期和時(shí)間處理需注意以下幾點(diǎn):1.創(chuàng)建Date對(duì)像有多種方式,推薦使用ISO格式字符串以保證兼容性;2.獲取和設(shè)置時(shí)間信息可用get和set方法,注意月份從0開始;3.手動(dòng)格式化日期需拼接字符串,也可使用第三方庫;4.處理時(shí)區(qū)問題建議使用支持時(shí)區(qū)的庫,如Luxon。掌握這些要點(diǎn)能有效避免常見錯(cuò)誤。

為什麼要將標(biāo)籤放在的底部? 為什麼要將標(biāo)籤放在的底部? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript與Java:開發(fā)人員的全面比較 JavaScript與Java:開發(fā)人員的全面比較 Jun 20, 2025 am 12:21 AM

JavaScriptIspreferredforredforwebdevelverment,而Javaisbetterforlarge-ScalebackendsystystemsandSandAndRoidApps.1)JavascriptexcelcelsincreatingInteractiveWebexperienceswebexperienceswithitswithitsdynamicnnamicnnamicnnamicnnamicnemicnemicnemicnemicnemicnemicnemicnemicnddommanipulation.2)

什麼是在DOM中冒泡和捕獲的事件? 什麼是在DOM中冒泡和捕獲的事件? Jul 02, 2025 am 01:19 AM

事件捕獲和冒泡是DOM中事件傳播的兩個(gè)階段,捕獲是從頂層向下到目標(biāo)元素,冒泡是從目標(biāo)元素向上傳播到頂層。 1.事件捕獲通過addEventListener的useCapture參數(shù)設(shè)為true實(shí)現(xiàn);2.事件冒泡是默認(rèn)行為,useCapture設(shè)為false或省略;3.可使用event.stopPropagation()阻止事件傳播;4.冒泡支持事件委託,提高動(dòng)態(tài)內(nèi)容處理效率;5.捕獲可用於提前攔截事件,如日誌記錄或錯(cuò)誤處理。了解這兩個(gè)階段有助於精確控制JavaScript響應(yīng)用戶操作的時(shí)機(jī)和方式。

JavaScript:探索用於高效編碼的數(shù)據(jù)類型 JavaScript:探索用於高效編碼的數(shù)據(jù)類型 Jun 20, 2025 am 12:46 AM

javascripthassevenfundaMentalDatatypes:數(shù)字,弦,布爾值,未定義,null,object和symbol.1)numberSeadUble-eaduble-ecisionFormat,forwidevaluerangesbutbecautious.2)

如何減少JavaScript應(yīng)用程序的有效載荷大小? 如何減少JavaScript應(yīng)用程序的有效載荷大小? Jun 26, 2025 am 12:54 AM

如果JavaScript應(yīng)用加載慢、性能差,問題往往出在payload太大,解決方法包括:1.使用代碼拆分(CodeSplitting),通過React.lazy()或構(gòu)建工具將大bundle拆分為多個(gè)小文件,按需加載以減少首次下載量;2.移除未使用的代碼(TreeShaking),利用ES6模塊機(jī)制清除“死代碼”,確保引入的庫支持該特性;3.壓縮和合併資源文件,啟用Gzip/Brotli和Terser壓縮JS,合理合併文件並優(yōu)化靜態(tài)資源;4.替換重型依賴,選用輕量級(jí)庫如day.js、fetch

JavaScript模塊上的確定JS綜述:ES模塊與COMPORJS JavaScript模塊上的確定JS綜述:ES模塊與COMPORJS Jul 02, 2025 am 01:28 AM

ES模塊和CommonJS的主要區(qū)別在於加載方式和使用場(chǎng)景。 1.CommonJS是同步加載,適用於Node.js服務(wù)器端環(huán)境;2.ES模塊是異步加載,適用於瀏覽器等網(wǎng)絡(luò)環(huán)境;3.語法上,ES模塊使用import/export,且必須位於頂層作用域,而CommonJS使用require/module.exports,可在運(yùn)行時(shí)動(dòng)態(tài)調(diào)用;4.CommonJS廣泛用於舊版Node.js及依賴它的庫如Express,ES模塊則適用於現(xiàn)代前端框架和Node.jsv14 ;5.雖然可混合使用,但容易引發(fā)問題

See all articles