Built with blockbuilder.org
Created
August 31, 2018 19:58
-
-
Save xmanemran/1ef4b13996ea60abedbfe36eecdaa4d3 to your computer and use it in GitHub Desktop.
Line and area
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
body { margin:0;position:fixed;top:;right:0;bottom:0;left:0; } | |
svg { | |
width: 520px; | |
padding: 10px; | |
height: 520px; | |
background: '#b700b7' | |
} | |
</style> | |
</head> | |
<body> | |
<svg> | |
</svg> | |
<script> | |
console.clear(); | |
var rectWidth = 50; | |
var height = 300; | |
var item = 15; | |
var data = Array(item).fill('').map((x, i) =>{ | |
return { | |
data: Math.random()*1000, | |
year: 2011 + i | |
} | |
}) | |
var svg = d3.select('svg'); | |
var xScale = d3.scaleLinear() | |
.domain(d3.extent(data, d => d.year)) | |
.range([0, 500-40]) | |
var yScale = d3.scaleLinear() | |
.domain(d3.extent(data, d => d.data)) | |
.range([300, 0]) | |
var xAxis = d3.axisBottom() | |
.scale(xScale) | |
.ticks(data.length) | |
var yAxis = d3.axisLeft() | |
.scale(yScale) | |
.ticks(10) | |
var line = d3.line() | |
.x(d => xScale(d.year) + 40) | |
.y(d => yScale(d.data)) | |
.curve(d3.curveCatmullRom.alpha(0.5)); | |
var area = d3.area() | |
.x(d => xScale(d.year) + 40) | |
.y0(height) | |
.y1(d => yScale(d.data) ) | |
.curve(d3.curveCatmullRom.alpha(0.5)); | |
svg.append('path') | |
.attr('d', line(data)) | |
.attr('fill', 'none') | |
.attr('stroke', 'red') | |
.attr('stroke-width', 3) | |
svg.append("path") | |
.attr('d', area(data)) | |
.attr('stroke', 'none') | |
.attr('fill', 'rgba(255, 0, 0, 0.2)') | |
svg.append('g') | |
.attr('transform', 'translate(40, 300)') | |
.call(xAxis) | |
svg.append('g') | |
.attr('transform', 'translate(40, 0)') | |
.call(yAxis) | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment