繁体   English   中英

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

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

你有两个问题。

您正在设置剪辑路径但不使用它。 Append 为您的酒吧组,并在此处设置其剪辑路径属性:

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

除非您也使用条形 class ,否则您的缩放选择调用将包括剪辑路径矩形:

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

你有两个问题:

  • 该示例使用连续时间尺度,而您的代码使用具有离散域的序数带尺度 缩放转换(在您的 D3 版本中)不提供 function 来自动转换比例本身(D3 如何知道“缩放”任意离散值?)
  • 您的代码的 D3 版本中的缩放转换是从您提供的示例中使用的版本演变而来的。

您可以将所有条形rect元素放入 svg 组(“ zoomGroup ”)并将缩放转换应用于该组。 在第二步中,您可以通过根据缩放转换提供的 x 偏移和缩放因子更新其范围来“缩放”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 轴都不会绘制在视口之外。 请记住,您需要级联两个 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 轴(x 比例)只是根据缩放进行拉伸。 轴刻度的数量和粒度(“一月”-“十二月”)不会改变。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM