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 can I use d3.js to create a zoom scale?
- How do I use d3.js to zoom to a selected area?
- How do I set up the x axis in d3.js?
- How can I use d3.js with Next.js?
- How do I use d3.js to enable zooming and panning in my web application?
- How can I use d3.js xscale to create a chart?
- How do I install and use D3.js with Yarn?
- How can I use d3.js to parse XML data?
- How can I use d3.js to create interactive data visualizations?
- How can I create a time scale on the x-axis using d3.js?
See more codes...