Line charts are often used to plot temporal data, like a stock price over time. In this lesson we’ll see how to use D3 APIs to create our own simplified version of the charts seen on Google Finance.

var margin = {
top: 10,
right: 20,
bottom: 65,
left: 40
};
var width = 400 - margin.left - margin.right;
var height = 600 - margin.top - margin.bottom; var svg = d3.select('.chart')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.call(responsivefy)
.append('g')
.attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')'); /**
* Load data
*/
d3.json('../data/data3.json', function (err, data) {
const parseTime = d3.timeParse('%Y/%m/%d'); data.forEach(company => {
company.values.forEach(d => {
d.date = parseTime(d.date)
d.close = +d.close
})
}) /**
* x axis
*/
const xScale = d3.scaleTime()
.domain([
d3.min(data, co => d3.min(co.values, d => d.date)),
d3.max(data, co => d3.max(co.values, d => d.date))
])
.range([0, width])
.nice();
svg.append('g')
.attr('transform', `translate(0, ${height})`)
.call(d3.axisBottom(xScale).tickSize(10).tickPadding(5))
.selectAll('text')
.attr('text-anchor', 'end')
.attr('transform', 'rotate(-45)'); /**
* Y axis
*/
const yScale = d3.scaleLinear()
.domain([
d3.min(data, co => d3.min(co.values, d => d.close)),
d3.max(data, co => d3.max(co.values, d => d.close))
])
.range([height, 0])
.nice();
svg.append('g')
.call(d3.axisLeft(yScale)); /**
* Create lines
*/
const line = d3.line()
.x(d => xScale(d.date))
.y(d => yScale(d.close))
.curve(d3.curveCatmullRom.alpha(0.5)); //smmoth the line svg
.selectAll('.line')
.data(data)
.enter()
.append('path')
.attr('class', 'line')
.attr('d', d => line(d.values)) // draw the line
.style('stroke', (d, i) => ['#FF9900', '#3369E8'][i])
.style('stroke-width', 2)
.style('fill', 'none');
}); function responsivefy(svg) {
// get container + svg aspect ratio
var container = d3.select(svg.node().parentNode),
width = parseInt(svg.style("width")),
height = parseInt(svg.style("height")),
aspect = width / height; // add viewBox and preserveAspectRatio properties,
// and call resize so that svg resizes on inital page load
svg.attr("viewBox", "0 0 " + width + " " + height)
.attr("preserveAspectRatio", "xMinYMid")
.call(resize); // to register multiple listeners for same event type,
// you need to add namespace, i.e., 'click.foo'
// necessary if you call invoke this function for multiple svgs
// api docs: https://github.com/mbostock/d3/wiki/Selections#on
d3.select(window).on("resize." + container.attr("id"), resize); // get width of container and resize svg to fit it
function resize() {
var targetWidth = parseInt(container.style("width"));
svg.attr("width", targetWidth);
svg.attr("height", Math.round(targetWidth / aspect));
}
}

[D3] Build a Line Chart with D3 v4的更多相关文章

  1. [D3] Build an Area Chart with D3 v4

    Similar to line charts, area charts are great for displaying temporal data. Whether you’re displayin ...

  2. [D3] Build a Column Chart with D3 v4

    Column and bar charts are staples of every visualization library. They also make a great project for ...

  3. [D3] Build a Scatter Plot with D3 v4

    Scatter plots, sometimes also known as bubble charts, are another common type of visualization. They ...

  4. 使用Aspose.Cells 根据模板生成excel里面的 line chart

    目的: 1.根据模板里面的excel数据信息,动态创建line chart 2.linechart 的样式改为灰色 3.以流的形式写到客户端,不管客户端是否装excel,都可以导出到到客户端 4.使用 ...

  5. 关于k Line Chart (k线图)

    K Line Chart python实现k线图的代码,之前找过matplotlib中文文档但是画k线图的finance方法已经弃用了.所以自己在网上搜寻一下加上改编,很好的实现出k线图, 代码如下: ...

  6. ./utils/build.sh: line 131: patch: command not found

    安装 percona-xtrabackup-2.1.5过程中遇到如下问题: [root@test percona-xtrabackup-2.1.5]# ./utils/build.sh innodb5 ...

  7. 使用 angular directive 和 json 数据 D3 随着标签 donut chart演示样本

    使用angular resource载入中priorityData.json中间json数据,结合D3绘制甜甜圈图.执行index.html其结果见于图.: priorityData.json中jso ...

  8. [D3] Load and Inspect Data with D3 v4

    You probably use a framework or standalone library to load data into your apps, but what if that’s o ...

  9. d3可视化实战02:理解d3数据驱动的真正含义

    前文中已经提到,SVG从诞生之初起就可以非常方便地使用javascript脚本语言来进行其DOM对象的控制.当然,控制的方法有很多,有直接控制SVG对象的方法,例如使用原生js:有帮你封装一下图形接口 ...

随机推荐

  1. Python基础班培训视频课程

    课程目录:│  ├─第01天视频│  │      01-课程介绍.avi│  │      02-什么是操作系统.avi│  │      03-生活中的操作系统.avi│  │      04-操 ...

  2. 实现IE下兼容CSS3的圆角效果

    有些CSS3的牛逼的效果在IE下展示不出来是最烦人的啦,在项目中做的圆角效果到了IE下一堆方块....忒尴尬了...,找了个替代解决方案 1.首先下载一个js插件PIE.js百度一搜都是的,我也就不写 ...

  3. Unity 实现Log实时输出到屏幕或控制台上<一>

    本文章由cartzhang编写,转载请注明出处. 所有权利保留. 文章链接:http://blog.csdn.net/cartzhang/article/details/49818953 作者:car ...

  4. tcp_tw_recycle检查tcp_timestamps的内核代码

    注意:本文档中的内核代码的版本号:linux-4.0.5 /************************************************* * Author : Samson * ...

  5. Unity中uGUI的控件事件穿透逻辑

    1.正常来说Image和Text是会拦截点击事件的,假设加入EventTrigger的话,就能够响应相应的交互事件. 2.假设Image和Text是一个Button的子控件.那么尽管其会显示在Butt ...

  6. solr 亿万级数据查询性能測试

    废话不多说,我电脑配置 i7四核cpu 8G内存 插入数据文档中有5个字段,当中有两个分词.一个int,一个date 批量插入測试一次10万循环10次总共100万用时85秒 批量插入測试一次10万循环 ...

  7. Linux下MySQL允许远程连接以及授权命令

    --针对某个库做授权 GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'%' IDENTIFIED BY 'mypassword' WITH GRANT OPTION; ...

  8. 懒加载js实现和优化

    1.懒加载的作用和原理 在我们展示多图片的场景下,类似淘宝或者百度图片,由于图片的数目过多,全部从服务器请求会给用户糟糕的用户体验,为了提升用户体验,我们这里使用懒加载,随着下拉逐步加载. 每个图片的 ...

  9. 荣获CCF(中国计算机学会)高级会员代表资格

    详细地址:http://www.ccf.org.cn/sites/ccf/xjhydb.jsp?contentId=2624287722908 650) this.width=650;" b ...

  10. pycharm做什么

    pycharm做什么 说实话.作为一个Coder.每天在各种IDE中切换编写Code.如果一个IDE Look and Feel总是无形中影响你每天Code Farm的心情.那该是多么不爽的事情.特别 ...