首页 > 解决方案 > 在 d3 图表上拖动时仅更新最后一个 Y 轴

问题描述

我的图表有多个具有不同域的 Y 轴。

当我在图表上拖动时,只有最后一个 y 轴正在更新。

在此处输入图像描述

我添加了每个 y 轴,如下所示;

addYAxis(data, tag) { // tag is for index for each y-axis e.g: 0, 1, 2
  const yScale = d3.scale.linear()
    .domain([0, this.innerHeight])
    .range([this.innerHeight, 0]);
  const yAxis = d3.svg.axis()
    .scale(yScale)
    .orient(tag ? 'right' : 'left')
    .tickSize(tag ? this.innerWidth + 50 * (tag - 1) : -this.innerWidth);
  const yAxisElement = this.g.append('g')
    .attr('class', 'y axis')
    .call(yAxis);
  this.yAxisList.push({yScale, yAxis, yAxisElement});
}

这是每个轴的缩放列表。

this.zoom.push(d3.behavior.zoom()
    .x(this.xScale)
    .y(this.yAxisList[tag].yScale)  // when I replace [tag] with [0], then only first axis is being updated.
    .scaleExtent([.5, 10])
    .scale(this.currentZoom)
    .translate(this.currentPan)
    .on('zoom', () => this.zoomed(tag))
    .on('zoomend', () => {
        setTimeout(() => { this.zooming = false; }, 10);
    }));

this.g.call(this.zoom[tag])  // when I replace [tag] with [0], then only first axis is being updated.
    .on('dblclick.zoom', null);

并像下面这样更新它们;

updateYAxis() {
  this.yAxisList.forEach(({yAxisElement, yAxis}) => yAxisElement.call(yAxis));
}

此图表的结构:

在此处输入图像描述

在图表上拖动时如何更新所有 Y 轴?

标签: javascriptd3.js

解决方案


这里,

.on('zoom', () => this.zoomed(tag))

您只更新了当前缩放,但也应该使用当前缩放值更新其他缩放对象。

.on('zoom', () => {
    this.zoom.forEach((zoom, t) => {
        zoom.scale(this.zoom[tag].scale());
        zoom.translate(this.zoom[tag].translate());
        this.zoomed(t);
    });
})

推荐阅读