[英]Drag & zoom D3 V4 charts with Angular 2
I am working with d3 4.2.2 to create charts with Angular2. 我正在与d3 4.2.2一起使用Angular2创建图表。 I created a multi series line chart and now I am trying to add more features.
我创建了多系列折线图,现在尝试添加更多功能。 My data source has data for 90 days and the chart displays all the data but it doesn't looks good.
我的数据源具有90天的数据,并且该图表显示了所有数据,但是看起来不太好。 So I trued to add zoom and pan features to the chart.
因此,我确实希望向图表添加缩放和平移功能。 But outcome is not what I really expected.
但是结果并不是我真正期望的。 X-axis label are overlapping.
X轴标签重叠。 Axis names are displaying half.
轴名称显示一半。 Here is what I tried.
这是我尝试过的。
Data Source 数据源
var data = [{
"date": "2016-10-01",
"sales": 110,
"searches": 67
},
....
{
"date": "2016-12-31",
"sales": 110,
"searches": 45
}];
To add zoom & pan 添加缩放和平移
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 + ")");
Adding ticks 添加刻度
// 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));
At the end My chart looks like below. 最后,我的图表如下所示。
Now the chart is able to zoom & drag as the whole chart. 现在,该图表可以缩放和拖动为整个图表。 Is there a way to limit number of ticks of x-axis to display then user will be able to drag and see the rest of the chart?
有没有一种方法可以限制要显示的x轴刻度的数量,然后用户将能够拖动并查看图表的其余部分?
I would be much obliged if anyone could be so kind enough to help me to make my chart good looking 如果有人能够如此友好地帮助我使我的图表看起来更好,我将非常有责任。
Thank you 谢谢
You need to recalculate the x and y axis with the zoom transform on zoom callback function. 您需要使用缩放回调函数上的缩放变换来重新计算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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.