D3FC - Color Fill with Tilt X-Axis labels
45 degrees rotate x-axis labels and color customization to match bars colors.
HTML
<script src="https://unpkg.com/d3"></script>
<script src="https://unpkg.com/d3fc"></script>
<div></div>
CSS
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
div {
position: absolute;
padding: 1rem;
top: 0px;
left: 0px;
width: calc(100% - 2rem);
height: calc(100% - 2rem);
}
JavaScript
// a random number generator
const generator = fc.randomGeometricBrownianMotion()
.steps(11);
// some formatters
const dateFormatter = d3.timeFormat('%B');
const valueFormatter = d3.format('$.0f');
const yExtent = fc.extentLinear()
.include([0])
.pad([0, 0.5])
.accessors([d => d.sales]);
const data = {
// Target values for the annotations
targets: [{
name: 'low',
value: 4.5
}, {
name: 'high',
value: 8
}],
// Randomly generated sales data
sales: generator(1).map((d, i) => ({
month: dateFormatter(new Date(0, i + 1, 0)),
sales: d + i / 2
}))
};
const bar = fc.autoBandwidth(fc.seriesSvgBar())
.crossValue(d => d.month)
.mainValue(d => d.sales)
.align('left');
const annotation = fc.annotationSvgLine()
.value(d => d.value);
// Define the chart type
const multi = fc.seriesSvgMulti()
.series([bar, annotation])
.mapping((data, index, series) => {
switch (series[index]) {
case bar:
return data.sales;
case annotation:
return data.targets;
}
});
// Track the labels which are to have its color changed
// when the bar chart colors are also changed
const monthsSalesStatus = {};
bar.decorate(selection => {
// The selection passed to decorate is the one which the component creates
// within its internal data join, here we use the update selection to
// apply a style to 'path' elements created by the bar series
// Change to green
selection.select('.bar > path')
.style('fill', d => {
if (d.sales < data.targets[0].value) {
monthsSalesStatus[d.month] = "low"
return 'inherit';
} else {
monthsSalesStatus[d.month] = "high"
return '#0c0';
}
});
});
annotation.decorate(selection => {
selection.enter()
.select('g.left-handle')
...