<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.3/d3.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<svg id="test" width="500" height="400"></svg>
</body>
</html>
<script>
var data = [
{
date: '2019-01-01',
value: 100,
group: 1
},
{
date: '2019-01-02',
value: 200,
group: 1
},
{
date: '2019-01-03',
value: 200,
group: 2
},
{
date: '2019-01-04',
value: 200,
group: 3
},
{
date: '2019-01-05',
value: 100,
group: 3
},
{
date: '2019-01-06',
value: 250,
group: 3
}
]
var groupedData = d3.nest()
.key(function(d) { return d.group; })
.rollup(function(v) { return {
count: v.length,
lastDate: v[v.length-1].date + ' 12:00:00'
}; })
.entries(data)
var groupedData = groupedData.map((d, i) => {
const prev = groupedData[(i - 1)]
const cumsum = prev ? d.value.count + prev.cumsum : d.value.count
d.cumsum = cumsum
return d
})
const svg = d3.select('svg')
var width = 500
var xscaleTime = d3.scaleTime()
.domain([new Date('2019-01-01'), new Date('2019-01-06')])
.range([0,500]).nice()
var bandwidth = (xscaleTime(new Date(groupedData[1].value.lastDate))
- xscaleTime(new Date(groupedData[0].value.lastDate)))
var padding = 20
const b = svg.append("g")
const t = b.append("g").call( d3.axisBottom().scale(xscaleTime))
const g = b.append("g")
.attr("class", "group-labels")
.attr("y", 30)
g.selectAll(".group-label")
.data(groupedData)
.enter()
.append("text")
.attr("class", "group-label")
.attr("x", function(d, i) {
return xscaleTime(new Date (d.value.lastDate)) - bandwidth *((d.value.count-1)/2)
})
.attr("y", 50)
.attr("text-anchor", "middle")
.text(function(d,i){
return 'is Group ' + d.key
})
</script>
xScale.bandwidth()
? - ivan