JSFiddle - React, Tailwind, and code Playground
by Rich Shih
HTML
<script src="https://d3js.org/d3.v4.min.js"></script>
<div class="container" style="width: 600px; height: 300px">
<svg id='chart'></svg>
</div>
CSS
* {
margin: 0;
padding: 0;
}
body {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
div.container {
background: gainsboro;
border: 2px solid gainsboro;
}
svg#chart {
position: relative;
width: 100%;
height: 100%;
background: tomato;
}
.axis line {
stroke: gainsboro;
shape-rendering: crispEdges;
}
.axis path {
stroke-width: 0;
fill: none;
}
.axis text {
fill: gainsboro;
}
.grid line {
stroke: lightgrey;
stroke-opacity: 0.7;
shape-rendering: crispEdges;
}
.grid path {
stroke-width: 0;
}
.grid text {
fill: gainsboro;
}
JavaScript
//https://bl.ocks.org/d3noob/c506ac45617cf9ed39337f99f8511218
var svg = d3.select("svg#chart");
var element = svg.node();
var Width = element.getBoundingClientRect().width,
Height = element.getBoundingClientRect().height;
var margin = {
top: 25,
right: 25,
bottom: 40,
left: 40
},
width = Width - margin.left - margin.right,
height = Height - margin.top - margin.bottom;
// 1) Append g and transform by margins
var g = svg
.append('g')
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
// converts string to Date object http://learnjsdata.com/time.html
var parseTime = d3.timeParse("%d-%b-%y");
x.domain(d3.extent(data.map(function(d) {
return parseTime(d[0]);
})));
y.domain([0,1]);
/*
var horizontalLinesGroup = g
.append("g")
.attr("class", "grid")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x)
.ticks(10)
.tickSize(-height)
.tickFormat("")
);
*/
var verticalLinesGroup = g
.append("g")
.attr("class", "grid")
.attr("transform", "translate(0,0)")
.call(d3.axisLeft(y)
.ticks(10)
.tickSize(-width)
.tickFormat("")
)
// add the X Axis
var xAxis = g.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// add the Y Axis
var yAxis = g.append("g")
.attr("class", "axis")
.call(d3.axisLeft(y));
g.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr('cx', function(d, i) {
return x(parseTime(d[0]));
})
.attr('cy', function(d, i) {
return y(d[1]);
})
.attr('r', function(d) {
return 8;
})