[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));
    }
}
时间: 08-13

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

[D3] Build a Scatter Plot with D3 v4

Scatter plots, sometimes also known as bubble charts, are another common type of visualization. They’re extremely versatile thanks to their ability to display multiple dimensions of data simultaneously using x and y position, opacity, color, and even

【d3.js实践教程01】d3基本操作

学习d3.js(以下都简称d3)也有一段时间了,运行d3做了几个项目.我发现中文的d3教程很少,国外资料多但要求有一定的英文阅读能力(推荐网址:http://bl.ocks.org/mbostock),于是就萌发了写一个d3实际运用系列文章的想法,现在开始付之行动.在系列中,我会用d3+html5 canvas实现一些实际效果(如统计结果展示,地图数据展示等),希望可以跟大家共同学习交流. 代码我公布在git.cschina.com上,大家可以clone到本地运行,地址是:http://git.

XCL-Charts画线图(Line Chart)

关于线图(Line Chart)如何画,我以前写过很详细的说明,只是在这附一下,现在的基类是怎么弄的. 基类把有关线图的所有相关元素都能开发出来变成可控制的,而隐藏了具体的位置计算,图形绘制计算等待过程,只须传入数据源, 加上自己想要的控制即可得到一个还不错的图表. 附上代码: //线图基类 chart = new LineChart(); //图所占范围大小 chart.setChartRange(0, 0, this.mScrWidth , this.mScrHeight ); //标签1对

使用 angular directive 和 json 数据的 D3 带标签 donut chart示例

利用angular resource加载priorityData.json中的json数据,结合D3画出甜甜圈图.运行index.html结果如图所示: priorityData.json中json数据如下: { "priority":{ "Blocker":12, "Critical":18, "Major":5, "Minor":30, "Trivial":24 } } index.

[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 overkill for your needs? What if you’re just putting together a quick demo? This lesson demonstrates D3’s APIs for loading data on its own, as well as

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

前文中已经提到,SVG从诞生之初起就可以非常方便地使用javascript脚本语言来进行其DOM对象的控制.当然,控制的方法有很多,有直接控制SVG对象的方法,例如使用原生js:有帮你封装一下图形接口再进行直接控制的js类库,如 Raphaël.但是正如我在第一篇文章中所说,d3作为一个中间型类库还能脱颖而出的重要原因,在于它突破了其他类库的那种直接控制表现层的机制,而采用了对于web图形处理领域较为新颖的数据驱动机制(2011),并获得了极大的成功. 数据驱动的历史 数据驱动编程并不是一个新鲜

iOS:Line Chart

下载地址:http://download.csdn.net/detail/ouyangtianhan/8643101

Matplotlib学习---用matplotlib画折线图(line chart)

这里利用Jake Vanderplas所著的<Python数据科学手册>一书中的数据,学习画图. 数据地址:https://raw.githubusercontent.com/jakevdp/data-CDCbirths/master/births.csv 准备工作:先导入matplotlib和pandas,用pandas读取csv文件,然后创建一个图像和一个坐标轴 import pandas as pd from matplotlib import pyplot as plt birth=p

[D3] Basic Interactivity with D3 v4

Data visualizations are a lot more interesting when they’re interactive. Whether it’s clicks, roll overs, or drags, it makes things more compelling, and D3 is up to the task. This lesson demonstrates how to implement basic interactions and shows how