Search code examples
javascriptd3.jschartslogarithmyaxis

How to set ticks for yAxis using a logarithmic (Symlog) scale?


Here is the code for yAxis on my chart using d3.v5:

    let x = d3.scaleTime()
        .domain(d3.extent(data, d => d.date))
        .range([margin.left, width - margin.right])
    let y = d3.scaleSymlog()
        .domain([0, d3.max(data, d => d.Confirmed)]).nice()
        .range([height - margin.bottom, margin.top])

    let line = d3.line()
        .defined(d => !isNaN(d.value))
        .x(d => x(d.date))
        .y(d => y(d.value))

    let xAxis = g => g
        .attr("transform", `translate(0,${height - margin.bottom})`)
        .call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0))

    let yAxis = g => g
        .attr("transform", `translate(${margin.left},0)`)
        .call(d3.axisLeft(y))
        .call(g => g.select(".domain").remove())
        .call(g => g.select(".tick:last-of-type text").clone()
            .attr("x", 3)
            .attr("text-anchor", "start")
            .attr("font-weight", "bold")
            .text(data.y))

    let svg = d3.select('#MultiLineLogChart').select("svg")
    svg.attr("viewBox", [0, 0, width, height])
        .attr("fill", "none")
        .attr("stroke-linejoin", "round")
        .attr("stroke-linecap", "round");

    svg.append("g")
        .call(xAxis);

    svg.append("g")
        .call(yAxis);

and here is a link for my logarithmic chart: https://covid19wiki.info/country/Canada


Solution

  • The problem you see is an ongoing issue with Symlog scales: https://github.com/d3/d3-scale/issues/162

    You can see it in this simple demo:

    const svg = d3.select("svg");
    const scale = d3.scaleSymlog()
      .domain([0, 100000])
      .range([140, 10]);
    const axis = d3.axisLeft(scale).ticks(4)(svg.append("g").attr("transform", "translate(50,0)"));
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <svg></svg>

    These are the possible solutions:

    • Change D3 source code, as described in the GitHub link;
    • Set yourself an array of adequate tick values, which you'll pass to axis.tickValues;
    • Use a Log scale with the domain starting at 1 instead of zero.

    The last option seems to be a hacky one, but it is by far the easiest and, given your top value is so big, it will make no difference in the dataviz visually speaking. Here it is:

    const svg = d3.select("svg");
    const scale = d3.scaleLog()
      .domain([1, 100000])
      .range([140, 10]);
    const axis = d3.axisLeft(scale).ticks(4).tickFormat(d => d3.format("")(d))(svg.append("g").attr("transform", "translate(50,0)"));
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <svg></svg>