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 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...