【问题标题】:Drag & zoom D3 V4 charts with Angular 2使用 Angular 2 拖动和缩放 D3 V4 图表
【发布时间】:2016-09-05 10:34:29
【问题描述】:

我正在使用 d3 4.2.2 使用 Angular2 创建图表。我创建了一个多系列折线图,现在我正在尝试添加更多功能。我的数据源有 90 天的数据,图表显示了所有数据,但看起来不太好。所以我确实在图表中添加了缩放和平移功能。但结果并不是我真正期望的。 X 轴标签重叠。轴名称显示一半。这是我尝试过的。

数据源

 var data = [{
  "date": "2016-10-01",
  "sales": 110,
  "searches": 67
}, 
....
{
  "date": "2016-12-31",
  "sales": 110,
  "searches": 45
}];

添加缩放和平移

var svg = d3.select(this.htmlElement).append("svg")
  .attr("class", "bar-graph")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .call(d3.zoom().scaleExtent([1, 10]).on("zoom", function () {
        svg.attr("transform", d3.event.transform)
    }))
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

添加刻度

// Add the X Axis
svg.append("g")
  .style("font", "14px open-sans")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x).ticks(d3.timeDay.every(1)).tickFormat(d3.timeFormat("%d/%m")));


// Add the Y Axis
svg.append("g")
  .style("font", "14px open-sans")
  //.tickSize(-height)
  .call(d3.axisLeft(y).ticks(5));

最后我的图表如下所示。

现在图表可以作为整个图表进行缩放和拖动。有没有办法限制要显示的 x 轴刻度数,然后用户将能够拖动并查看图表的其余部分?

如果有人能如此好心地帮助我使我的图表看起来更漂亮,我将非常感激

谢谢

【问题讨论】:

  • 您是否尝试过使用此ticks(d3.timeDay.every(10)) 来显示相隔 10 天的 x 轴。这应该会提高可读性
  • 是的,然后它显示 x 轴,相隔 10 天。但我想显示所有数据点(每天)。它应该首先显示 10 天,然后用户可以在图表上拖动并查看剩余的天数。

标签: javascript d3.js angular angular-cli


【解决方案1】:

您需要在缩放回调函数上使用缩放变换重新计算 x 和 y 轴。

function zoomed() {
    var t = d3.event.transform,
        xt = t.rescaleX(x);
        yt = t.rescaleY(y);
    svg.attr("transform", t)
    var line = d3.line()
        .x(function(d) {
            return xt(d.date);
        })
        .y(function(d) {
            return yt(d.scales);
        });
    g.select("path").attr("d", line);
    svg.select(".axis--x").call(xAxis.scale(xt));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-03
    • 2017-10-15
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多