Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 line chart axis text labels in multi line

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:

present chart

The x-axis labels are split into 2 lines here. Date and month in 2 different lines.

Expected x-axis:

expected

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);
like image 228
Roydon D' Souza Avatar asked Jul 07 '15 18:07

Roydon D' Souza


1 Answers

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.

like image 161
Mark Avatar answered Oct 16 '22 10:10

Mark