數據可視化【四】Bar Chart

Make a Bar Chart

  • Representing a data table in JavaScript
  • Creating rectangles for each row
  • Using linear and band scales
  • The margin convention
  • Adding axes

以下學習內容參考博客:傳送門

select()選擇所有指定元素的第一個
selectAll()選擇指定元素的全部
上面兩個函數返回的結果為選擇集
關于 select 和 selectAll 的參數,其實是符合 CSS 選擇器的條件的,即用“井號(#)”表示 id,用“點(.)”表示 class。
datum()綁定一個數據到選擇集上
data()綁定一個數組到選擇集上,數組的各項值分別與選擇集的各項元素綁定

在選擇集A和給定數據集B進行綁定的時候,會返回一個值,這個值有三種狀態。默認然會的是update狀態。通過update狀態我們還能得到exit狀態和enter狀態。

  • update:A∩BA\cap BAB
  • exit:A?BA-BA?B
  • enter:B?AB-AB?A

比較常用的是enter,當我們綁定新數據以后一般要對新數據進行處理。對enter()函數的處理會應用到每個數據上。例如:

svg.selectAll("rect")//選擇svg內的所有矩形.data(dataset)//綁定數組.enter()//指定選擇集的enter部分.append("rect")//添加足夠數量的矩形元素.attr("x",20).attr("y",function(d,i){return i * rectHeight;}).attr("width",function(d){return d;}).attr("height",rectHeight-2).attr("fill","steelblue");

以上面的代碼為例。我們對所有的矩形綁定了data以后獲得entry,然后對每個數據進行處理。需要注意的是對屬性的設置要么是常數要么應該傳入一個函數,并且函數可以有兩個參數,第一個是數據,第二個是數據的下標。

學習實現代碼:https://vizhub.com/Edward-Elric233/b9b751bfae674d0aa65deae87899b710

index.html

<!DOCTYPE html>
<html><head><title>Makign a Bar Chart</title><link rel="stylesheet" href="styles.css"><script src="https://unpkg.com/d3@5.7.0/dist/d3.min.js"></script><!-- find D3 file on UNPKG d3.min.js-->
</head><body><svg width="960" height="500"></svg><script src="./index.js">// console.log(d3); test whether you have imported d3.js or not</script></body></html>

index.js

const svg = d3.select('svg');
// svg.style('background-color', 'red'); test
const width = +svg.attr('width');
const height = +svg.attr('height');const render = data => {const xValue = d => d.population;const yValue = d => d.country;const margin = { top: 20, right: 20, bottom: 20, left: 100 };const innerWidth = width - margin.left - margin.right;const innerHeight = height - margin.top - margin.bottom;const xScale = d3.scaleLinear().domain([0, d3.max(data, xValue)]).range([0, innerWidth]);const yScale = d3.scaleBand().domain(data.map(yValue)).range([0, innerHeight]).padding(0.1);const yAxis = d3.axisLeft(yScale);const xAxis = d3.axisBottom(xScale);const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`);//yAxis(g.append('g'));g.append('g').call(yAxis);g.append('g').call(xAxis).attr('transform', `translate(0,${innerHeight})`);let colorSet = ['#eb2617', '#ffaa00', '#4dff00', '#00fbff', '#bb00ff', '#eeff00'];const createGetColor = (idx) => {var i = idx || -1;return {get: () => { i = (i + 1) % colorSet.length; return colorSet[i]; }};};const getColor = createGetColor();g.selectAll('rect').data(data).enter().append('rect').attr('y', d => yScale(yValue(d))).attr('width', d => xScale(xValue(d))).attr('height', yScale.bandwidth()).attr('fill', getColor.get);
};d3.csv("https://gist.githubusercontent.com/Edward-Elric233/23f3024c472ffd7e34e6a5ac04bad26c/raw/6ced2249ea6f5d12f72c1eb00b8c1278d2c86e95/every%2520countries'%2520population").then(data => {data.forEach(d => {d.population = +d.population * 1000;});render(data);// console.log(data);
});

實現效果:在這里插入圖片描述

需要注意的是使用d3綁定csv文件的時候要求csv文件不能是本地,必須上傳到服務器然后使用http協議訪問。我這里使用的是gist.github上傳的數據。

這里其他地方都比較簡單,主要詳細講解一下js文件。

d3.csv('data.csv').then(data => {data.forEach(d => {d.population = +d.population * 1000;});render(data);

上面的代碼主要是讀取數據然后再對數據進行處理,處理使用的是我們自己編寫的函數render

然后就是render函數。

const xScale = d3.scaleLinear().domain([0, d3.max(data, xValue)]).range([0, innerWidth]);const yScale = d3.scaleBand().domain(data.map(yValue)).range([0, innerHeight]).padding(0.1);

scaleLinear函數用來標注柱狀圖的刻度。定義域domain是一個范圍,值域range也是一個范圍,d3會自動進行一個比例映射。這個函數返回一個函數,我們使用xScale(input)輸入一個數字d3就會返回一個值,這個值是按照比例進行映射的。

scaleBand函數的定義域是一個數組,值域是一個范圍。然后我們可以獲取yScale.bandwidth()來確定每個柱狀圖的寬度(因為是水平的所以其實是高度)。每個條形的y坐標我們可以通過這個函數輸入參數獲取。例如這里的yScale('China')就會返回一個值,這個值是計算好的,我們不用處理。

其他的就是最前面的做法,使用selectAll獲取到所有矩形(此時為空),然后和data進行綁定,然后再對enter進行處理。每個數據都會得到一個矩形并且有相應的坐標。

這里使用xValueyValue函數的原因是因為多個地方都要取數據的屬性,我們將這種操作抽象出來以后就只用修改一個地方。

這個代碼中和老師講解不同的是我的柱狀圖的顏色是五顏六色的。我覺得老師講都弄成一種顏色太過單調了,就想辦法改了一下。主要就是設置了每個矩形的fill屬性,傳入一個每次會返回不同顏色的函數,如下:

let colorSet = ['#eb2617', '#ffaa00', '#4dff00', '#00fbff', '#bb00ff', '#eeff00'];const createGetColor = (idx) => {var i = idx || -1;return {get: () => { i = (i + 1) % colorSet.length; return colorSet[i]; }};};
const getColor = createGetColor();

這里使用的是通過閉包的方式在函數里面保存了一個累加器,從而實現不斷返回新顏色。

Customizing Axes

Formatting numbers

為了使得坐標上的數字變得規格化,我們可以使用d3中的format函數。我們可以在http://bl.ocks.org/zanarmstrong/05c1e95bf7aa16c4768e查看如何進行格式化。

const xAxisTickFormat = number => format('.3s')(number).replace('G','B');
const yAxis = axisLeft(yScale);
const xAxis = axisBottom(xScale).tickFormat(xAxisTickFormat);

Removing unnecessary lines

如果一些東西是多出來的想要進行刪除可以在開發者工具中的選擇多余的部分查看屬性然后用selectremove進行刪除。

g.append('g').call(yAxis).selectAll('.domain, .tick line').remove();

Adding a visualization title

g.append('text').attr('y', -10).text('Top 10 Most Population Countries').style('font-size', 40);

Adding axis lables

const yAxisG = g.append('g').call(yAxis).selectAll('.domain, .tick line').remove();const xAxisG = g.append('g').call(xAxis)	.attr('transform', `translate(0,${innerHeight})`);xAxisG.append('text').attr('y', 50).attr('x', innerWidth-60).attr('fill', 'black').text('populiation').style('font-size', 20);

Making tick grid lines

可以將下面的刻度的線弄的很長,比如:

  const xAxis = axisBottom(xScale).tickFormat(xAxisTickFormat).tickSize(-innerHeight);

可是我覺得這樣很丑,所以就算了。

課程還介紹了一個關于Data Visualization的一個文檔,感興趣的可以下載:https://github.com/amycesal/dataviz-style-guide/blob/master/Sunlight-StyleGuide-DataViz.pdf

經過上面代碼的修改以及顏色的修改,最后的效果圖:
在這里插入圖片描述

看起來已經比較標準了。vizhub代碼:https://vizhub.com/Edward-Elric233/dc1509720f104350a589b46eda59157a

本地代碼:

index.html

<!DOCTYPE html>
<html><head><title>Makign a Bar Chart</title><link rel="stylesheet" href="styles.css"><script src="https://unpkg.com/d3@5.7.0/dist/d3.min.js"></script><!-- find D3 file on UNPKG d3.min.js-->
</head><body><svg width="960" height="500"></svg><script src="./index.js">// console.log(d3); test whether you have imported d3.js or not</script></body></html>

index.js

const svg = d3.select('svg');
// svg.style('background-color', 'red'); test
const width = +svg.attr('width');
const height = +svg.attr('height');const render = data => {const xValue = d => d.population;const yValue = d => d.country;const margin = { top: 60, right: 20, bottom: 80, left: 150 };const innerWidth = width - margin.left - margin.right;const innerHeight = height - margin.top - margin.bottom;const xScale = d3.scaleLinear().domain([0, d3.max(data, xValue)]).range([0, innerWidth]);const yScale = d3.scaleBand().domain(data.map(yValue)).range([0, innerHeight]).padding(0.1);const xAxisTickFormat = number => d3.format('.3s')(number).replace('G', 'B');const yAxis = d3.axisLeft(yScale);const xAxis = d3.axisBottom(xScale).tickFormat(xAxisTickFormat);const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`);//yAxis(g.append('g'));const yAxisG = g.append('g').call(yAxis).selectAll('.domain, .tick line').remove();const xAxisG = g.append('g').call(xAxis).attr('transform', `translate(0,${innerHeight})`);xAxisG.append('text').attr('class', 'axis-label').attr('y', 60).attr('x', innerWidth / 2).attr('fill', 'black').text('populiation');let colorSet = ['#eb2617', '#ffaa00', '#4dff00', '#00fbff', '#bb00ff', '#eeff00'];const createGetColor = (idx) => {var i = idx || -1;return {get: () => { i = (i + 1) % colorSet.length; return colorSet[i]; }};};const getColor = createGetColor();g.selectAll('rect').data(data).enter().append('rect').attr('y', d => yScale(yValue(d))).attr('width', d => xScale(xValue(d))).attr('height', yScale.bandwidth()).attr('fill', getColor.get);g.append('text').attr('class', 'title').attr('y', -20).text('Top 10 Most Population Countries');
};d3.csv("https://gist.githubusercontent.com/Edward-Elric233/23f3024c472ffd7e34e6a5ac04bad26c/raw/6ced2249ea6f5d12f72c1eb00b8c1278d2c86e95/every%2520countries'%2520population").then(data => {data.forEach(d => {d.population = +d.population * 1000;});render(data);// console.log(data);
});

