D3.js 中 Box Plots详解

2024-02-01 06:20
文章标签 详解 js box d3 plots

本文主要是介绍D3.js 中 Box Plots详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Box Plot

聊聊box plot,将自己阅读、理解d3.js的箱形图源码的过程和思路记录下来……

箱形图(Box-plot)又称为盒须图、盒式图或箱线图,是一种用作显示一组数据分散情况资料的统计图。因形状如箱子而得名。在各种领域也经常被使用,常见于品质管理。 —— [ 百度百科 ]

话不多少,先睹为快,用d3实现的箱形图如图1所示:

图1 箱形图的样图

眨一看,箱形图有点难懂,图中的盒子,以及各种线段上标注的数字,还有那莫名奇妙的小空心圆圈什么意思?其实,我第一眼看也是一脸蒙,接着就查阅相关资料,搞明白了这张神秘的图,请看图2,保证您一秒懂什么是箱形图。

图2 箱形图关键参数标注图

所以,箱形图主要包含六个数据节点,将一组数据从大到小排列,分别计算出他的上边缘(largest value),上四分位数Q3(upper quartile),中位数(median),下四分位数Q1(lower quartile),下边缘(smallest value),还有一个异常值(图中的空心小圆圈所示)

粗略了解了箱形图怎么回事之后,开始研究d3画箱形图的方式,其中包括了三个文件,分别是index.html文件;box.js文件以及样例数据文件morley.csv,下面分别对整个实现过程进行详细解释。

box.js文件解读 —— [ 源码 ]

