D3 条形图水平平移

D3 Bar Chart Horizontal Pan

我有一个 D3 条形图,我希望它水平平移,有点像这里的这个例子:https://jsfiddle.net/Cayman/vpn8mz4g/1/ 但左侧没有溢出问题。

这是我的 csv 数据:

month,revenue,profit
January,123432,80342
February,19342,10342
March,17443,15423
April,26342,18432
May,34213,29434
June,50321,45343
July,54273,80002
August,60000,30344
September,44432,32444
October,21332,9974
November,79105,48711
December,45246,21785

这是我的完整代码:https://plnkr.co/edit/ZmNcEB0QFVg4r8PA?open=lib%2Fscript.js&preview

对于这方面的任何帮助,我将不胜感激。提前致谢!

你有两个问题。

您正在设置 clip-path 但未使用它。为您的条形图附加一个组并在此处设置它的 clip-path 属性:

var rect = layer.append('g')
        .attr('clip-path', 'url(#clip)') //here
        .selectAll("rect")

您的缩放选择调用将包括 clip-path 矩形,除非您也使用栏 class:

svg.selectAll(".chart rect.bar")
    .attr("transform", "translate(" + d3.event.translate[0] + ",0)scale(" + d3.event.scale + ", 1)");

您有两个问题:

  • 该示例使用连续时间尺度,而您的代码使用的是具有离散域的序数波段尺度Zoom Transformations(在您的 D3 版本中)不提供自动转换比例本身的功能(D3 如何知道 'scale' 任意离散值?)
  • Zoom Transformations 您代码的 D3 版本是从您提供的示例中使用的版本演变而来的。

您可以将所有 rect 条形元素放入一个 svg 组 ("zoomGroup") 并对该组应用缩放转换。 在第二步中,您可以 'zoom' x-axis 通过根据缩放转换提供的 x 偏移和缩放因子更新其范围。

// the zooming & panning
const zoom = d3.zoom()
  // define the zoom event handler with the zoom transformation as the parameter
  .on("zoom", ({transform}) => {
    // the scaling/zooming factor: scaleFactor = 2 means double the size
    const scaleFactor = transform.k;
    // the x offset of the bars after zooming and panning (this depends on the x position of the cursor when zooming)
    const xOffset = transform.x;
    // horizontally move and then scale the bars
    zoomGroup.attr('transform', `translate(${xOffset} 0) scale(${scaleFactor} 1)`);
    
    // also update the viewport range of the x axis
    x.range([xOffset, WIDTH * scaleFactor + xOffset]);
    xAxisGroup.call(xAxisCall)
  });

最后,您可以应用剪辑路径来确保 rect 和 x-axis 元素都不会绘制在视口之外。请记住,您将需要两个 svg 组 (g) 元素的级联:

  • 一个父组(“barsGroup”)将剪辑路径应用到
  • 一个子组(“zoomGroup”)应用缩放变换

这是因为对组的任何变换也会变换其剪辑路径。

// add clip paths to the svg to hide overflow when zooming/panning
const defs = svg.append('defs');
const barsClipPath = defs.append('clipPath')
    .attr('id', 'bars-clip-path')
  .append('rect')
  .attr('x',0)
  .attr('y', 0)
  .attr('width', WIDTH)
  .attr('height', 400);
  
// apply clip path to group of bars
barsGroup.attr('clip-path', 'url(#bars-clip-path)');
// apply clip path to the axis group
xAxisGroup.attr('clip-path', 'url(#bars-clip-path)');

总而言之:

const data = [
  ['January', 123432, 80342],
  ['February', 19342, 10342],
  ['March', 17443, 15423],
  ['April', 26342, 18432],
  ['May', 34213, 29434],
  ['June', 50321, 45343],
  ['July', 54273, 80002],
  ['August', 60000, 30344],
  ['September', 44432, 32444],
  ['October', 21332, 9974],
  ['November', 79105, 48711],
  ['December', 45246, 21785]
].map((item, i) => {
  return {
    index: i,
    month: item[0],
    revenue: item[1],
    profit: item[2]
  }
});


const MARGIN = {
  LEFT: 100,
  RIGHT: 10,
  TOP: 10,
  BOTTOM: 130
}
// total width incl margin
const VIEWPORT_WIDTH = 1000;
// total height incl margin
const VIEWPORT_HEIGHT = 400;

const WIDTH = VIEWPORT_WIDTH - MARGIN.LEFT - MARGIN.RIGHT
const HEIGHT = VIEWPORT_HEIGHT - MARGIN.TOP - MARGIN.BOTTOM

