JSFiddle - React, Tailwind, and code Playground
by kontrach
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
JavaScript
const data = [{
date: '2017-01-21'
}, {
date: '2017-04-01'
}, {
date: '2017-05-21'
}, {
date: '2017-12-12'
}];
const buttonWidth = 24;
const firstNotRealDate = moment(data[0].date).add(-5, 'days');
const lastNotRealDate = moment(data[data.length - 1].date).add(+5, 'days');
const container = d3.select("body");
const svg = container.append("svg")
.attr("width", 500)
.attr("height", 300);
const margin = { top: 0, right: 10, bottom: 20, left: 10 };
const width = +svg.attr("width");
const height = +svg.attr("height");
//first date
const firstDateMonth = svg.append("text")
.text(moment(data[0].date).format('MMM'))
.attr('x', margin.left)
.attr('y', height - margin.bottom - 5);
const firstDateYear = svg.append("text")
.text(moment(data[0].date).format('YYYY'))
.attr('x', margin.left)
.attr('y', height - margin.bottom + 10);
//last date
const lastDateMonth = svg.append("text")
.text(moment(data[data.length - 1].date).format('MMM'))
.attr('x', width - 50)
.attr('y', height - margin.bottom - 5);
const lastDateYear = svg.append("text")
.text(moment(data[data.length - 1].date).format('YYYY'))
.attr('x', width - 50)
.attr('y', height - margin.bottom + 10);
const group = svg.append("g");
// Create scale
const x = d3.scaleTime()
.domain([new Date(firstNotRealDate), new Date(lastNotRealDate)])
.range([margin.left + 50, width - margin.right - 50]);
// Add axis
const axisGroup = group.append("g");
axisGroup
.attr("class", "axis")
.attr("transform", "translate(0," + (height - margin.bottom) + ")")
.call(d3.axisBottom(x).tickSize(0).tickFormat(d3.timeFormat("%b")))
.selectAll("text").remove();
// Add dots
const dotsGroup = group.append("g")
.attr("fill-opacity", 1)
.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("class", "circle")
.attr("transform", function(d) {
return "translate(" + x(new Date(d.date)) + "," + (height - margin.bottom)+ ")";
})
.attr("r", 5);