I have a line chart built in d3.js. I needed some help with some customisation. I am looking to split x-axis text labels in two lines. I want the date in one line and the month in another.
The present chart has "14 Dec" in one line.
The present chart:
The x-axis labels are split into 2 lines here. Date and month in 2 different lines.
Expected x-axis:
Codepen link
var xScale = d3.time.scale().domain([data[0][xkeyVal], data[data.length - 1][xkeyVal]]).range([margin.left, width]);
var yScale = d3.scale.linear().domain([0, d3.max(data, function(d) {
return d[ykeyVal];
})]).range([height, margin.left]);
var xAxisGen = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(_config.keys.xAxis.ticks)
.tickFormat(d3.time.format("%d %b"))
.tickSize(0);
var yAxisGen = d3.svg.axis()
.scale(yScale)
.orient("left")
.tickValues(_config.keys.yAxis.tickValues.length > 0 ? _config.keys.yAxis.tickValues : 1)
.tickSize(0);
I'd do it after generating the axis:
svg.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," +height + ")")
.call(_config.xAxisGen)
.selectAll('.x .tick text') // select all the x tick texts
.call(function(t){
t.each(function(d){ // for each one
var self = d3.select(this);
var s = self.text().split(' '); // get the text and split it
self.text(''); // clear it out
self.append("tspan") // insert two tspans
.attr("x", 0)
.attr("dy",".8em")
.text(s[0]);
self.append("tspan")
.attr("x", 0)
.attr("dy",".8em")
.text(s[1]);
})
});
Updated example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With