javascript - 轴为大域添加额外的填充

标签 javascript html d3.js svg data-visualization

在 d3 轴生成中遇到奇怪的情况。使用 d3.axisBottom() 创建底部 x 轴时对于序数域值,在轴中刻度的起始点和结束点添加额外的填充。 d3.scaleBand()的情况域中有更多的值。

我猜刻度生成会随着域项目的阈值数量而缩小。

刻度与平均项目数均匀分布,一旦超过限制,它会随着第一个和最后一个刻度的填充而缩小。

对上述场景的正确解释将更加感激。

var width = 400, height = 200;

var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);
  
var xAxisScale = d3.scaleBand()
 .domain([1,3,5,7,8,10,12,13,14,15,16,17,18,19,20,22,23,24,25,26,27,28,29,30,31,32,33,34,36,37,39,40,41,43,45,46,47,48,49,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,69,70,71,72,73,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,95,98,99,105,106,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,127,128,129,130,131,135,136,141,154])
    .rangeRound([10, width -10])
    .padding(0.1);
    
var xAxisScale1 = d3.scaleBand()
 .domain([1,3,5,7,8,10,12,13,14,15,16,17,18,19,20,22,23,24,25,26,27,28,29,30,31,32])
    .rangeRound([10, width -10])
    .padding(0.1);    
    
var xAxis = d3.axisBottom(xAxisScale);
var xAxis1 = d3.axisBottom(xAxisScale1);

svg.append("g").attr("transform", "translate(0,20)").call(xAxis);
svg.append("g").attr("transform", "translate(0,60)").call(xAxis1);
<script src="https://d3js.org/d3.v4.min.js"></script>

最佳答案

这里的罪魁祸首是rangeRound。这是预期的行为,API 中对此进行了解释。 :

If round is specified, enables or disables rounding accordingly. If rounding is enabled, the start and stop of each band will be integers. Rounding is sometimes useful for avoiding antialiasing artifacts, though also consider the shape-rendering “crispEdges” styles. Note that if the width of the domain is not a multiple of the cardinality of the range, there may be leftover unused space, even without padding! (emphasis mine)

因此,解决方案很简单:使用 range 代替:

var width = 400,
  height = 200;

var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

var xAxisScale = d3.scaleBand()
  .domain(d3.range(200))
  .range([10, width - 10])

var xAxisScale1 = d3.scaleBand()
  .domain(d3.range(20))
  .range([10, width - 10])

var xAxis = d3.axisBottom(xAxisScale);
var xAxis1 = d3.axisBottom(xAxisScale1);

svg.append("g").attr("transform", "translate(0,20)").call(xAxis);
svg.append("g").attr("transform", "translate(0,60)").call(xAxis1);
<script src="https://d3js.org/d3.v4.min.js"></script>

关于javascript - 轴为大域添加额外的填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47669596/

相关文章:

events - 如何在 nvd3.js 图上添加点击事件

javascript - window.print() 不会在 iPAD 中弹出 PDF 打印对话框

javascript - 无法使用 'in' 运算符在中搜索 '_id'

javascript - 我想使用一个函数来运行多个函数来完成所有这些任务!有任何想法吗?

javascript - 滚动到顶部的链接不起作用

jquery - 复选框未选中

jquery - D3可折叠树只能拖动,不能缩放和跳跃和滚动

html - 我的电子邮件中未显示 Google 字体

html - 避免在 IE 中使用动态宽度的 div 内换行

svg - 如何确定鼠标事件附近的 SVG 元素?