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 display Unix time using d3.js?
- How do I use the yscale feature in d3.js?
- How can I use d3.js to make an XMLHttpRequest?
- How do I create a timeline using d3.js?
- How can I use d3.js to create visuals in Power BI?
- How do I create a React tutorial using d3.js?
- How can I use d3.js to create an interactive mouseover effect?
- How do I implement zooming in a d3.js visualization?
- How can I use d3.js and neo4j together to create data visualizations?
- How can I use d3.js to parse XML data?
See more codes...