let flag = true

const svg = d3.select(".chart-container").append("svg")
  .attr("width", WIDTH + MARGIN.LEFT + MARGIN.RIGHT)
  .attr("height", HEIGHT + MARGIN.TOP + MARGIN.BOTTOM)

const g = svg.append("g")
  .attr("transform", `translate(${MARGIN.LEFT}, ${MARGIN.TOP})`);


const x = d3.scaleBand()
  .range([0, WIDTH])
  .paddingInner(0.3)
  .paddingOuter(0.2)
  .domain(data.map(d => d.month))


const y = d3.scaleLinear()
  .range([HEIGHT, 0])
  .domain([0, d3.max(data, d => d.profit)])

const xAxisGroup = g.append("g")
  .attr("class", "x axis")
  .attr("transform", `translate(0, ${HEIGHT})`)

const yAxisGroup = g.append("g")
  .attr("class", "y axis")

const xAxisCall = d3.axisBottom(x)
xAxisGroup.call(xAxisCall)
  .selectAll("text")
  .attr("y", "10")
  .attr("x", "-5")
  .attr("text-anchor", "end")
  .attr("transform", "rotate(-40)")

const yAxisCall = d3.axisLeft(y)
  .ticks(3)
  .tickFormat(d => "$" + d)

yAxisGroup.call(yAxisCall);

// contains all the bars - we will apply a clip path to this
const barsGroup = g.append('g')
  .attr('class', 'bars');
// the group which gets transformed by the zooming
const zoomGroup = barsGroup.append('g')
  .attr('class', 'zoom');


const monthGroups = zoomGroup.selectAll('g.month')
  .data(data)
  .enter()
  .append('g')
  .attr('class', 'month');

const rectsProfit = monthGroups
  .append("rect")
  .attr("class", "profit")
  .attr("y", d => y(d.profit))
  .attr("x", (d) => x(d.month))
  .attr("width", 0.5 * x.bandwidth())
  .attr("height", d => HEIGHT - y(d.profit))
  .attr("fill", "grey");

const rectsRevenue = monthGroups
  .append("rect")
  .attr("class", "revenue")
  .attr("y", d => y(d.revenue))
  .attr("x", (d) => x(d.month) + 0.5 * x.bandwidth())
  .attr("width", 0.5 * x.bandwidth())
  .attr("height", d => HEIGHT - y(d.revenue))
  .attr("fill", "red");

// add clip paths to the svg to hide overflow when zooming/panning
const defs = svg.append('defs');
const barsClipPath = defs.append('clipPath')
  .attr('id', 'bars-clip-path')
  .append('rect')
  .attr('x', 0)
  .attr('y', 0)
  .attr('width', WIDTH)
  .attr('height', 400);

// apply clip path to group of bars
barsGroup.attr('clip-path', 'url(#bars-clip-path)');
// apply clip path to the axis group
xAxisGroup.attr('clip-path', 'url(#bars-clip-path)');

// the zooming & panning
const zoom = d3.zoom()
  // here you can limit the min/max zoom. In this case it cannot shrink by more than half the size
  .scaleExtent([0.5, Infinity])
  .on("zoom", ({
    transform
  }) => {
    // the scaling/zooming factor: scaleFactor = 2 means double the size
    const scaleFactor = transform.k;
    // the x offset of the bars after zooming and panning (this depends on the x position of the cursor when zooming)
    const xOffset = transform.x;
    // horizontally move and then scale the bars
    zoomGroup.attr('transform', `translate(${xOffset} 0) scale(${scaleFactor} 1)`);

    // also update the viewport range of the x axis
    x.range([xOffset, WIDTH * scaleFactor + xOffset]);
    xAxisGroup.call(xAxisCall)
  });

// listen for zoom events on the entire drawing
svg.call(zoom);
.chart-container {
  width: 100%;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Multi Series Span Chart (Vertical)</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
  <div class="chart-container">
  </div>
  <script src="https://d3js.org/d3.v7.min.js"></script>
  <script type="text/javascript" src="main.js"></script>
</body>

</html>

替代实施

此解决方案的一个缺点是 x-axis(x 比例)只是根据缩放比例进行拉伸。坐标轴刻度(“一月”-“十二月”)的数量和粒度不变。

您可以尝试将 X 域的离散月份值转换为日期并创建连续的时间尺度。 在这种情况下,您可以使用 transform.rescaleX(x) (docs) 来操纵 x 刻度的域,轴刻度将根据缩放比例发生变化。 这发生在您提供的原始示例中。