[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)); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2016-08-14 [Web] What Is JSONP?
2016-08-14 [React Fundamentals] Introduction to Properties
2016-08-14 [React Fundamentals] Development Environment Setup
2014-08-14 [CSS] Pseduo
2014-08-14 [Backbone] First Application!!!!