Search code examples
javascriptd3.jstooltipc3.js

c3.js - Tooltips on xgrid lines


is it possible to have tooltips when hovering over xgrid lines when using c3.js?

var chart1 = c3.generate({
    bindto: '#chart1',
    padding: {
      right:30
    },
    data: {
          x: 'x',
          xFormat: '%Y-%m-%d %H:%M',
          columns:
          [
              ['x', '2013-01-01 00:00', '2013-01-01 01:00','2013-01-01 03:00','2013-01-01 04:00', '2013-01-01 05:00', '2013-01-01 06:00', '2013-01-01 07:00', '2013-01-01 08:00', '2013-01-01 09:00', '2013-01-01 10:00', '2013-01-01 11:00','2013-01-01 12:00','2013-01-01 13:00', '2013-01-01 14:00', '2013-01-01 15:00', '2013-01-01 16:00', '2013-01-01 17:00', '2013-01-01 18:00', '2013-01-01 19:00', '2013-01-01 20:00', '2013-01-01 21:00', '2013-01-01 22:00', '2013-01-01 23:00'],
              ['RX', 20, 10, 9, 20, 30, 20, 20, 20, 32, 20, 10, 9, 20, 30, 20, 20, 20, 32, 23, 12, 5, 14, 15],
          ],
          type: 'spline',
          colors: {
            RX:'#2d74d0',
          },
        },
        tooltip: {
          order: null,
        },
        point: {
          show: false
        },
        axis: {
            x: {
                type: 'timeseries',
                tick: {
                  multiline: false
                }
            },
            y: {
              tick: {
                format: function (y) { return y + 'GB'}
              }
            }
        }
    }
).xgrids.add([
  {value: '2013-01-01 01:00', text: '01:00, Network 1'},
  {value: '2013-01-01 02:28', text: '02:28, Network 2'}
]);

I posted an example on jsfiddle https://jsfiddle.net/tekp7vvc/


Solution

  • You can poke it into using a basic 'title' based tooltip with the following addition to your c3 setup:

    onrendered: function () {
      var xg = d3.selectAll(".c3-xgrid-lines text");
      xg.each (function (d,i) {
            var title = d3.select(this).select("title");
          if (title.empty()) {
            title = xg.append("title");
          }
          title.text (function (d) {
            return "Gridline: "+d.value+", "+d.text;
          })
      })
    },
    

    https://jsfiddle.net/tekp7vvc/1/

    It's set to work when hovering over the gridline text as otherwise it would be competing with the functionality for showing the data in a tooltip if a gridline was at the same position as a datapoint (which the 1.00am datapoint is)

    It's also set up to run in onrendered rather than oninit, because at the time oninit is called your gridlines haven't been added yet.