前言
从freecodecamp中得知了d3.js,在官网上看到了那么多高大上的例子,不禁想要多加了解它
d3.js介绍
D3.js是一套javaScript函数库,包含一整组操纵画图很好的辅助工具,还有很方便element操作模型
需掌握javascript,html和css与svg
废话不多说,先上例子(用d3的3.5.3版本)
柱形图
定义变量
|
|
设置svg画布
- 为了改变轴相对于基址图的位置,可以指定g元素上的 transform 变换属性,此处改变的是svg图
|
|
坐标轴渲染
- 先定义x,y轴比例尺,本例使用
d3.time.scale()
[日期比例尺]与d3.scale.linear()
[线性比例尺],然后再设置范围和定义域,注意:svg的x,y轴的方向是由左上角向右与下延伸
|
|
- x,y轴的渲染设置,
d3.svg.axis.scale()
是将比例尺应用在坐标轴上,orient()
指刻度的方向,ticks()
刻度出现的频率,而ticks(d3.time.year,5)
指的是每5年一个刻度,同样的代表时间的还有d3.time.minute
/d3.time.seconds
|
|
- 渲染x,y轴,
attr(y,)
表示相对于svg坐标y轴的位置,而attr(dy,)
是偏离于y的值其中attr('tranform','translate(left,top)')
是偏离(x,y)当前位置,然后call()
相应的坐标轴渲染设置
|
|
画图
- 设置选择器,此处通过append(‘rect’)来画矩形图
|
|
- 设置矩形具体信息
|
|
- 为其绑定事件
|
|
散布图
此处便只post上与柱形图不同的核心代码
绘制比例尺
- 由于x轴单位为Minutes Behind Fastest Time,而date对象中并没有直接地对分钟的提取,故需要使用
tickFormat()
函数来设置刻度格式,事实上,在此时,ticks指定的参数也要传递给scale.tickFormat
方法
|
|
画图
|
|
热图
分析:本例使用的
d3.json()
来获取数据,凡是画图表,重中之重仍是比例尺的绘制。现在让我们来分析一下如何绘制该比例尺吧。
首先是x轴的绘制,此处与我们上述的代码都相似
|
|
然后便是monthLabel的设置,它的方位是在y轴位置,但此处无需按照我们先前设置比例尺后,再绘制坐标轴,因为无需显示刻度线。
|
|
自定义颜色比例尺,该比例尺乃是热图的特点,通过自定义颜色来确定温度的范围,让数据瞬间一目了然。
此处需要用到d3.scale.quantile()
量化比例尺,定义域是用于可视化的数据维度,值域则是输出的可视化维度,用在此处便恰当好处。
|
|
然后便开始画图了,注意
d3.event.pageX
表示当前交互物件相对于svg的坐标
|
|
力导学图
这时候我需要介绍一种关于d3的力导学图布局给大家,d3.layout.force()
,力导学图可以反映事物之间的关系,下面以国家间的关系为例。
Show National Contiguity with a Force Directed Graph
作品
现在让我来说一下思路
- 布局(数据转换)
|
|
- 使力学作用作用生效
|
|
- 绘制
- line 线段
- circle 节点
|
|
- 更新节点和连线位置(因为力导向图是时刻变化的,重中之重)
|
|
效果示例
- 柱形图
See the Pen Visualize Data with a Bar Chart by vivian (@leoCecilia) on CodePen.
- 散布图
See the Pen Visualize Data with a Scatterplot Graph by vivian (@leoCecilia) on CodePen.
- 热点图
See the Pen Visualize Data with a Heat Map by vivian (@leoCecilia) on CodePen.
- 力导向图
See the Pen Force Directed Graph by vivian (@leoCecilia) on CodePen.