我正在d3.js中构建一个区域图.
对于我的y轴,我想使用从图表中表示的数据的最小值到最大值的线性比例.
运用
y = d3.scale.linear().range([height, 0]),
yAxis = d3.svg.axis().scale(y).orient("left")
Run Code Online (Sandbox Code Playgroud)
d3仅显示10000的倍数的刻度.
我还想看到开始和结束值的刻度.这可能吗?怎么样?
Ame*_*aBR 37
这种nice()方法通常更可取,但如果您确实希望在数据的最大值和最小值处有明确的刻度标签,则可以强制轴包含它们,以及由刻度创建的任何默认刻度值:
axis.tickValues( scale.ticks( 5 ).concat( scale.domain() ) );
Run Code Online (Sandbox Code Playgroud)
scale.ticks(count)从比例的域返回大约那么多刻度值的数组,四舍五入到很好的偶数. scale.domain()返回[min,max]根据数据设置的域数组. array.concat(array)将一个数组连接到另一个数组的末尾,并axis.tickValues(array)告诉轴专门绘制这些值的刻度.
实例:https://jsfiddle.net/zUj3E/671/
(function () {
//Set up SVG and axis//
var svg = d3.select("svg");
var width = window.getComputedStyle(svg[0][0])["width"];
width = parseFloat(width);
var height = window.getComputedStyle(svg[0][0])["height"];
height = parseFloat(height);
var margin = 50;
var scale = d3.scale.linear()
.domain([0.05, 0.95])
.range([0, height - 2*margin]);
var formatPercent = d3.format(".0%");
var axis = d3.svg.axis()
.scale(scale)
.orient("right")
.tickFormat(formatPercent);
axis.tickValues( scale.ticks( 5 ).concat( scale.domain() ) );
//set the axis tick values explicitly, as the array of ticks
//generated by the scale PLUS the max and min values from the scale domain
//concatenated into a single array
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + [margin, margin]+")")
.call(axis);
})();Run Code Online (Sandbox Code Playgroud)
g.axis line, g.axis path {
fill:none;
stroke:royalblue;
shape-rendering:crispEdges;
}
g.axis text{
fill:royalblue;
font-family:sans-serif;
}
g.axis path {
stroke-width:2;
stroke:seagreen;
}
svg {
display: block;
width: 100vw;
height: 100vh;
}
body {
margin: 0;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg></svg>Run Code Online (Sandbox Code Playgroud)
Lar*_*off 18
一种方法是将比例域扩展为"好",即包括将在轴上显示的"圆"值.您可以.nice()在设置域后通过调用来执行此操作:
y = d3.scale.linear().range([height, 0]).domain(...).nice();
Run Code Online (Sandbox Code Playgroud)
另一种方法是明确指定刻度,这通常会更加痛苦.