3

I have a chart with dates on the x-axis. Now I would like to add the time aswell and place it on the row below the date for each tick because the text get rather wide for each tick with both date and time.

By looking to the question suggestion below I tried this instead:

var xMainScale = d3.scale.linear()
   .domain([0,100])
   .range([20, 600]);

//--- date format
var formatAsDate = function(d) {var md = new Date(d*1000);
   md_utc=new Date(md.getUTCFullYear(), md.getUTCMonth(),
   md.g etUTCDate(),  md.getUTCHours(), md.getUTCMinutes(), md.getUTCSeconds());
   return md_utc.format("Y-m-d H:i:s");};

//--- label on several rows
var insertLinebreaks = function (d) {
var el = d3.select(this);
var words = d.split(' ');
el.text('');

for (var i = 0; i < words.length; i++) {
  var tspan = el.append('tspan').text(words[i]);
  if (i > 0)
    tspan.attr('x', 0).attr('dy', '15');
 }
};

//===== axis
var xMainAxis = d3.svg.axis()
  .scale(xMainScale)
  .orient("bottom")
  .ticks(5)
  .tickFormat(formatAsDate);

//====== create SVG element
var chart = d3.select("body")
  .append("svg:svg")
  .attr("width", w)
  .attr("height", h)
  .attr("id","chart")
  .attr("class","chart");

//==== main chart (there are more but I left them out here)
var main = chart.append('g')
  .attr('transform', 'translate(' + 25 + ',' + 25 + ')')
  .attr('width', w)
  .attr('height', main_h)
  .attr('class', 'main')
  .attr('id', 'mainchart');

//===== create x axis
main.append("g")
  .attr("id","main_x")
  .attr("class", "x_axis")
  .attr("transform", "translate("+0+"," + (700 - 25)  + ")")
  .call(xMainAxis);

In a function a bit down:

//----- update the axis
main.select('#main_x').call(xMainAxis);
main.selectAll('#main_x g text').each(insertLinebreaks);

I have cut and past what I think is the important parts as my code is rather large. I think I'm passing the wrong objects to the insertLinebreaks function, but what should I pass instead?

/Lars

Lars Ljungberg
  • 313
  • 1
  • 6
  • 19

1 Answers1

4

Thanks to @Lars Kotthoff who helped me to find the solution.

By changing the function insertLinebreakes to:

var insertLinebreaks = function (d) {
  var el = d3.select(this);
  var words=d3.select(this).text().split(' ');

  el.text('');

  for (var i = 0; i < words.length; i++) {
var tspan = el.append('tspan').text(words[i]);
if (i > 0)
      tspan.attr('x', 0).attr('dy', '15');
  }
 };

It works.

Lars Ljungberg
  • 313
  • 1
  • 6
  • 19
  • for some reason for me when i append text back to the element it append the same text back so none of the tspans get appended just one text element with the old date not three separate data plus `el.text('')` does nothing. – Box and Cox May 06 '19 at 23:24