javascript-d3How do I create a zoomable chart using d3.js?
Creating a zoomable chart with d3.js requires the following steps:
-
Create an SVG element in the HTML page to draw the chart.
<svg id="chart" width="900" height="500"></svg>
-
Create a margin object to position the chart within the SVG element.
var margin = {top: 20, right: 20, bottom: 30, left: 40};
-
Create a scale object to map the data to the chart area.
var x = d3.scaleLinear().range([0, width]); var y = d3.scaleLinear().range([height, 0]);
-
Create an axis object to draw the axes.
var xAxis = d3.axisBottom(x); var yAxis = d3.axisLeft(y);
-
Create a zoom object to enable zooming.
var zoom = d3.zoom().on("zoom", zoomed);
-
Create a zoom function to update the chart when zooming.
function zoomed() { //update the x and y scale according to the zoom transform x.domain(d3.event.transform.rescaleX(xScale).domain()); y.domain(d3.event.transform.rescaleY(yScale).domain()); //redraw the axes svg.select(".x.axis").call(xAxis); svg.select(".y.axis").call(yAxis); //redraw the chart svg.selectAll(".bar") .attr("x", function(d) { return x(d.x); }) .attr("y", function(d) { return y(d.y); }) .attr("width", x.bandwidth()) .attr("height", function(d) { return height - y(d.y); }); }
-
Finally, attach the zoom object to the SVG element.
svg.call(zoom);
Helpful links
More of Javascript D3
- How can I use d3.js with W3Schools?
- How can I display Unix time using d3.js?
- How do I create a zoomable line chart using d3.js?
- How do I check the license for d3.js?
- How do I use the viewbox feature in d3.js?
- How do I use d3.js to zoom to a selected area?
- How do I use the z-index property with d3.js?
- How do I add a label to the Y axis of a D3.js chart?
- How do I set up the x axis in d3.js?
- What is the purpose of using d3.js?
See more codes...