Home > Mobile >  D3 Bar Chart Horizontal Pan
D3 Bar Chart Horizontal Pan

Time:01-25

I have a D3 Bar Chart and I want it to Pan Horizontally, kinda like this example here: https://jsfiddle.net/Cayman/vpn8mz4g/1/ But without its overflow issue on the left side.

Here is my csv data:

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

And here is my complete code: https://plnkr.co/edit/ZmNcEB0QFVg4r8PA?open=lib/script.js&preview

I would appreciate any help on this. Thanks in advance!

CodePudding user response:

You have a two issues:

  • The example uses a continuous time scale, whereas your code is using a ordinal band scale with a discrete domain. Zoom Transformations (in your D3 version) do no provide a function to automatically transform the scale itself (How would D3 know to 'scale' arbitrary discrete values?)
  • Zoom Transformations in the D3 version of your code have evolved from the version used in the example you provided.

You can put all the bar rect elements into a svg group ("zoomGroup") and apply zoom transformations to that group. In a second step you can 'zoom' the x-axis by updating its range based on the x offset and scaling factor provided by the zoom transformation.

// 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)
  });

At last you can apply a clip path to ensure that neither the bar rect elements not the x-axis is drawn outside the view port. Keep in mind that you will need a cascade of two svg group (g) elements:

  • One parent group ("barsGroup") to apply the clip path to
  • One child group ("zoomGroup") to apply the zoom transformations

This is because any transformation to a group will also transform its clip path.

// 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)');

To put it all together:

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 >
  </div>
  <script src="https://d3js.org/d3.v7.min.js"></script>
  <script type="text/javascript" src="main.js"></script>
</body>

</html>

Alternative Implementation

One downside of this solution is that the x-axis (x scale) is simply stretched according to the zoom. The number and granularity of the axis ticks ("January" - "December") does not change.

You could try to cast your discrete month values of the X domain to dates and create a continuous time scale. In that case you could use transform.rescaleX(x) (docs) to manipulate the domain of the x scale and the axis ticks will be change based on the zoom scale. This happens in the original example you provided.

CodePudding user response:

You've got two problems.

You are setting a clip-path but not using it. Append a group for your bars and set it's clip-path attribute here:

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

Your zoom selection call is going to include the clip-path rectangle unless you use the bar class as well:

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