【问题标题】:Grid lines in d3 js don't match the axesd3 js中的网格线与轴不匹配
【发布时间】:2021-09-29 04:58:54
【问题描述】:

我正在尝试使用 d3.js 制作一个多折线图。情节看起来很好,而且很好,但有时网格线没有对齐。这是非常随机的,有时有些图形有对齐的网格线,有些则没有。 其中一些是这样的:

我的网格线有这个代码:

        svg
            .append('g')
            .attr('class', 'grid')
            .attr('transform', `translate(0,${height})`)
            .call(
                d3.axisBottom(xScale)
                    .tickSize(-height)
                    .tickFormat(() => ""),
            );
        svg
            .append('g')
            .attr('class', 'grid')
            .call(
                d3.axisLeft(yScale)
                    .tickSize(-width)
                    .tickFormat(() => ""),
            );

我按照这个例子:https://betterprogramming.pub/react-d3-plotting-a-line-chart-with-tooltips-ed41a4c31f4f

任何关于如何完美对齐这些线条的帮助将不胜感激。

【问题讨论】:

  • 它们的网格与轴刻度对齐 - 它看起来与我对齐 - 你是说当刻度靠近轴并导致两条线彼此靠近时?我想在这些情况下,最简单的选择是删除轴线,但这在所有用例中可能并不令人满意。修改刻度以与绘图区域的边缘对齐需要更混乱的刻度,例如:2:59:14.441、修改数据值的范围或删除刻度(导致不规则的网格)。

标签: javascript reactjs typescript d3.js charts


【解决方案1】:

您可以考虑nicey 刻度,以便向下/向上舍入数据集的最小值和最大值,从而使刻度等间距。

在你的教程中这段代码:

const yScale = d3
    .scaleLinear()
    .range([height, 0])
    .domain([0, yMaxValue]);

可以变成:

const yScale = d3
    .scaleLinear()
    .range([height, 0])
    .domain([0, yMaxValue])
    .nice(); // <--------------------------- here

这是在 x 尺度上使用 nice 的基本示例,其中第一个示例为“不好”,第二个示例为“不错”。

// note gaps of 10 between data points
// apart from first and last where gap is different
const data = [3, 4, 14, 24, 34, 44, 47];

// svg
const margin = 20;
const width = 360;
const height = 140;
const svg = d3.select("body")
  .append("svg")
  .attr("width", width + margin + margin)
  .attr("height", height + margin + margin);
  
// scale without 'nice'
const xScale1 = d3.scaleLinear()
  .range([0, width])
  .domain(d3.extent(data));

// scale with nice
const xScale2 = d3.scaleLinear()
  .range([0, width])
  .domain(d3.extent(data))
  .nice();
  
// plot axes with both scales for comparison
// not 'nice'
svg.append("g")
  .attr("transform", `translate(${margin},${margin})`)
  .call(d3.axisBottom(xScale1));

// 'nice'
svg.append("g")
  .attr("transform", `translate(${margin},${margin + 50})`)
  .call(d3.axisBottom(xScale2));  
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多