keno
keno

Reputation: 93

d3.js change position of tick label on pannable graph

I am working in d3.js and have two pannable (but not zoomable) time axes. One axis has labels for days, one has labels for months. I use the same scale for both axes.

Currently, it looks like this: (pipe- and minus-symbol only for better visibility)

|November
1 2 3 4 5 6 7 8 9 10 11 12 13 ... 30

I want to move the name of the month to the middle of the interval, so that it looks like this:

|-------------November
1 2 3 4 5 6 7 8 9 10 11 12 13 ... 30

I already tried several ways to fix the issue, but without success. The core problem is that when panning, the text of the tick will disappear as soon as the tick itself disappears.

  1. If I use post selection to move the text of the tick to the right position, the text will disappear too early when panning the axis to the left.

    Initial (ok):

    |-------------November
    1 2 3 4 5 6 7 8 9 10 11 12 13 ... 30
    

    After panning to the left (wrong):

    (gone)             
    2 3 4 5 6 7 8 9 10 11 12 13 ... 30
    
  2. I tried to change the interval to a date near "the middle". Instead of placing the Label with

    .ticks(d3.time.months, 1);
    

    I tried to set it using the following:

    .ticks(d3.time.days, 15);
    

    But this had not the desired effect. It generates the following:

    |November-----November------November
    1 2 3 4 5 6 7 8 9 10 11 12 13 ... 30
    
  3. The following did not help me:

    .style("text-anchor", "end/begin")
    
  4. I found a way (as described in this example: http://bl.ocks.org/mbostock/6186172) to add a offset to the axis, so ticks that are too long will still be displayed. I was not able to get this working in a pannable graph.

    var x = d3.time.scale()
        .domain([t0, t3])
        .range([t0, t3].map(d3.time.scale()
              .domain([t1, t2])
              .range([0, width])));
    

Is there any better working solution?

Upvotes: 2

Views: 1823

Answers (1)

keno
keno

Reputation: 93

Writing a custom ticks() function worked for me. Using this, I am able to set the tick (and its label) to any given position.

I created a simple gist to show you my solution: http://bl.ocks.org/kevinnoll/77430421843b940869ed

Upvotes: 1

Related Questions