D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
michalmatwie
Full window
Github gist
area graph
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } .line {fill: none; stroke: rgb(54,218,255); stroke-width: 2} .line2 {fill: none; stroke: violet; stroke-width: 1} .area1 {fill: url(#lgrad)} </style> </head> <body> <svg height='500' width='500'> <defs> <linearGradient id="lgrad" x1="50%" y1="0%" x2="50%" y2="100%" > <stop offset="0%" style="stop-color:rgb(54,218,255);stop-opacity:0.5" /> <stop offset="40%" style="stop-color:rgb(0,255,255);stop-opacity:0.14" /> <stop offset="73%" style="stop-color:rgb(0,255,255);stop-opacity:0" /> </linearGradient> </defs> </svg> <script> function dataGen() { let res = []; for (let i = 1; i <= 12; i++) { let dataPoint = { date: `2017-${i}-1`, value: 100 + Math.random() * 80 } res.push(dataPoint); } return res; } let data = dataGen(); let data2 = dataGen(); let joinedData = data.concat(data2) const svg = d3.select('svg') const g = svg.append('g').attr('transform', `translate(${50}, ${50})`); const yScale = d3.scaleLinear().domain([0, d3.max(joinedData, d => d.value)]).range([300, 50]); const monthScale = d3.scaleTime().domain(d3.extent(data, d => new Date(d.date))).range([0, 400]) const xAxis = d3.axisBottom(monthScale) .tickFormat(d3.timeFormat('%b')) .tickSize(-260) const yAxis = d3.axisLeft(yScale).ticks(3).tickSize(0) yScale() g.selectAll('rect') .data(data) .enter() .append('circle') .attr('cx', d => monthScale(new Date(d.date))) .attr('cy', d => yScale(d.value)) .attr('r', 0) g.append('g') .call(xAxis) .attr('transform', 'translate(0, 300)') g.append('g') .call(yAxis) const line = d3.line() .x(d => monthScale(new Date(d.date))) .y(d => yScale(d.value)) .curve(d3.curveCardinal.tension(0.5)) const area = d3.area() .x(d => monthScale(new Date(d.date))) .y1(d => yScale(d.value)) .curve(d3.curveCardinal.tension(0.5)) area.y0(yScale(0)) g.append('path') .datum(data) .attr('class', 'line') .attr('d', line) g.append('path') .datum(data) .attr('class', 'area1') .attr('d', area) g.append('path') .datum(data2) .attr('class', 'line2') .attr('d', line) </script> </body>
https://d3js.org/d3.v4.min.js