HTML
导入代码模板:
练习//坐标轴
var height = 500,
width = 500,
margin = 25,
xScale,
yScale,
xAixs,
yAixs;
var xAxisWidth = width - 2 * margin;
var yAxisWidth = height - 2 * margin;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
function renderxAxis() {
xScale = d3.scale.linear()
.domain([0, 100])
.range([0, xAxisWidth]);
xAixs = d3.svg.axis()
.scale(xScale)
.orient("bottom");
svg.append("g")
.attr("class", "x_axis")
.attr("transform", function() {
return "translate(" + margin + "," + (height - margin) + ")";
})
.call(xAixs);
}
function renderyAxis() {
yScale = d3.scale.linear()
.domain([100, 0])
.range([0, yAxisWidth]);
yAixs = d3.svg.axis()
.scale(yScale)
.orient("left");
svg.append("g")
.attr("class", "y_axis")
.attr("transform", function() {
return "translate(" + margin + "," + margin + ")";
})
.call(yAixs);
}
function renderXGridlines() {
var lines = d3.selectAll("g.x_axis g.tick")
.select("line.grid-line")
.remove();
lines = d3.selectAll("g.x_axis g.tick")
.append("line")
.classed("grid-line", true);
lines.attr("x1", 0)
.attr("y1", 0)
.attr("x2", 0)
.attr("y2", -yAxisWidth);
}
function renderYGridlines() {
var lines = d3.selectAll("g.y_axis g.tick")
.select("line.grid-line")
.remove();
lines = d3.selectAll("g.y_axis g.tick")
.append("line")
.classed("grid-line", true);
lines.attr("x1", 0)
.attr("y1", 0)
.attr("x2", xAxisWidth)
.attr("y2", 0);
}
function rescale() {
var Xmax = Math.round(Math.random() * 100);
xAixs.scale()
.domain([0, Xmax]);
svg.selectAll("g.x_axis")
.transition()
.call(xAixs);
renderXGridlines();
var Ymax = Math.round(Math.random() * 80);
yAixs.scale().domain([Ymax, 0]);
svg.selectAll("g.y_axis")
.transition()
.call(yAixs);
renderYGridlines();
}
renderxAxis();
renderyAxis();
renderXGridlines();
renderYGridlines();
Rescale