簡體   English   中英

改變 D3 條形圖中特定條形之間的間隙

[英]Varying the gaps between specific bars in a D3 bar chart

我有一個條形圖,我想讓圖表中的第 6 個和條形與圖表中的第 12 個和第 13 個條形之間的差距更加明顯。 現在我正在使用.rangeRoundBands ,它會產生均勻的填充,而且似乎沒有辦法為特定的矩形覆蓋它(我嘗試將填充和邊距附加到那個特定的矩形,但沒有成功)。

這是圖表的jsfiddle

我自己生成條帶和條形的代碼:

    var yScale = d3.scale.ordinal()
                    .domain(d3.range(dataset.length))
                    .rangeRoundBands([padding, h- padding], 0.05);

    svg.selectAll("rect.bars")
                .data(dataset)
                .enter()
                .append("rect")
                .attr("class", "bars")
                .attr("x", 0 + padding)
                .attr("y", function(d, i){
                    return yScale(i);
                })
                .attr("width", function(d) {
                    return xScale(d.values[0]);
                })
                .attr("height", yScale.rangeBand())

您可以提供根據數據和索引計算高度的功能。 也就是說,您可以使用類似

.attr("height", function(d,i) {
            if(i == 5) {
                return 5;
            }
            return yScale.rangeBand();
        })

將第6個小節設為5像素高。 您當然可以將此值基於yScale.rangeBand() ,即減去某個數字以使間隙變寬。

這是 D3 v6 的 function,它采用波段比例並返回帶間隙的比例。

// Create a new scale from a band scale, with gaps between groups of items
//
// Parameters:
//       scale:            a band scale
//       where:            how many items should be before each gap?
//       gapSize:          gap size as a fraction of scale.size()
function scaleWithGaps(scale, where, gapSize) {
  scale = scale.copy();
  var offsets = {};
  var i = 0;
  var offset = -(scale.step() * gapSize * where.length) / 2;
  scale.domain().forEach((d, j) => {
    if (j == where[i]) {
      offset += scale.step() * gapSize;
      ++i;
    }
    offsets[d] = offset;
  });
  var newScale = value => scale(value) + offsets[value];
  // Give the new scale the methods of the original scale
  for (var key in scale) {
    newScale[key] = scale[key];
  }
  newScale.copy = function() {
    return scaleWithGaps(scale, where, gapSize);
  };
  return newScale;
}

要使用它,首先要創建一個帶刻度...

let y_ = d3
  .scaleBand()
  .domain(data.map(d => d.name))
  .range([margin.left, width - margin.right])
  .paddingInner(0.1)
  .paddingOuter(0.5)

...然后在其上調用scaleWithGaps()

y = scaleWithGaps(y_, [1, 5], .5)

您可以使用此比例以正常方式創建條形圖。

是一個關於 Observable 的例子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM