📈 js 그래픽/react + d3.js

React + D3.js (5) Animation

DarrenKwonDev 2021. 1. 18. 03:33

아래 bar 그래프에 grow하는 듯한 애니메이션을 추가하겠습니다.

 

1. 

 

transform으로 원하는 애니메이션을 적용하고 transition으로 애니메이션을 구동하면 됩니다.

svg
  .selectAll(".bar")
  .data(data)
  .join("rect")
  .attr("class", "bar")
  .attr("x", (value, index) => xScale(index))
  .attr("y", -150) // 뒤집었으므로 svg viewBox의 height 만큼 빼워야 함
  .attr("width", xScale.bandwidth())
  .style("transform", "scale(1, -1)") // upside-down 뒤집기
  .transition() // 애니메이션 적용
  .attr("height", (value, index) => 150 - yScale(value));

 

2.

 

일정 크기마다 값을 다르게 해보겠습니다.

0에 가까울수록 green, 150에 가까울수록 red를 지정하겠습니다.

const colorScale = scaleLinear().domain([0, 150]).range(["green", "red"]);

 

transition 메서드의 위치에 주의합시다. 색이 바뀌는 게 animation이 아니라 단순히 바뀌기만 한다면 fill 속성을 부여하는 부분을 transition 이후로 옮겨 줍시다.

svg
  .selectAll(".bar")
  .data(data)
  .join("rect")
  .attr("class", "bar")
  .attr("x", (value, index) => xScale(index))
  .attr("y", -150) 
  .attr("width", xScale.bandwidth())
  .style("transform", "scale(1, -1)") 
  .transition() // transition 메서드의 위치가 중요함.
  .attr("fill", colorScale) // color 더해줌
  .attr("height", (value, index) => 150 - yScale(value));

 

색이 적절하지 않으므로 30, 50, 150와 같이 구간을 나워 다른 색을 지정하면 좀 더 자연스러운 색을 연출할 수 있습니다.

const colorScale = scaleLinear()
  .domain([30, 50, 150])
  .range(["green", "orange", "red"])
  .clamp(true);

 

clamp

If clamping is disabled and the scale is passed a value outside the domain, the scale may return a value outside the range through extrapolation. If clamping is enabled, the return value of the scale is always within the scale’s range. Clamping similarly applies to the "invert" method.