Search code examples
javascriptd3.jsplotdc.jsaxis-labels

Scale y-tick labels in DC.js chart (D3.js underneath)


I'm trying to find a way to dynamically scale a chart's y-axis so the values are shown in single digits, with a exponential denotation at the top, effectively changing this:
unscaled y axis

To this:

scaled y axis

Note, this works automatically in e.g. Matlab/Matplotlib/etc., but I'm struggling to find a solution with the web plotting frameworks (maybe my search language is wrong)... I know D3.js is not a charting library, but I'd be open to a solution that works with the frontend DC.js or the backend D3.js


Edit based on @Gordon's answer below, I get the following graph using this

chart.yAxis().tickFormat(d3.format('.1e'));

exponential format

Is it somehow possible to move all of the e+6 to the top? Or do I need to write a custom scaling function and insert a separate text box myself?


Solution

  • In dc.js, the axes are straight from d3-axis.

    Access them using chart.xAxis() and chart.yAxis(), and to reduce confusion, do this in a separate statement from the rest of your chart initialization.

    You can use axis.tickFormat to control how the tick text is formatted.

    You can use d3.format to do automatic formatting. It seems like exponent or SI notation might suit what you're doing, although it's not exactly the same as having the exponent in a separate text element like in your screenshot.

    Putting it together, this is pretty close

    chart.yAxis().tickFormat(d3.format('.1e'))
    

    The tick formatting question comes up a lot. I wonder where we could put this information so that people don't have to ask.