Skip to content

Instantly share code, notes, and snippets.

@zemirco
Last active June 4, 2018 20:07
Show Gist options
  • Save zemirco/280fe14ac9f2b7385ce7cc11dbd7ef7a to your computer and use it in GitHub Desktop.
Save zemirco/280fe14ac9f2b7385ce7cc11dbd7ef7a to your computer and use it in GitHub Desktop.
d3 simple
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<style>
.line {
fill: none;
stroke: steelblue;
stroke-width: 1;
}
.dot {
fill: steelblue;
stroke: #fff;
stroke-width: 3;
}
</style>
</head>
<body>
<svg></svg>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
// const width = 640
// const height = 480
const width = document.body.clientWidth
const height = 480
const margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
}
const w = width - margin.left - margin.right
const h = height - margin.top - margin.bottom
const svg = d3.select('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`)
const data = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]
const xScale = d3.scaleLinear()
.domain([0, data.length - 1])
.range([0, w])
const yScale = d3.scaleLinear()
.domain([0, 10])
.range([h, 0])
const line = d3.line()
.x((d, i) => xScale(i))
.y(d => yScale(d))
const xAxis = d3.axisBottom(xScale)
svg.append('g')
.attr('class', 'x axis')
.attr('transform', `translate(0, ${h})`)
.call(xAxis)
const yAxis = d3.axisLeft(yScale)
svg.append('g')
.attr('class', 'y axis')
.call(yAxis)
svg.append('path')
.datum(data)
.attr('class', 'line')
.attr('d', line)
svg.selectAll('.dot')
.data(data)
.enter()
.append('circle')
.attr('class', 'dot')
.attr('cx', (d, i) => xScale(i))
.attr('cy', d => yScale(d))
.attr('r', 5)
window.onresize = () => {
const width = document.body.clientWidth
const svg = d3.select('svg')
.attr('width', width)
const w = width - margin.left - margin.right
xScale.range([0, w])
line.x((d, i) => xScale(i))
const xAxis = d3.axisBottom(xScale)
svg.select('.x.axis')
.call(xAxis)
svg.selectAll('.dot')
.attr('cx', (d, i) => xScale(i))
svg.select('.line')
.attr('d', line)
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment