如何使用对数(Symlog)刻度为 yAxis 设置刻度?

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

这是我图表上使用 d3.v5 的 yAxis 代码:

    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);

这是我的对数图表 link:https://covid19wiki.info/country/Canada

您看到的问题是 Symlog 尺度的持续问题:https://github.com/d3/d3-scale/issues/162

你可以在这个简单的演示中看到它:

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>

这些是可能的解决方案:

  • 更改D3源代码,如GitHublink;
  • 中所述
  • 为自己设置一个包含足够刻度值的数组,然后将其传递给 axis.tickValues;
  • 使用域从 1 而不是零开始的对数刻度。

最后一个选项似乎是一个 hacky,但它是迄今为止最简单的,并且鉴于您的最高值如此之大,从视觉上看,它对数据可视化没有任何影响。这是:

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>