javascript-d3How do I update the axis scale in d3.js?
Updating the axis scale in d3.js is a relatively simple process. The following example code will illustrate the process:
// Set up the SVG
var svg = d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 500);
// Set up the x and y scales
var xScale = d3.scaleLinear()
.domain([0, 10])
.range([0, 500]);
var yScale = d3.scaleLinear()
.domain([0, 10])
.range([500, 0]);
// Draw the x and y axis
var xAxis = d3.axisBottom(xScale);
var yAxis = d3.axisLeft(yScale);
svg.append("g")
.attr("transform", "translate(0," + 500 + ")")
.call(xAxis);
svg.append("g")
.call(yAxis);
// Update the x and y scales
xScale.domain([5, 10]);
yScale.domain([5, 10]);
// Update the x and y axis
svg.select(".x-axis")
.transition()
.call(xAxis);
svg.select(".y-axis")
.transition()
.call(yAxis);
This example code will produce a 500x500 SVG with the x and y axis drawn using the initial scales. Then the scales are updated and the axis are updated by selecting the class of the axis and calling the axis function again.
Code explanation
- Set up the SVG
- Set up the x and y scales
- Draw the x and y axis
- Update the x and y scales
- Update the x and y axis
Helpful links
More of Javascript D3
- How do I set up the x axis in 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 d3.js to implement zooming functionality?
- How can I use d3.js with W3Schools?
- How do I use the viewbox feature in d3.js?
- How can I display Unix time using d3.js?
- How do I use the tspan element in D3.js?
- How can I use D3.js to read a CSV file?
- How can I use d3.js with Next.js?
See more codes...