Reputation: 51
I have a dataset
[
{
date: '2015-12',
value: 100,
priority: null,
},
{
date: '2016-01',
value: 200,
priority: 'high',
},
{
date: '2016-02',
value: 200,
priority: null,
},
{
date: '2016-03',
value: 200,
priority: null,
},
{
date: '2016-04',
value: 100,
priority: 'low',
},
{
date: '2016-05',
value: 250,
priority: 'low',
},
{
date: '2016-06',
value: 250,
priority: null,
},
{
date: '2016-07',
value: 100,
priority: null,
},
{
date: '2016-08',
value: 250,
priority: null,
}
]
I've create linear chart with D3 v4. Now I have to fill in chart's segments with background color from top to bottom by priority
field value? like on image (High priority segment should fill in with red color, low - with green, etc.)
Could someone give an example how to implement this behavior, or advice the direction for researching?
Upvotes: 0
Views: 382
Reputation: 668
You can create a band scale that will be used to calculate the width of every tick between two dates as such:
const bandScale = d3.scaleBand()
.domain(data.map(item => item.date).slice(1))
.range([margin.left, width - margin.right])
.paddingInner(0)
After that you can add a new iterator using a rect element before adding the path using:
svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('fill', d => d.priority !== null ?
d.priority === 'high' ? '#FFBBB7' : '#CCFFC4' :
'transparent')
.attr('x', d => x(new Date(d.date)))
.attr('y', margin.top)
.attr('width', bandScale.bandwidth())
.attr('height', height - margin.top - margin.bottom)
Where you will add a rectangle for tick on the x axis where the fill depends on the priority.
Please see the following observable: https://observablehq.com/@cstefanache/simple-line-chart
Upvotes: 1