(function() {// Inspired by http://informationandvisualization.de/blog/box-plot//@onlywan  在该立即执行函数中定义以下一系列操作d3.box = function() {var width = 1,height = 1,duration = 0,domain = null,value = Number,whiskers = boxWhiskers,quartiles = boxQuartiles,   //@onlywan 声明获取四分位数的函数tickFormat = null;// For each small multiple…function box(g) {//@onlywan 以下计算绘制箱形图所需的各种数据参数:// 第一步:对每个数组进行排序;// 第二步:计算每个数组的 上四分位数、下四分位数、中位数、最大值、最小值;// 第三步:获取每个数组最大值、最小值的index;// 第四步:计算每个数组异常值的index;// 第五步:定义比例尺;// 第六步:给各种元素绑定数据并设置相关的属性;g.each(function(d, i) {//@onlywan 先将d数组进行数值类型的映射转换,再按照升序顺序对d数组进行排序d = d.map(value).sort(d3.ascending);   var g = d3.select(this),n = d.length,    //@onlywan 记录数组的长度min = d[0],      //@onlywan 记录数组的最小值max = d[n - 1];  //@onlywan 记录数组的最大值// Compute quartiles. Must return exactly 3 elements.// @onlywan 获取数组d的三个分位数,见boxQuartiles()函数var quartileData = d.quartiles = quartiles(d);// Compute whiskers. Must return exactly 2 elements, or null.// @onlywan 获取数组d的最大值和最小值在数组中的下标,见boxWhiskers()函数,此处命名为//          boxWhiskers,盒子的胡须,自我理解应该是因为箱形图中每个盒子的两端用虚线来//          标识上下边缘数值,看起来长得像胡须,因此命名为whisker吧var whiskerIndices = whiskers && whiskers.call(this, d, i),whiskerData = whiskerIndices && whiskerIndices.map(function(i) { return d[i]; });// Compute outliers. If no whiskers are specified, all data are "outliers".// We compute the outliers as indices, so that we can join across transitions!// @onlywan 获取异常值的下标,即箱形图中的那些小空心圆圈//          d3.range([start,]stop[,step]);返回等差数列函数;如d3.range(6)返回//          [0,1,2,3,4,5]var outlierIndices = whiskerIndices? d3.range(0, whiskerIndices[0]).concat(d3.range(whiskerIndices[1] + 1, n)): d3.range(n);// Compute the new x-scale.//@onlywan d3.scale.linear()来指定比例尺为线性的,返回线性比例尺;//         后面的domain()和range()分别表示 定义域和值域,类似于数学函数中,x的取值范围//         称为定义域,y的取值范围称为值域;//         通过计算得出,此处定义域指定为[min,max],即当前数组的最小值到最大值的区间;//         此处值域指定为[1,0],此处的height是在函数开始定义的,值为1;//         最终比例尺的线性关系满足如 当x=min时,y=height,当x=max时,y=0这样的关系var x1 = d3.scale.linear().domain(domain && domain.call(this, d, i) || [min, max]).range([height, 0]);// Retrieve the old x-scale, if this is an update.//@onlywan 若是某种更新,要恢复旧比例尺,结果要么是图像现有的,要么是定义域为[0,Infinity]//         值域为上边x1中值域var x0 = this.__chart__ || d3.scale.linear().domain([0, Infinity]).range(x1.range());// Stash the new scale.//@onlywan 将新的比例尺函数存储在__chart__变量中;this.__chart__ = x1;// Note: the box, median, and box tick elements are fixed in number,// so we only have to handle enter and update. In contrast, the outliers// and other elements are variable, so we need to exit them! Variable// elements also fade in and out.//@onlywan 上面英文注释中的enter、exit动作是指 d3中的函数 enter()函数和//         exit()函数,enter()函数是选中那些缺少的虚拟dom,exit()函数的//         的作用是选中那些多余的dom元素;两个函数都是选择器;// Update center line: the vertical line spanning the whiskers.//@onlywan 设置中心线的绑定数组,这里将[min,max]数组绑定到中心线上var center = g.selectAll("line.center").data(whiskerData ? [whiskerData] : []);//@onlywan 为缺少中心线的添加 中心线,绑定class、x1,y1,x2,y2属性,并且指//         动画动作;center.enter().insert("line", "rect").attr("class", "center").attr("x1", width / 2).attr("y1", function(d) { return x0(d[0]); }).attr("x2", width / 2).attr("y2", function(d) { return x0(d[1]); }) .style("opacity", 1e-6) .transition() .duration(duration) .style("opacity", 1) .attr("y1", function(d) { return x1(d[0]); }) .attr("y2", function(d) { return x1(d[1]); }); //@onlywan 为中心线添加动画动作以及y坐标的值 center.transition() .duration(duration) .style("opacity", 1) .attr("y1", function(d) { return x1(d[0]); }) .attr("y2", function(d) { return x1(d[1]); }); //@onlywan 为多余出来的中心线元素添加移除动画动作 center.exit().transition() .duration(duration) .style("opacity", 1e-6) .attr("y1", function(d) { return x1(d[0]); }) .attr("y2", function(d) { return x1(d[1]); }) .remove(); // Update innerquartile box. //@onlywan 为box元素绑定数据,数据为三个,上四分位数,下四分位数和中位数 var box = g.selectAll("rect.box") .data([quartileData]); //@onlywan 补充添加缺少的box元素,并且为其添加相关属性及动画 box.enter().append("rect") .attr("class", "box") .attr("x", 0) .attr("y", function(d) { return x0(d[2]); }) .attr("width", width) .attr("height", function(d) { return x0(d[0]) - x0(d[2]); }) .transition() .duration(duration) .attr("y", function(d) { return x1(d[2]); }) .attr("height", function(d) { return x1(d[0]) - x1(d[2]); }); //@onlywan 为box添加动画 box.transition() .duration(duration) .attr("y", function(d) { return x1(d[2]); }) .attr("height", function(d) { return x1(d[0]) - x1(d[2]); }); // Update median line. //@onlywan 为中位线绑定数据 var medianLine = g.selectAll("line.median") .data([quartileData[1]]); //@onlywan 补充缺少的中位线,并且给其添加相关属性及动画 medianLine.enter().append("line") .attr("class", "median") .attr("x1", 0) .attr("y1", x0) .attr("x2", width) .attr("y2", x0) .transition() .duration(duration) .attr("y1", x1) .attr("y2", x1); //@onlywan 为中位线添加动作 medianLine.transition() .duration(duration) .attr("y1", x1) .attr("y2", x1); // Update whiskers. //@onlywan 为盒子两端虚线绑定数据 var whisker = g.selectAll("line.whisker") .data(whiskerData || []); //@onlywan 补充缺少的线,并为其绑定相关属性及动画 whisker.enter().insert("line", "circle, text") .attr("class", "whisker") .attr("x1", 0) .attr("y1", x0) .attr("x2", width) .attr("y2", x0) .style("opacity", 1e-6) .transition() .duration(duration) .attr("y1", x1) .attr("y2", x1) .style("opacity", 1); //@onlywan 为盒子两端虚线绑定动作 whisker.transition() .duration(duration) .attr("y1", x1) .attr("y2", x1) .style("opacity", 1); //@onlywan 去除多余的线 whisker.exit().transition() .duration(duration) .attr("y1", x1) .attr("y2", x1) .style("opacity", 1e-6) .remove(); // Update outliers. //@onlyan 为异常值绑定数据 var outlier = g.selectAll("circle.outlier") .data(outlierIndices, Number); //@onlywan 填补缺少的异常值圆圈,并设定其圆心,半径以及动画等属性 outlier.enter().insert("circle", "text") .attr("class", "outlier") .attr("r", 5) .attr("cx", width / 2) .attr("cy", function(i) { return x0(d[i]); }) .style("opacity", 1e-6) .transition() .duration(duration) .attr("cy", function(i) { return x1(d[i]); }) .style("opacity", 1); //@onlywan 为异常值点绑定动画 outlier.transition() .duration(duration) .attr("cy", function(i) { return x1(d[i]); }) .style("opacity", 1); //@onlywan 去除多余的异常值元素 outlier.exit().transition() .duration(duration) .attr("cy", function(i) { return x1(d[i]); }) .style("opacity", 1e-6) .remove(); // Compute the tick format. //@onlywan 坐标轴刻度格式化函数定义 var format = tickFormat || x1.tickFormat(8); // Update box ticks. //@onlywan 为盒子坐标刻度绑定数据 var boxTick = g.selectAll("text.box") .data(quartileData); //填补缺少的刻度文字及相关属性 boxTick.enter().append("text") .attr("class", "box") .attr("dy", ".3em") .attr("dx", function(d, i) { return i & 1 ? 6 : -6 }) .attr("x", function(d, i) { return i & 1 ? width : 0 }) .attr("y", x0) .attr("text-anchor", function(d, i) { return i & 1 ? "start" : "end"; }) .text(format) .transition() .duration(duration) .attr("y", x1); //@onlywan 定义盒子刻度格式 boxTick.transition() .duration(duration) .text(format) .attr("y", x1); // Update whisker ticks. These are handled separately from the box // ticks because they may or may not exist, and we want don't want // to join box ticks pre-transition with whisker ticks post-. //@onlywan 虚线刻度数据绑定 var whiskerTick = g.selectAll("text.whisker") .data(whiskerData || []); //@onlywan 填补虚线刻度缺少的文字并设置相关属性 whiskerTick.enter().append("text") .attr("class", "whisker") .attr("dy", ".3em") .attr("dx", 6) .attr("x", width) .attr("y", x0) .text(format) .style("opacity", 1e-6) .transition() .duration(duration) .attr("y", x1) .style("opacity", 1); //@onlywan 虚线刻度设置相关属性 whiskerTick.transition() .duration(duration) .text(format) .attr("y", x1) .style("opacity", 1); //@onlywan 去除多余的虚线刻度 whiskerTick.exit().transition() .duration(duration) .attr("y", x1) .style("opacity", 1e-6) .remove(); }); //@onlywan 立刻执行当前没有延迟的计时,常用来处理闪屏问题 d3.timer.flush(); } //@onlywan box的宽度属性设置函数 box.width = function(x) { if (!arguments.length) return width; width = x; return box; }; //@onlywan box的高度属性设置函数 box.height = function(x) { if (!arguments.length) return height; height = x; return box; }; //@onlywan box的刻度格式设置函数 box.tickFormat = function(x) { if (!arguments.length) return tickFormat; tickFormat = x; return box; }; //@onlywan box的动作间隔设置函数 box.duration = function(x) { if (!arguments.length) return duration; duration = x; return box; }; //@onlywan box的定义域设置函数 box.domain = function(x) { if (!arguments.length) return domain; domain = x == null ? x : d3.functor(x); return box; }; //@onlywan box的value属性设置函数 box.value = function(x) { if (!arguments.length) return value; value = x; return box; }; //@onlywan box的虚线设置函数 box.whiskers = function(x) { if (!arguments.length) return whiskers; whiskers = x; return box; }; //@onlywan box的分位数设置函数 box.quartiles = function(x) { if (!arguments.length) return quartiles; quartiles = x; return box; }; //@onlywan 最终返回box对象 return box; }; //@onlywan 获取whisker值在数组d中的index值 function boxWhiskers(d) { return [0, d.length - 1]; } //@onlywan d3.quantile(array, p[, accessor])函数是用来获取排好序的数组的一个分位数 function boxQuartiles(d) { return [ d3.quantile(d, .25), //@onlywan 获取已排序数组d的 下四分位数 d3.quantile(d, .5), //@onlywan 获取已排序数组d的 中位数 d3.quantile(d, .75) //@onlywan 获取已排序数组d的 上四分位数 ]; } })();

index.html文件解读 —— [ 源码 ]

<!DOCTYPE html>
<meta charset="utf-8">
<style>body {font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}.box {font: 10px sans-serif;
}.box line,
.box rect,
.box circle {fill: #fff;stroke: #000;stroke-width: 1.5px;
}.box .center {stroke-dasharray: 3,3;
}.box .outlier {fill: none;stroke: #ccc;
}</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="box.js"></script>
<script>var margin = {top: 10, right: 50, bottom: 20, left: 50},width = 120 - margin.left - margin.right,height = 500 - margin.top - margin.bottom;var min = Infinity,max = -Infinity;//@onlywan  初始化箱形图
var chart = d3.box().whiskers(iqr(1.5)).width(width).height(height);d3.csv("morley.csv", function(error, csv) {if (error) throw error;var data = [];//@onlywan 生成 data[]数组csv.forEach(function(x) {var e = Math.floor(x.Expt - 1),r = Math.floor(x.Run - 1),s = Math.floor(x.Speed),d = data[e];if (!d) d = data[e] = [s];else d.push(s);if (s > max) max = s;if (s < min) min = s;});//@onlywan 定义箱形图的 定义域chart.domain([min, max]);//@onlywan 生成svg元素,给其绑定数据为data数组,并且设置相关的属性var svg = d3.select("body").selectAll("svg").data(data).enter().append("svg").attr("class", "box").attr("width", width + margin.left + margin.right).attr("height", height + margin.bottom + margin.top).append("g") //@onlywan 此处追加一个group元素//@onlywan 转换坐标.attr("transform", "translate(" + margin.left + "," + margin.top + ")").call(chart);//@onlywan 将svg元素给chart函数setInterval(function() {//@onlywan 为svg赋予新的随机数组值,此处用datum函数来一次性为5个svg图赋值,并执行chart函数svg.datum(randomize).call(chart.duration(1000));}, 2000);
});//@onlywan 功能函数,用于变换d
function randomize(d) {if (!d.randomizer) d.randomizer = randomizer(d);return d.map(d.randomizer);
}
//@onlywan 功能函数,用于变换d
function randomizer(d) {var k = d3.max(d) * .02;return function(d) {return Math.max(min, Math.min(max, d + k * (Math.random() - .5)));};
}// Returns a function to compute the interquartile range.
//@onlywan 功能函数,用来计算四分位差,interquartile range ,即IQR,表示四分位差
function iqr(k) {return function(d, i) {var q1 = d.quartiles[0],q3 = d.quartiles[2],iqr = (q3 - q1) * k,i = -1,j = d.length;while (d[++i] < q1 - iqr);while (d[--j] > q3 + iqr);return [i, j];};
}</script>

d3官网对于box plot 图给出的数据是 著名的迈克尔逊-莫雷实验 迈克耳孙-莫雷实验的数据,共5组实验,每组中20个数据,5组实验对应箱形图中5个盒子。【个人理解】

终于把第一个图读完了,今天是黑色星期五之后的星期日,天气还算可以。

这篇关于D3.js 中 Box Plots详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/666322

相关文章

MySQL 主从复制部署及验证(示例详解)

《MySQL主从复制部署及验证(示例详解)》本文介绍MySQL主从复制部署步骤及学校管理数据库创建脚本,包含表结构设计、示例数据插入和查询语句,用于验证主从同步功能,感兴趣的朋友一起看看吧... 目录mysql 主从复制部署指南部署步骤1.环境准备2. 主服务器配置3. 创建复制用户4. 获取主服务器状态5

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

MySql基本查询之表的增删查改+聚合函数案例详解

《MySql基本查询之表的增删查改+聚合函数案例详解》本文详解SQL的CURD操作INSERT用于数据插入(单行/多行及冲突处理),SELECT实现数据检索(列选择、条件过滤、排序分页),UPDATE... 目录一、Create1.1 单行数据 + 全列插入1.2 多行数据 + 指定列插入1.3 插入否则更

Redis中Stream详解及应用小结

《Redis中Stream详解及应用小结》RedisStreams是Redis5.0引入的新功能,提供了一种类似于传统消息队列的机制,但具有更高的灵活性和可扩展性,本文给大家介绍Redis中Strea... 目录1. Redis Stream 概述2. Redis Stream 的基本操作2.1. XADD

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Java JDK1.8 安装和环境配置教程详解

《JavaJDK1.8安装和环境配置教程详解》文章简要介绍了JDK1.8的安装流程,包括官网下载对应系统版本、安装时选择非系统盘路径、配置JAVA_HOME、CLASSPATH和Path环境变量,... 目录1.下载JDK2.安装JDK3.配置环境变量4.检验JDK官网下载地址:Java Downloads

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

MySQL中的LENGTH()函数用法详解与实例分析

《MySQL中的LENGTH()函数用法详解与实例分析》MySQLLENGTH()函数用于计算字符串的字节长度,区别于CHAR_LENGTH()的字符长度,适用于多字节字符集(如UTF-8)的数据验证... 目录1. LENGTH()函数的基本语法2. LENGTH()函数的返回值2.1 示例1:计算字符串

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用