Reputation: 3160
I am working with d3 4.2.2 to create charts with 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. 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. 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?
I would be much obliged if anyone could be so kind enough to help me to make my chart good looking
Thank you
Upvotes: 1
Views: 2099
Reputation: 106
You need to recalculate the x and y axis with the zoom transform on zoom callback function.
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));
}
Upvotes: 2