D3.js 如何在D3折线图中添加轴和线之间的空间?
根据我创建的这个简单图表:D3.js 如何在D3折线图中添加轴和线之间的空间?,d3.js,D3.js,根据我创建的这个简单图表: var data = [["2013-01-24 06:38:02.235191", 52], ["2013-01-23 06:38:02.235310", 54], ["2013-01-22 06:38:02.235330", 45], ["2013-01-21 06:38:02.235346", 53]], maxValue = d3.max(data, function (d) { return d[1]; }), margin = {top:
var data = [["2013-01-24 06:38:02.235191", 52], ["2013-01-23 06:38:02.235310", 54], ["2013-01-22 06:38:02.235330", 45], ["2013-01-21 06:38:02.235346", 53]],
maxValue = d3.max(data, function (d) { return d[1]; }),
margin = {top: 20, right: 20, bottom: 50, left: 50},
width = 500 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom,
svg, x, y, xAxis, yAxis, line;
$.each(data, function(index, val) {
val[0] = new Date(val[0]);
});
x = d3.time.scale()
.range([0, width])
y = d3.scale.linear()
.domain([0, maxValue])
.range([height, 0]);
xAxis = d3.svg.axis()
.scale(x)
.tickSize(4, 2, 0)
.ticks(d3.time.days, 1)
.tickFormat(d3.time.format("%m/%d"))
.orient("bottom");
yAxis = d3.svg.axis()
.scale(y)
// .ticks(5)
// .tickValues([0, maxValue * 0.25, maxValue * 0.5, maxValue * 0.75, maxValue])
.tickSize(4, 2, 0)
.orient("left");
line = d3.svg.line()
.x(function(d) { return x(d[0]); })
.y(function(d) { return y(d[1]); });
svg = d3.select("#chart-holder").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(d3.extent(data, function(d) { return d[0]; }));
y.domain(d3.extent(data, function(d) { return d[1]; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.attr("transform", function(d) {
return "rotate(-60)translate(" + -this.getBBox().height * 1.7 + "," +
-this.getBBox().width/4 + ")";
});
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
svg
.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("fill", "#0b8da0")
.attr("r", 3.5)
.attr("cx", function(d) { return x(d[0]); })
.attr("cy", function(d) { return y(d[1]); });
如何在轴和线之间添加空间,使其不会接触轴
还有一种方法可以强制yAxis刻度始终从0开始,而不管数据集中的最小值是多少
工作示例可在此处找到:您只需更改用于绘制y轴的比例域,然后查找直线
y.domain(d3.extent(data, function(d) { return d[1]; }));
如果希望它比数据集中使用的最小值小一个,则需要更改
y.domain([d3.min(data, function (d) { return d[1]; })-1, maxValue]);
或者如果希望从0开始,无论数据如何
y.domain([0, maxValue]);
您只需更改用于绘制y轴的比例域,然后查找直线
y.domain(d3.extent(data, function(d) { return d[1]; }));
如果希望它比数据集中使用的最小值小一个,则需要更改
y.domain([d3.min(data, function (d) { return d[1]; })-1, maxValue]);
或者,如果希望从0开始,则不考虑数据
y.domain([0, maxValue]);
啊,谢谢,这正是我正在做的,只是我在代码后面重写了自己!谢谢你帮我发现了这个问题。有没有在x轴和直线之间添加空格的解决方案?啊,谢谢,这正是我正在做的,只是我在代码后面重写了自己!谢谢你帮我找到这个。有没有办法在x轴和直线之间增加空间?