Created
March 12, 2017 22:51
-
-
Save stayradiated/2c272c07256e110f257af37b510536c0 to your computer and use it in GitHub Desktop.
D3 Dot Graph
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
snap | audience | |
---|---|---|
0 | 100 | |
1 | 95 | |
2 | 82 | |
3 | 78 | |
4 | 61 | |
5 | 59 | |
6 | 42 | |
7 | 30 | |
8 | 29 | |
9 | 15 |
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> | |
<svg width='960' height='200'></svg> | |
<script src='https://d3js.org/d3.v4.min.js'></script> | |
<script> | |
const svg = d3.select('svg') | |
const margin = {top: 20, right: 20, bottom: 30, left: 50} | |
const width = +svg.attr('width') - margin.left - margin.right | |
const height = +svg.attr('height') - margin.top - margin.bottom | |
const g = svg.append('g') | |
.attr('transform', `translate(${margin.left},${margin.top})`) | |
const x = d3.scaleLinear() | |
.rangeRound([0, width]) | |
const y = d3.scaleLinear() | |
.rangeRound([height, 0]) | |
const yAxis = d3.axisRight(y) | |
.ticks(5) | |
.tickSize(width) | |
.tickFormat('') | |
const line = d3.line() | |
.x((d) => x(d.snap)) | |
.y((d) => y(d.audience)) | |
const area = d3.area() | |
.x((d) => x(d.snap)) | |
.y1((d) => y(d.audience)) | |
const background = '#814ac2' | |
d3.csv('data.csv', (d) => { | |
d.snap = parseInt(d.snap, 10) | |
d.audience = parseInt(d.audience, 10) | |
return d | |
}, (error, data) => { | |
if (error) throw error | |
console.log(data) | |
x.domain(d3.extent(data, (d) => d.snap)) | |
y.domain([0, 100]) | |
area.y0(y(0)) | |
g.append('g') | |
.call(customYAxis) | |
g.append('path') | |
.datum(data) | |
.attr('fill', background) | |
.attr('opacity', 0.38) | |
.attr('d', area) | |
g.append('path') | |
.datum(data) | |
.attr('fill', 'none') | |
.attr('stroke', background) | |
.attr('stroke-linejoin', 'round') | |
.attr('stroke-linecap', 'round') | |
.attr('stroke-width', 1.5) | |
.attr('d', line) | |
g.selectAll('dot') | |
.data(data) | |
.enter().append('circle') | |
.attr('r', 2.5) | |
.attr('fill', background) | |
.attr('cx', (d) => x(d.snap)) | |
.attr('cy', (d) => y(d.audience)) | |
}) | |
function customYAxis(g) { | |
g.call(yAxis); | |
g.select('.domain').remove(); | |
g.selectAll('.tick line') | |
.attr('stroke-opacity', 0.5) | |
.attr('stroke', '#000') | |
.attr('stroke-dasharray', '1,10'); | |
g.selectAll('.tick text').attr('x', 4).attr('dy', -4); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment