Making a simple scatter plot with d3.js

来源:https://www.cnblogs.com/kungfupanda/archive/2020/07/18/13334370.html
-Advertisement-
Play Games

https://medium.com/@kj_schmidt/making-a-simple-scatter-plot-with-d3js-58cc894d7c97 Making a simple scatter plot with d3.js KJ Schmidt Follow Feb 20, 2 ...


https://medium.com/@kj_schmidt/making-a-simple-scatter-plot-with-d3js-58cc894d7c97

 

Making a simple scatter plot with d3.js

KJ Schmidt KJ Schmidt Feb 20, 2019 · 3 min read   Image for post Image for post

Getting started

This tutorial uses d3 v4.6. The CDN is hosted on Cloudflare, so you can start by adding this script tag to your html file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.6.0/d3.min.js"></script>

While still in your html file, add a div with an ID (I’m using #scatter in this tutorial) where you’d like the scatter plot to go:

<div id="scatter"></div>

Now onto the javascript. Create a new javascript file for your graph (don’t forget to go back to your html file and add a script tag for it!).

Next, we’ll need some data. We can add this directly to our javascript file. You can add dummy data or use the data I used about the federal minimum wage from United States Department of Labor:

data = [{
date: 2009,
wage: 7.25
}, {
date: 2008,
wage: 6.55
}, {
date: 2007,
wage: 5.85
}, {
date: 1997,
wage: 5.15
}, {
date: 1996,
wage: 4.75
}, {
date: 1991,
wage: 4.25
}, {
date: 1981,
wage: 3.35
}, {
date: 1980,
wage: 3.10
}, {
date: 1979,
wage: 2.90
}, {
date: 1978,
wage: 2.65
}]

Get going on the graph

First, we’ll set our variables for margin, width, and height.

var margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
}width = 700 - margin.left - margin.right;
height = 500 - margin.top - margin.bottom;

Next, we need to format the data. I used d3.timeParse() because my data includes dates. You can also sort your data, which I did from lowest to highest year. Sorting is only important here if you plan to connect your data points.

// format the data
data.forEach(function (d) {
parseDate = d3.timeParse("%Y");
d.date = parseDate(d.date);
d.wage = +d.wage;
});//sort the data by date
data.sort(function (a, b) {
return a.date - b.date;
});

Now it’s time to set the ranges and scale for our x and y axis. I used .scaleTime() for the x axis since it’s in years, and .scaleLinear() for the y axis since it’s a continuous scale.

var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);// Scale the range of the data
x.domain(d3.extent(data, function (d) {
return d.date;
}));y.domain([0, d3.max(data, function (d) {
return d.wage;
})]);

This next code establishes what kind of graph we’re making. We’re using d3.line(), which allows us to make either a scatter plot or a line chart.

var valueline = d3.line()
.x(function (d) {
return x(d.date);
})
.y(function (d) {
return y(d.wage);
});

Now we need to append the SVG object to the #scatter div we made earlier in the html.

var svg = d3.select("#scatter").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

Optional: If you want to connect your data points like this, add this code for a trend line:

Image for post Image for post
svg.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline)
//styling:
.attr("stroke", "#32CD32")
.attr("stroke-width", 2)
.attr("fill", "#FFFFFF");

*make sure you sorted your data in the format/sort step, or you may have a weird shape here.

Almost done

It’s time to add the actual data points:

var path = svg.selectAll("dot")
.data(data)
.enter().append("circle")
.attr("r", 5)
.attr("cx", function (d) {
return x(d.date);
})
.attr("cy", function (d) {
return y(d.wage);
})
.attr("stroke", "#32CD32")
.attr("stroke-width", 1.5)
.attr("fill", "#FFFFFF");

For both the line and data point code, you can edit the way it looks with the .attr lines.

Lastly, we add the axis. I added some formatting to the y axis to show dollar amounts with .tickFormat(). You can also specify the amount of ticks you want with .ticks().

svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));svg.append("g")
.call(d3.axisLeft(y).tickFormat(function (d) {
return "$" + d3.format(".2f")(d)
}));
Image for post Image for post

You have a graph!

If you’re having any issues, see the full code or check it out live.

Interested in adding effects and showing the data point’s value on hover? I have another tutorial for that!


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.<video></video> 用於定義視頻,如影視片段 語法<video src="XXXmovie.mp4" controls></video> 支持視頻格式:mp4、ogg移動端、webM高清 常用屬性: src,視頻的地址url autoplay,視頻就緒後自動播放 controls,向 ...
  • 五角星形線的笛卡爾坐標方程式可設為: r=10+(3*sin(θ*2.5))^2 x=r*cos(θ) y=r*sin(θ) (0≤θ≤2π) 根據這個曲線方程,在[0,2π]區間取一系列角度值,根據給定角度值計算對應的各點坐標,然後在計算出的坐標位置繪製一個填充色交替變換的小圓,從而得到沿五角星形 ...
  • 1.新增類型 電子郵件類型,語法<input type="email"/>,input中輸入的內容必須包含“@”,並且“@”後面必須有內容 搜索類型,語法<input type="search"/>,輸入搜索關鍵字的文本框 URL類型,語法<input type="url"/>,輸入web站點的文本 ...
  • 一、安裝node.js(https://nodejs.org/en/) 下載完畢後,可以安裝node,建議不要安裝在系統盤(如C:)。 二、設置nodejs prefix(全局)和cache(緩存)路徑 1、在nodejs安裝路徑下,新建node_global和node_cache兩個文件夾 2、設 ...
  • 1.粒子文本的實現原理 粒子文本的實現原理是:使用兩張 canvas,一張是用戶看不到的canvas1,用來繪製文本;另一張是用戶看到的canvas2,用來根據canvas1中繪製的文本數據來生成粒子。 先在canvas1中用如下的語句繪製待顯示的文本。 ctx1.font = '100px Pin ...
  • 定位 定位:通過定位可以將元素擺放在頁面中任意位置 語法:position屬性設置元素的定位 可選值:static:預設值,開啟定位 relative開啟相對定位 absolute開啟絕對定位 fixed開啟固定定位 相對定位:當元素設置position:relative;開啟元素的相對定位 1 開 ...
  • 背景是這樣的,母親節的時候,我們有個需求就是用戶可以長按或者點擊一個按鈕進行截圖後去分享我們的活動,然而我們的圖片例如頭像,採用又拍雲做 cdn 優化,所以意味著圖片的鏈接跟主頁面所在功能變數名稱不一樣,當需要需要對 canvas 圖片進行 getImageData() 或 toDataURL() 操作的時 ...
  • https://www.d3indepth.com/scales/ D3 in Depth Home About Introduction to D3 Selections Joins Enter/exit Scales Shapes Layouts Force Geographic Request ...
一周排行
    -Advertisement-
    Play Games
  • 概述:在C#中,++i和i++都是自增運算符,其中++i先增加值再返回,而i++先返回值再增加。應用場景根據需求選擇,首碼適合先增後用,尾碼適合先用後增。詳細示例提供清晰的代碼演示這兩者的操作時機和實際應用。 在C#中,++i 和 i++ 都是自增運算符,但它們在操作上有細微的差異,主要體現在操作的 ...
  • 上次發佈了:Taurus.MVC 性能壓力測試(ap 壓測 和 linux 下wrk 壓測):.NET Core 版本,今天計劃準備壓測一下 .NET 版本,來測試並記錄一下 Taurus.MVC 框架在 .NET 版本的性能,以便後續持續優化改進。 為了方便對比,本文章的電腦環境和測試思路,儘量和... ...
  • .NET WebAPI作為一種構建RESTful服務的強大工具,為開發者提供了便捷的方式來定義、處理HTTP請求並返迴響應。在設計API介面時,正確地接收和解析客戶端發送的數據至關重要。.NET WebAPI提供了一系列特性,如[FromRoute]、[FromQuery]和[FromBody],用 ...
  • 原因:我之所以想做這個項目,是因為在之前查找關於C#/WPF相關資料時,我發現講解圖像濾鏡的資源非常稀缺。此外,我註意到許多現有的開源庫主要基於CPU進行圖像渲染。這種方式在處理大量圖像時,會導致CPU的渲染負擔過重。因此,我將在下文中介紹如何通過GPU渲染來有效實現圖像的各種濾鏡效果。 生成的效果 ...
  • 引言 上一章我們介紹了在xUnit單元測試中用xUnit.DependencyInject來使用依賴註入,上一章我們的Sample.Repository倉儲層有一個批量註入的介面沒有做單元測試,今天用這個示例來演示一下如何用Bogus創建模擬數據 ,和 EFCore 的種子數據生成 Bogus 的優 ...
  • 一、前言 在自己的項目中,涉及到實時心率曲線的繪製,項目上的曲線繪製,一般很難找到能直接用的第三方庫,而且有些還是定製化的功能,所以還是自己繪製比較方便。很多人一聽到自己畫就害怕,感覺很難,今天就分享一個完整的實時心率數據繪製心率曲線圖的例子;之前的博客也分享給DrawingVisual繪製曲線的方 ...
  • 如果你在自定義的 Main 方法中直接使用 App 類並啟動應用程式,但發現 App.xaml 中定義的資源沒有被正確載入,那麼問題可能在於如何正確配置 App.xaml 與你的 App 類的交互。 確保 App.xaml 文件中的 x:Class 屬性正確指向你的 App 類。這樣,當你創建 Ap ...
  • 一:背景 1. 講故事 上個月有個朋友在微信上找到我,說他們的軟體在客戶那邊隔幾天就要崩潰一次,一直都沒有找到原因,讓我幫忙看下怎麼回事,確實工控類的軟體環境複雜難搞,朋友手上有一個崩潰的dump,剛好丟給我來分析一下。 二:WinDbg分析 1. 程式為什麼會崩潰 windbg 有一個厲害之處在於 ...
  • 前言 .NET生態中有許多依賴註入容器。在大多數情況下,微軟提供的內置容器在易用性和性能方面都非常優秀。外加ASP.NET Core預設使用內置容器,使用很方便。 但是筆者在使用中一直有一個頭疼的問題:服務工廠無法提供請求的服務類型相關的信息。這在一般情況下並沒有影響,但是內置容器支持註冊開放泛型服 ...
  • 一、前言 在項目開發過程中,DataGrid是經常使用到的一個數據展示控制項,而通常表格的最後一列是作為操作列存在,比如會有編輯、刪除等功能按鈕。但WPF的原始DataGrid中,預設只支持固定左側列,這跟大家習慣性操作列放最後不符,今天就來介紹一種簡單的方式實現固定右側列。(這裡的實現方式參考的大佬 ...