d3.js直方图与座标轴基础

d3.js直方图与座标轴基础

LSD_Monkey

这里讲一下怎么样用d3.js,输入一个数据list,根据数据画一个带有座标轴的简单直方图.
以下是目标效果.

 

a plot

直方图部分


引入d3.
<script src="//d3js.org/d3.v4.min.js"></script>

画矢量图需要画布,首先,创建新svg:

<script>
var width = 800;  //定义宽度
var height = 800;   //定义高度
var svg = d3.select("body")     //选择<body>标签
    .append("svg")          //在其中加入<svg>标签
    .attr("width", width)      //设定宽度 
    .attr("height", height)   //设定高度
    .attr("style", "border: 1px solid black"); //给一个边框
</script>

空白 svg

我的数据为一个数组:var dataset = [ 25, 6, 21 , 17 , 13 , 9, 6, 2, 20 ];
我想让我的直方图向右,纵向排列.
每一个矩形的x向长度既表示了数据的大小.
那么第一个要解决的问题就是,怎么把原始数据换算成像素,肯定不能直接画25px,6px...
这个时候就需要一个比例尺了.

d3提供的连续比例尺可以这么写:

var linear = d3.scaleLinear()
        .domain([0, d3.max(dataset)])
        .range([ 0,400]);

定义变量linear为一个连续比例尺,定义域.domain,值域.range.
在这里,定义域 .domain([0, d3.max(dataset)])是指,我比例尺输入的数据最小为0,最大是原dataset里最大的那个数(25),所以输入比例尺的定义域为0到25,换算后的值域为0到400px,既——数据0对应0px,数据25对应400px.

有了长度比例尺,就可以画直方图了.

var rectHeight = 30;   
svg.selectAll("rect")
    .data(dataset)
    .enter()
    .append("rect")
    .attr("x",0)
    .attr("y",function(d,i){
         return i * (rectHeight + 5);
    })
    .attr("width",function(d){
         return linear(d);
    })
    .attr("height",rectHeight)
    .attr("fill","steelblue")
    .attr("opacity",0.4);

在这里,先定义了每一个矩形框框的高度为30px,
.data()绑定数据dataset
.enter()方法是专门用在这种,根据输入数据动态新建元素的情况下的,具体可以参考官方说明:

# selection.enter() <>
Returns the enter selection: placeholder nodes for each datum that had no corresponding DOM element in the selection. (The enter selection is empty for selections not returned by selection.data.)
**The enter selection is typically used to create “missing” elements corresponding to new data. **For example, to create DIV elements from an array of numbers:

var div = d3.select("body") .selectAll("div")
  .data([4, 8, 15, 16, 23, 42]) 
  .enter()
  .append("div")
  .text(function(d) { return d; });

If the body is initially empty, the above code will create six new DIV elements, append them to the body in-order, and assign their text content as the associated (string-coerced) number:

<div>4</div>
<div>8</div>
<div>15</div>
<div>16</div>
<div>23</div>
<div>42</div>

Conceptually, the enter selection’s placeholders are pointers to the parent element (in this example, the document body). The enter selection is typically only used transiently to append elements, and is often merged with the update selection after appending, such that modifications can be applied to both entering and updating elements.

所以,在这里,我们既是根据输入dataset来新建<rect>,
怎么根据呢?
属性设置里面:

    .attr("x",0)
    .attr("y",function(d,i){
         return i * (rectHeight + 5);
    })
    .attr("width",function(d){
         return linear(d);
    })
    .attr("height",rectHeight)

表示的是,对于每一个新建的矩形<rect>,x座标为0,y座标为序号*矩形高度+5px. (5px是矩形之间的空格)
可以理解为,在(0,0)放置一个高度为30px的矩形,再在(0,35)放一个,再在(0,70)放一个,再在(0,105)放一个...
而矩形的宽度要和我们的数据保持一致,所以width属性,输入了一个无名函数

function(d){
    return linear(d);
}

这个函数是什么意思呢,当选择集需要使用被绑定的数据时,常需要这么使用。其包含两个参数,其中:

  • d 代表数据,也就是与某元素绑定的数据
  • i 代表索引,代表数据的索引号,从 0 开始
    所以在这里,每个矩形的宽度,是通过比例尺返回的像素值return linear(d).
    当完成这一部后,我们的矩形就显示出来了. 其中最长的一根应该就是代表25的400像素,看右边监视栏的第一个rect,正好就是400的宽度.
    <rect x="0" y="0" width="400" height="25" fill="steelblue" opacity="0.4"></rect>

显示出的矩形

座标轴部分


有了直方图的矩形,我们现在来画一个座标轴.
座标轴有4种:

座标轴类型

 

分别是什么样子的呢,我们来试一试.
在API使用规范里这样写到:

Regardless of orientation, axes are always rendered at the origin. To change the position of the axis with respect to the chart, specify a transform attribute on the containing element. For example:

d3.select("body").append("svg") 
        .attr("width", 1440) 
        .attr("height", 30)
    .append("g") 
        .attr("transform", "translate(0,30)") 
        .call(axis);

意思是,在使用座标轴的时候,必须先添加一个<g>元素,再.call(axis)调用axis. 而默认座标轴都是从原点(0,0)开始画,如果需要调整位置,在属性transform里设置translate(x,y)

所以,我们测试一下在(30,30)画一个axisTop.

var axis = d3.axisTop(linear);//新建一个axisTop座标轴,比例尺为linear
  svg.append("g") //调用
        .attr("transform", "translate(30,30)")//位置(30,30)
        .call(axis);

我们得到结果如下:

 

座标轴

 

而每个座标轴是由哪些部分组成的呢:

 

座标轴的组成


一个横线轴<path class="domain>,和许许多多的<g class="tick">
而且在每一个<g class="tick">内部,有一个<line>和一个<text>.
<line>就是用来画座标轴每一个小分割那条小竖线的,text就是座标轴上的数据.
那么,我们要怎么才能修改这些呢.
查阅API得知axis.tickValues([values])可以直接用来传入一系列座标轴分割点.
试一试:

 

var axis = d3.axisTop(linear)
          .tickValues([0,1, 2, 3, 5, 8, 13, 21,25]);

 

自定义左座标轴分割


果然,座标轴根据我们输入的数据进行了分割.
我们还可以用axis.tickSize([size])来更改每一个分割的大小.
这一次我们画一个向下的座标轴,设定每一个分割为300px:

 

var axis = d3.axisBottom(linear)
          .tickSize(300)
          .tickValues([0,1, 2, 3, 5, 8, 13, 21,25]);

svg.append("g") //调用
        .attr("transform", "translate(0,0)")//位置(0,0)
        .call(axis);

改变分割长度

除此之外,我们还可以改样式.
我们知道了每一个座标轴有一个<path class="domain>,我们可以试试更改样式.

 svg.selectAll("path")
        .attr("stroke","red").attr("stroke-width","5" );

更改path样式

而且在每一个<g class="tick">内部,有一个<line>和一个<text>.
<line>,这两个元素的可用属性可以参考linetext
最终,实现效果:

var axis = d3.axisBottom(linear)
          .tickSize(300)
          .tickValues([0,1, 2, 3, 5, 8, 13, 21,25]);

svg.append("g")
        .attr("transform", "translate(10,10)")
   .call(axis);

svg.selectAll("line")
        .attr("stroke","green")
        .attr("stroke-dasharray","2.2");

svg.selectAll("text")
        .attr("dy","2em");

svg.select(".domain").remove()

a plot

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章