【问题标题】:D3 annotations in wrong place along x axisD3 注释在 x 轴上的错误位置
【发布时间】:2020-04-12 09:04:35
【问题描述】:

我正在使用出色的插件 d3 注释,但我很难弄清楚为什么我的注释沿 x 轴放置在错误的区域。我正在使用时间刻度来确定我的轴的范围,并且我对注释使用相同的范围,但不知何故它不起作用。我遵循了文档 (https://bl.ocks.org/susielu/23dc3082669ee026c552b85081d90976) 中的相同流程。

X 尺度:

 const xScale = d3
.scaleTime()
.domain(d3.extent(data, xAccessor))
.range([0, dimensions.boundedWidth])
.nice();

注释:

    const annotations = [
    {
      note: {
        label: 'National emergency is declared',
        align: 'center',
        wrap: 100,
      },
      subject: {
        y1: dimensions.margin.top + 40,
        y2: dimensions.height - dimensions.margin.bottom,
      },
      y: dimensions.height - dimensions.boundedHeight,
      data: { x: dateParser('2020-3-13') }, // position the x based on an x scale
    },
    {
      note: {
        label: `Florida's stay at home rule is declared`,
        align: 'right',
        wrap: 120,
      },
      subject: {
        y1: dimensions.margin.top + 40,
        y2: dimensions.height - dimensions.margin.bottom,
      },
      y: dimensions.height - (dimensions.boundedHeight - 10),
      data: { x: dateParser('2020-4-1') },
    },
  ];

  const type = d3.annotationCustomType(d3.annotationXYThreshold, {
    note: {
      lineType: 'none',
      orientation: 'top',
    },
  });

  // 12 - render the annotations
  const makeAnnotations = d3
    .annotation()
    .type(type)
    .accessors({
      x(d) {
        return xScale(d.x);
      },
      y(d) {
        return yScale(d.y);
      },
    })
    .annotations(annotations)
    .textWrap(30);

  wrapper
    .append('g')
    .attr('class', 'annotation-group')
    .call(makeAnnotations);

【问题讨论】:

    标签: javascript d3.js data-visualization


    【解决方案1】:

    如果您查看您的数据可视化,两个注释都以相同的量关闭(向左)。您发布的代码不足以查看发生了什么,但是由于您将其作为比例范围...

    .range([0, dimensions.boundedWidth])
    

    ...我敢打赌,您将轴和其他元素附加到一个组中,该组由您设置的左边距量翻译,同时将注释附加到另一个组(在wrapper 内,无论如何),哪个翻译量不同。

    话虽如此,解决方案是:

    1. 将注释附加到您将轴放入的同一组(已翻译);
    2. 用边距设置刻度范围...

      .range([leftMargin, dimensions.boundedWidth - leftMargin - rightMargin])
      

      ...然后将所有内容附加到非翻译组。

    【讨论】:

    • 谢谢杰拉尔多!你是对的 !我在不同的地方附加了注释!我在这个项目上工作了这么多小时,以至于我错过了那个简单的步骤!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多