styles.css

body {margin: 0px;overflow: hidden;font-family: manosapce;
}text {font-family: sans-serif;
}.tick text {font-size: 2em;fill: #8E8883
}.axis-label {fill: #8E8883;font-size: 2.5em
}.title {font-size: 3em;fill: #8E8883
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/383615.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/383615.shtml
英文地址,請注明出處:http://en.pswp.cn/news/383615.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

數據庫原理及應用【三】DBMS+SQL

DBMS Query LanguagesInterface and maintaining tools(GUI)APIsClass Library QL 不是圖靈完備的&#xff0c;不是一種編程語言。 QL SQL是一種非過程化的查詢語言。 DDL數據定義語言&#xff1a;表&#xff0c;視圖QL 查詢語言DML 數據操縱語言DCL 數據控制語言 Base t…

數據可視化【五】 Scatter Plot

Scatter Plot vizhub上實現的代碼&#xff1a; https://vizhub.com/Edward-Elric233/53807a1b35d94329b3689081cd2ea945 https://vizhub.com/Edward-Elric233/b9647d50899a4a0e8e917f913cd0a53a https://vizhub.com/Edward-Elric233/8c6b50cd81a04f048f490f48e4fe6264 由前…

數據可視化【六】Line Chart Area Chart

Line Chart vizhub代碼&#xff1a; https://vizhub.com/Edward-Elric233/094396fc7a164c828a4a8c2e13045308 實現效果&#xff1a; 這里先使用d3.line()設置每個點的x坐標和y坐標&#xff0c;然后再用這個東西設置path的d屬性&#xff0c;就可以得到曲線。 const lineGen…

數據可視化【七】 更新模式

Enter 以下面這個簡單的代碼進行分析 const svg d3.select(svg); // svg.style(background-color, red); testconst height svg.attr(height); // equals paresFloat() const width svg.attr(width);const makeFruit type >( {type} ); //這種寫法好像能夠直接得到一個…

數據可視化【八】根據數據類型選擇可視化方式

Marks:Rows PointsLinesAreas Channels:Columns PositionColorShape

數據可視化【九】單向數據流交互

我們使用一下上上篇博客的代碼。 例如我們想要當鼠標點擊水果的時候會出現黑色的框&#xff0c;再點擊一下黑色的框就會消失。 首先&#xff0c;我們應該給組件添加點擊事件&#xff1a; fruitBowl.js gruopAll.on(click, d > onClick(d.id));這個on函數第一個參數是事件…

數據庫原理及應用【四】數據庫管理系統

查詢優化 數據庫管理系統中非常重要的一部分。 代數優化 按照一定的規則將語句變化成關系代數以后進行優化 操作優化 對代數優化后的查詢樹使用比較好的方法進行查詢。 主要是對連接運算進行優化 嵌套循環歸并掃描索引優化哈希連接 恢復機制 備份&#xff08;完整備份差…

數據庫原理及應用【五】安全性和完整性約束

數據庫一致性被破壞&#xff1a; 系統故障許多用戶的并發訪問人為破壞事務本身不正確 保護數據庫一致性的方法&#xff1a; 視圖/查詢修改訪問控制 普通用戶擁有資源特權的用戶DBA 數據庫的安全問題 身份驗證 口令物理設備 GRANT CONNECT TO John IDENTIFIED BY 123456…

遞歸式復雜度求解

代換法 猜測復雜度驗證是否滿足遞歸式&#xff08;使用歸納法&#xff09;找到常數應該滿足的條件針對基本情況&#xff0c;常數足夠大時總是成立的 需要注意的是&#xff0c;我們猜測的復雜度有可能不滿足遞歸式&#xff0c;這個時候就要通過減去一些低階項來使得歸納成立。…

斐波那契數列計算

定義 斐波那契數列&#xff1a; F[n]{0,n01,n1F[n?1]F[n?2],elseF[n] \begin{cases} 0,n0 \\ 1,n1\\ F[n-1]F[n-2],else \end{cases} F[n]??????0,n01,n1F[n?1]F[n?2],else? 樸素計算法 根據遞歸式F[n]F[n?1]F[n?2]F[n]F[n-1]F[n-2]F[n]F[n?1]F[n?2]進行計算…

P、NP、NP完全問題、NP難問題

可以在多項式時間內求解的問題稱為易解的&#xff0c;而不能在多項式時間內求解的問題稱為難解的。 P類問題&#xff1a;多項式類型&#xff0c;是一類能夠用&#xff08;確定性的&#xff09;算法在多項式的時間內求解的判定問題。 只有判定問題才屬于P 不可判定問題&#…

數據可視化【十】繪制地圖

Loading and parsing TOPOJSON 導入Topojson d3文件 地址&#xff1a;https://unpkg.com/topojson3.0.2/dist/topojson.min.js 想要找d3文件的話去unpkg.com好像大部分都能找到的樣子 Rendering geographic features 尋找合適的地圖數據&#xff1a;谷歌搜索world-atlas npm…

數據可視化【十一】樹狀圖

Constructing a node-link tree visualization 首先將節點之間的連線畫出來。 使用json函數讀取文件以后&#xff0c;使用hierarchy等函數得到連線的數組&#xff0c;然后綁定這個數組&#xff0c;給每個元素添加一個path&#xff0c;繪畫使用的是一個函數linkHorizontal&…

數據可視化【十二】 顏色圖例和尺寸圖例

有了前面的知識&#xff0c;制作一個圖例應該不是很難&#xff0c;關鍵是我們想要制作一個可以在其他地方進行使用的圖例&#xff0c;這樣就需要能夠動態地設置圖例的大小&#xff0c;位置&#xff0c;等等。 這里直接上代碼&#xff1a; colorLegend.js export const color…

數據可視化【十三】地區分布圖

在前面的博客中已經介紹了如何繪制地圖&#xff0c;這一節學習如何繪制地區分布圖。如果對繪制地圖還不熟悉的話可以了解一下之前我寫的博客&#xff1a;數據可視化【十】繪制地圖 Intergrating(整合) TopoJSON with tabular data(列表數據) 在前面的博客中沒有使用到tsv文件…

3.01【python正則表達式以及re模塊】

python正則表達式以及re模塊 元字符 正則表達式的語法就由表格中的元字符組成&#xff0c;一般用于搜索、替換、提取文本數據 元字符含義.匹配除換行符以外的任何單個字符*匹配前面的模式0次或1次匹配前面的模式1次或多次?匹配前面的模式0次或1次[]用于定義字符集&#xff…

Linux配置編程環境+云服務器上傳文件

Java環境配置 Ubuntu https://www.cnblogs.com/lfri/p/10437266.html Centos https://blog.csdn.net/qq_21077715/article/details/85536399 Tomcat配置 Centos https://blog.csdn.net/qq_21077715/article/details/85541685 https://www.cnblogs.com/newwind/p/9904561…

gbd + cgbd

gbd&#xff1a;傳送門 cgbd&#xff1a;傳送門 | 傳送門

數據可視化【十四】交互式過濾地區分布圖

在前面的博客中已經介紹了如何繪制地區分布圖&#xff0c;這一節學習如何繪制交互式過濾地區分布圖。如果對繪制地區分布圖還不熟悉的話可以了解一下之前我寫的博客&#xff1a;數據可視化【十三】地區分布圖 整體的框架仍然是在之前的基礎上進行修改&#xff0c;主要是添加交…

Ubuntu環境搭建

本文記錄了一些常用的Ubuntu軟件 然后首先修改軟件源&#xff1a;軟件和更新->Ubuntu軟件->下載自&#xff1a;其他站點&#xff08;修改為阿里云&#xff09; 在關閉的時候需要更新什么的 然后修改更新方式&#xff0c;將不支持的更新去掉 常用的Windows軟件 網易云…