javascript-d3How do I use D3.js to zoom on the x-axis?
Using D3.js to zoom on the x-axis is a simple process. The following example code block shows how to implement zoom on the x-axis.
// Set up the scale and range for the x-axis
var x = d3.scaleLinear()
.domain([0, 100])
.range([0, width]);
// Set up the zoom behavior
var zoom = d3.zoom()
.scaleExtent([1, 32])
.translateExtent([[0, 0], [width, height]])
.extent([[0, 0], [width, height]])
.on("zoom", zoomed);
// Add the zoom behavior to the x-axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.call(zoom);
// Define the zoomed function
function zoomed() {
x.domain(d3.event.transform.rescaleX(x2).domain());
svg.select(".x.axis").call(xAxis);
}
This code does the following:
- Sets up the scale and range for the x-axis using the
d3.scaleLinear()
method. - Sets up the zoom behavior using the
d3.zoom()
method. - Adds the zoom behavior to the x-axis using the
call()
method. - Defines the
zoomed()
function which rescales the x-axis using thed3.event.transform.rescaleX()
method.
For more information on how to use D3.js to zoom on the x-axis, see the following links:
More of Javascript D3
- How can I use d3.js xscale to create a chart?
- How do I use the viewbox feature in d3.js?
- How can I use d3.js with W3Schools?
- How can I display Unix time using d3.js?
- How do I create a zoomable chart using d3.js?
- How can I use d3.js to create a zoom scale?
- How do I create a zoomable line chart using d3.js?
- How do I use the z-index property with d3.js?
- How do I use the tspan element in D3.js?
See more codes...