d3.js - 如何在 D3 折线图中的轴和线之间添加空间?

标签 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: 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 开始,无论数据集中的最小值是多少?

可在此处找到工作示例:http://jsfiddle.net/n7Vmr/

最佳答案

您可以只更改用于绘制 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]);

关于d3.js - 如何在 D3 折线图中的轴和线之间添加空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14501959/

相关文章:

javascript - D3 + Leaflet : d3. geo.path() 重采样

d3.js - D3可视化创建建筑/校园 map

javascript - 在d3.js中显示圆弧末端的文字

javascript - d3 使用 selectAll().data().enter().append() 连续创建节点

javascript - 计算具有特定属性值的对象数组中的项目数 (JavaScript)

javascript - 从 json 文件构造 bar 的工具提示值

javascript - 加载时制作 Angular d3 donut 动画

javascript - 将 D3 代码转换为 Vue3 - 单元格不添加到行而是添加到 HTML

javascript - Firefox 无法正确呈现 SVG,其他浏览器可以

Javascript 工具提示跨浏览器兼容性