[D3] Build a Line Chart with D3 v4
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的更多相关文章
- [D3] Build an Area Chart with D3 v4
Similar to line charts, area charts are great for displaying temporal data. Whether you’re displayin ...
- [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 ...
- [D3] Build a Scatter Plot with D3 v4
Scatter plots, sometimes also known as bubble charts, are another common type of visualization. They ...
- 使用Aspose.Cells 根据模板生成excel里面的 line chart
目的: 1.根据模板里面的excel数据信息,动态创建line chart 2.linechart 的样式改为灰色 3.以流的形式写到客户端,不管客户端是否装excel,都可以导出到到客户端 4.使用 ...
- 关于k Line Chart (k线图)
K Line Chart python实现k线图的代码,之前找过matplotlib中文文档但是画k线图的finance方法已经弃用了.所以自己在网上搜寻一下加上改编,很好的实现出k线图, 代码如下: ...
- ./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 ...
- 使用 angular directive 和 json 数据 D3 随着标签 donut chart演示样本
使用angular resource载入中priorityData.json中间json数据,结合D3绘制甜甜圈图.执行index.html其结果见于图.: priorityData.json中jso ...
- [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 ...
- d3可视化实战02:理解d3数据驱动的真正含义
前文中已经提到,SVG从诞生之初起就可以非常方便地使用javascript脚本语言来进行其DOM对象的控制.当然,控制的方法有很多,有直接控制SVG对象的方法,例如使用原生js:有帮你封装一下图形接口 ...
随机推荐
- 休假结束,Linus重回内核开发岗位
在休假反省一个多月之后,Linus Torvalds 又回来了.10 月 22 日爱丁堡举行的欧洲开源峰会上,Linus Torvalds 将与内核维护者们碰头,这是他重新接管Linux内核开发的第一 ...
- Httpd 文件服务器的搭建
服务器信息 系统: CentOS 安装操作 安装 httpd 直接通过 yum 安装: yum install httpd 安装完成之后,可以检查版本: http 查看版本 httpd -versio ...
- Web测试要点 做移动端的测试,也做web端的测试,甚至后面桌面端的测试和后台的测试也做了,基本上把我们产品各个端都玩了一轮
Web测试要点 一.功能测试 1.链接测试 (1).测试所有链接是否按指示的那样确实链接到了该链接的页面: (2).测试所链接的页面是否存在: (3).保证Web应用系统上没有孤立的页面(所谓孤立 ...
- OpenJDK源码研究笔记(十三):Javac编译过程中的上下文容器(Context)、单例(Singleton)和延迟创建(LazyCreation)3种模式
在阅读Javac源码的过程中,发现一个上下文对象Context. 这个对象用来确保一次编译过程中的用到的类都只有一个实例,即实现我们经常提到的"单例模式". 今天,特意对这个上下文 ...
- 【2017 Multi-University Training Contest - Team 1 1002】Balala Power!
[Link]:http://acm.hdu.edu.cn/showproblem.php?pid=6034 [Description] 给你n个字符串; 每个字符串都仅由小写字母组成; 然后,你可以把 ...
- C# async/await异步编程深入理解
异步函数简介 一般指 async 修饰符声明得.可包含await表达式得方法或匿名函数. 声明方式 异步方法的声明语法与其他方法完全一样, 只是需要包含 async 关键字.async可以出现在返回值 ...
- BZOJ——1012: [JSOI2008]最大数maxnumber || 洛谷—— P1198 [JSOI2008]最大数
http://www.lydsy.com/JudgeOnline/problem.php?id=1012|| https://www.luogu.org/problem/show?pid=1198 T ...
- UVA - 10032 Tug of War (二进制标记+01背包)
Description Problem F: Tug of War A tug of war is to be arranged at the local office picnic. For the ...
- 基于二叉树和双向链表实现限制长度的最优Huffman编码
该代码採用二叉树结合双向链表实现了限制长度的最优Huffman编码,本文代码中的权重所有採用整数值表示.http://pan.baidu.com/s/1mgHn8lq 算法原理详见:A fast al ...
- mongodb官网文档阅读笔记:write concern
write concern保证了mongodb写操作的级别,不同的write concern设置相应了不同级别的写操作.设置的级别越高.那么写操作的性能的持久化做得越好,可是写性能也就越差. mong ...